content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Testing for external resource consistency / skipping django tests I'm writing tests for a Django application that uses an external data source. Obviously, I'm using fake data to test all the inner workings of my class but I'd like to have a couple of tests for the actual fetcher as well. One of these will need to verify that the external source is still sending the data in the format my application expects, which will mean making the request to retrieve that information in the test. Obviously, I don't want our CI to come down when there is a network problem or the data provider has a spot of downtime. In this case, I would like to throw a warning that skips the rest of that test method and doesn't contribute to an overall failure. This way, if the data arrives successfully I can check it for consistency (failing if there is a problem) but if the data cannot be fetched it logs a warning so I (or another developer) know to quickly check that the data source is ok. Basically, I would like to test my external source without being dependant on it! Django's test suite uses Python's unittest module (at least, that's how I'm using it) which looks useful, given that the documentation for it describes Skipping tests and expected failures. This feature is apparently 'new in version 2.7', which explains why I can't get it to work - I've checked the version of unittest I have installed on from the console and it appears to be 1.63! I can't find a later version of unittest in pypi so I'm wondering where I can get hold of the unittest version described in that document and whether it will work with Django (1.2). I'm obviously open to recommendations / discussion on whether or not this is the best approach to my problem :) [EDIT - additional information / clarification] As I said, I'm obviously mocking the dependancy and doing my tests on that. However, I would also like to be able to check that the external resource (which typically is going to be an API) still matches my expected format, without bringing down CI if there is a network problem or their server is temporarily down. I basically just want to check the consistency of the resource. Consider the following case... If you have written a Twitter application, you will have tests for all your application's methods and behaviours - these will use fake Twitter data. This gives you a complete, self-contained set of tests for your application. The problem is that this doesn't actually check that the application works because your application inherently depends on the consistency of Twitter's API. If Twitter were to change an API call (perhaps change the URL, the parameters or the response) the application would stop working even though the unit tests would still pass. (Or perhaps if they were to completely switch off basic authentication!) My use case is simpler - I have a single xml resource that is used to import information. I have faked the resource and tested my import code but I would like to have a test that checks the format of that xml resource has not changed. My question is about skipping tests in Django's test runner so I can throw a warning if the resource is unavailable without the tests failing, specifically getting a version of Python's unittest module that supports this behaviour. I've given this much background information to allow anyone with experience in this area to offer alternative suggestions. Apologies for the lengthy question, I'm aware most people won't read this now. I've 'bolded' the important bits to make it easier to read. A: I created a separate answer since your edit invalidated my last answer. I assume you're running on Python version 2.6 - I believe the changes that you're looking for in unittest are available in Python version 2.7. Since unittest is in the standard library, updating to Python 2.7 should make those changes available to you. Is that an option that will work for you? One other thing that I might suggest is to maybe separate the "external source format verification" test(s) into a separate test suite and run that separately from the rest of your unit tests. That way your core unit tests are still fast and you don't have to worry about the external dependencies breaking your main test suites. If you're using Hudson, it should be fairly easy to create a separate job that will handle those tests for you. Just a suggestion. A: The new features in unittest in 2.7 have been backported to 2.6 as unittest2. You can just pip install and substitute unittest2 for unittest and your tests will work as thyey did plus you get the new features without upgrading to 2.7. A: What are you trying to test? The code in your Django application(s) or the dependency? Can you just Mock whatever that external dependency is? If you're just wanting to test your Django application, then I would say Mock the external dependency, so your tests are not dependent upon that external resource's availability. If you can post some code of your "actual fetcher" maybe you will get some tips on how you could use mocks.
Testing for external resource consistency / skipping django tests
I'm writing tests for a Django application that uses an external data source. Obviously, I'm using fake data to test all the inner workings of my class but I'd like to have a couple of tests for the actual fetcher as well. One of these will need to verify that the external source is still sending the data in the format my application expects, which will mean making the request to retrieve that information in the test. Obviously, I don't want our CI to come down when there is a network problem or the data provider has a spot of downtime. In this case, I would like to throw a warning that skips the rest of that test method and doesn't contribute to an overall failure. This way, if the data arrives successfully I can check it for consistency (failing if there is a problem) but if the data cannot be fetched it logs a warning so I (or another developer) know to quickly check that the data source is ok. Basically, I would like to test my external source without being dependant on it! Django's test suite uses Python's unittest module (at least, that's how I'm using it) which looks useful, given that the documentation for it describes Skipping tests and expected failures. This feature is apparently 'new in version 2.7', which explains why I can't get it to work - I've checked the version of unittest I have installed on from the console and it appears to be 1.63! I can't find a later version of unittest in pypi so I'm wondering where I can get hold of the unittest version described in that document and whether it will work with Django (1.2). I'm obviously open to recommendations / discussion on whether or not this is the best approach to my problem :) [EDIT - additional information / clarification] As I said, I'm obviously mocking the dependancy and doing my tests on that. However, I would also like to be able to check that the external resource (which typically is going to be an API) still matches my expected format, without bringing down CI if there is a network problem or their server is temporarily down. I basically just want to check the consistency of the resource. Consider the following case... If you have written a Twitter application, you will have tests for all your application's methods and behaviours - these will use fake Twitter data. This gives you a complete, self-contained set of tests for your application. The problem is that this doesn't actually check that the application works because your application inherently depends on the consistency of Twitter's API. If Twitter were to change an API call (perhaps change the URL, the parameters or the response) the application would stop working even though the unit tests would still pass. (Or perhaps if they were to completely switch off basic authentication!) My use case is simpler - I have a single xml resource that is used to import information. I have faked the resource and tested my import code but I would like to have a test that checks the format of that xml resource has not changed. My question is about skipping tests in Django's test runner so I can throw a warning if the resource is unavailable without the tests failing, specifically getting a version of Python's unittest module that supports this behaviour. I've given this much background information to allow anyone with experience in this area to offer alternative suggestions. Apologies for the lengthy question, I'm aware most people won't read this now. I've 'bolded' the important bits to make it easier to read.
[ "I created a separate answer since your edit invalidated my last answer.\nI assume you're running on Python version 2.6 - I believe the changes that you're looking for in unittest are available in Python version 2.7. Since unittest is in the standard library, updating to Python 2.7 should make those changes availa...
[ 1, 1, 0 ]
[]
[]
[ "django", "python", "skip", "unit_testing" ]
stackoverflow_0003240049_django_python_skip_unit_testing.txt
Q: Sorting list that has tuple as an element with Python I have a list as follows. [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)] How can I sort the list to get [1,2,3,4,5,6,7,8] or [8,7,6,5,4,3,2,1] ? A: Convert the list of tuples into a list of integers, then sort it: thelist = [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)] sortedlist = sorted([x[0] for x in thelist]) print sortedlist See it on codepad A: I'll give you an even more generalized answer: from itertools import chain sorted( chain.from_iterable( myList ) ) which can sort not only what you've asked for but also any list of arbitrary length tuples. A: datalist = [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)] sorteddata = sorted(data for listitem in datalist for data in listitem) reversedsorted = sorteddata[::-1] print sorteddata print reversedsorted # Also print 'With zip', sorted(zip(*datalist)[0])
Sorting list that has tuple as an element with Python
I have a list as follows. [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)] How can I sort the list to get [1,2,3,4,5,6,7,8] or [8,7,6,5,4,3,2,1] ?
[ "Convert the list of tuples into a list of integers, then sort it:\nthelist = [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]\n\nsortedlist = sorted([x[0] for x in thelist])\n\nprint sortedlist\n\nSee it on codepad\n", "I'll give you an even more generalized answer:\nfrom itertools import chain\nsorted( chain.fr...
[ 4, 1, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003689830_python_sorting.txt
Q: Use of ctypes module I need to program VIX API of VMware. It´s a dll wrote with C functions... I want program in python calling this functions using ctypes and I don´t understand the documentation of ctypes in python web page... Can someone give some samples with how to do this???? Thanks, A: I've been meaning to do something like this for a while. I downloaded the VIX API kit, and extracted the vix.h file, containing all of the VIX API function prototypes. I then wrote a short pyparsing parser to extract the typedefs and function declarations, and convert them to ctypes definitions. With these definitions, you'll be able to invoke the VIX methods from the VIX dll (the lib's are not needed, only the dll is used by ctypes). Extract this code to a suitably-named Python module (vixlib.py, for instance), and then import this module into any Python script to use VIX: from ctypes import * # if on Windows, may need to change following to use WinDLL instead of CDLL vix = CDLL('vix.dll') # user defined types VixHandle = c_int VixHandleType = c_int VixError = c_uint64 VixPropertyType = c_int VixPropertyID = c_int VixEventType = c_int VixHostOptions = c_int VixServiceProvider = c_int VixFindItemType = c_int VixVMOpenOptions = c_int VixPumpEventsOptions = c_int VixVMPowerOpOptions = c_int VixVMDeleteOptions = c_int VixPowerState = c_int VixToolsState = c_int VixRunProgramOptions = c_int VixRemoveSnapshotOptions = c_int VixCreateSnapshotOptions = c_int VixMsgSharedFolderOptions = c_int VixCloneType = c_int VixEventProc = CFUNCTYPE(VixHandle, VixEventType, VixHandle, c_void_p) # constant definitions VIX_INVALID_HANDLE = 0 VIX_HANDLETYPE_NONE = 0 VIX_HANDLETYPE_HOST = 2 VIX_HANDLETYPE_VM = 3 VIX_HANDLETYPE_NETWORK = 5 VIX_HANDLETYPE_JOB = 6 VIX_HANDLETYPE_SNAPSHOT = 7 VIX_HANDLETYPE_PROPERTY_LIST = 9 VIX_HANDLETYPE_METADATA_CONTAINER = 11 VIX_OK = 0 VIX_E_FAIL = 1 VIX_E_OUT_OF_MEMORY = 2 VIX_E_INVALID_ARG = 3 VIX_E_FILE_NOT_FOUND = 4 VIX_E_OBJECT_IS_BUSY = 5 VIX_E_NOT_SUPPORTED = 6 VIX_E_FILE_ERROR = 7 VIX_E_DISK_FULL = 8 VIX_E_INCORRECT_FILE_TYPE = 9 VIX_E_CANCELLED = 10 VIX_E_FILE_READ_ONLY = 11 VIX_E_FILE_ALREADY_EXISTS = 12 VIX_E_FILE_ACCESS_ERROR = 13 VIX_E_REQUIRES_LARGE_FILES = 14 VIX_E_FILE_ALREADY_LOCKED = 15 VIX_E_VMDB = 16 VIX_E_NOT_SUPPORTED_ON_REMOTE_OBJECT = 20 VIX_E_FILE_TOO_BIG = 21 VIX_E_FILE_NAME_INVALID = 22 VIX_E_ALREADY_EXISTS = 23 VIX_E_BUFFER_TOOSMALL = 24 VIX_E_OBJECT_NOT_FOUND = 25 VIX_E_HOST_NOT_CONNECTED = 26 VIX_E_INVALID_UTF8_STRING = 27 VIX_E_OPERATION_ALREADY_IN_PROGRESS = 31 VIX_E_UNFINISHED_JOB = 29 VIX_E_NEED_KEY = 30 VIX_E_LICENSE = 32 VIX_E_VM_HOST_DISCONNECTED = 34 VIX_E_AUTHENTICATION_FAIL = 35 VIX_E_HOST_CONNECTION_LOST = 36 VIX_E_DUPLICATE_NAME = 41 VIX_E_INVALID_HANDLE = 1000 VIX_E_NOT_SUPPORTED_ON_HANDLE_TYPE = 1001 VIX_E_TOO_MANY_HANDLES = 1002 VIX_E_NOT_FOUND = 2000 VIX_E_TYPE_MISMATCH = 2001 VIX_E_INVALID_XML = 2002 VIX_E_TIMEOUT_WAITING_FOR_TOOLS = 3000 VIX_E_UNRECOGNIZED_COMMAND = 3001 VIX_E_OP_NOT_SUPPORTED_ON_GUEST = 3003 VIX_E_PROGRAM_NOT_STARTED = 3004 VIX_E_CANNOT_START_READ_ONLY_VM = 3005 VIX_E_VM_NOT_RUNNING = 3006 VIX_E_VM_IS_RUNNING = 3007 VIX_E_CANNOT_CONNECT_TO_VM = 3008 VIX_E_POWEROP_SCRIPTS_NOT_AVAILABLE = 3009 VIX_E_NO_GUEST_OS_INSTALLED = 3010 VIX_E_VM_INSUFFICIENT_HOST_MEMORY = 3011 VIX_E_SUSPEND_ERROR = 3012 VIX_E_VM_NOT_ENOUGH_CPUS = 3013 VIX_E_HOST_USER_PERMISSIONS = 3014 VIX_E_GUEST_USER_PERMISSIONS = 3015 VIX_E_TOOLS_NOT_RUNNING = 3016 VIX_E_GUEST_OPERATIONS_PROHIBITED = 3017 VIX_E_ANON_GUEST_OPERATIONS_PROHIBITED = 3018 VIX_E_ROOT_GUEST_OPERATIONS_PROHIBITED = 3019 VIX_E_MISSING_ANON_GUEST_ACCOUNT = 3023 VIX_E_CANNOT_AUTHENTICATE_WITH_GUEST = 3024 VIX_E_UNRECOGNIZED_COMMAND_IN_GUEST = 3025 VIX_E_CONSOLE_GUEST_OPERATIONS_PROHIBITED = 3026 VIX_E_MUST_BE_CONSOLE_USER = 3027 VIX_E_VMX_MSG_DIALOG_AND_NO_UI = 3028 VIX_E_NOT_ALLOWED_DURING_VM_RECORDING = 3029 VIX_E_NOT_ALLOWED_DURING_VM_REPLAY = 3030 VIX_E_OPERATION_NOT_ALLOWED_FOR_LOGIN_TYPE = 3031 VIX_E_LOGIN_TYPE_NOT_SUPPORTED = 3032 VIX_E_EMPTY_PASSWORD_NOT_ALLOWED_IN_GUEST = 3033 VIX_E_INTERACTIVE_SESSION_NOT_PRESENT = 3034 VIX_E_INTERACTIVE_SESSION_USER_MISMATCH = 3035 VIX_E_UNABLE_TO_REPLAY_VM = 3039 VIX_E_CANNOT_POWER_ON_VM = 3041 VIX_E_NO_DISPLAY_SERVER = 3043 VIX_E_VM_NOT_RECORDING = 3044 VIX_E_VM_NOT_REPLAYING = 3045 VIX_E_VM_NOT_FOUND = 4000 VIX_E_NOT_SUPPORTED_FOR_VM_VERSION = 4001 VIX_E_CANNOT_READ_VM_CONFIG = 4002 VIX_E_TEMPLATE_VM = 4003 VIX_E_VM_ALREADY_LOADED = 4004 VIX_E_VM_ALREADY_UP_TO_DATE = 4006 VIX_E_VM_UNSUPPORTED_GUEST = 4011 VIX_E_UNRECOGNIZED_PROPERTY = 6000 VIX_E_INVALID_PROPERTY_VALUE = 6001 VIX_E_READ_ONLY_PROPERTY = 6002 VIX_E_MISSING_REQUIRED_PROPERTY = 6003 VIX_E_INVALID_SERIALIZED_DATA = 6004 VIX_E_PROPERTY_TYPE_MISMATCH = 6005 VIX_E_BAD_VM_INDEX = 8000 VIX_E_INVALID_MESSAGE_HEADER = 10000 VIX_E_INVALID_MESSAGE_BODY = 10001 VIX_E_SNAPSHOT_INVAL = 13000 VIX_E_SNAPSHOT_DUMPER = 13001 VIX_E_SNAPSHOT_DISKLIB = 13002 VIX_E_SNAPSHOT_NOTFOUND = 13003 VIX_E_SNAPSHOT_EXISTS = 13004 VIX_E_SNAPSHOT_VERSION = 13005 VIX_E_SNAPSHOT_NOPERM = 13006 VIX_E_SNAPSHOT_CONFIG = 13007 VIX_E_SNAPSHOT_NOCHANGE = 13008 VIX_E_SNAPSHOT_CHECKPOINT = 13009 VIX_E_SNAPSHOT_LOCKED = 13010 VIX_E_SNAPSHOT_INCONSISTENT = 13011 VIX_E_SNAPSHOT_NAMETOOLONG = 13012 VIX_E_SNAPSHOT_VIXFILE = 13013 VIX_E_SNAPSHOT_DISKLOCKED = 13014 VIX_E_SNAPSHOT_DUPLICATEDDISK = 13015 VIX_E_SNAPSHOT_INDEPENDENTDISK = 13016 VIX_E_SNAPSHOT_NONUNIQUE_NAME = 13017 VIX_E_SNAPSHOT_MEMORY_ON_INDEPENDENT_DISK = 13018 VIX_E_SNAPSHOT_MAXSNAPSHOTS = 13019 VIX_E_SNAPSHOT_MIN_FREE_SPACE = 13020 VIX_E_SNAPSHOT_HIERARCHY_TOODEEP = 13021 VIX_E_HOST_DISK_INVALID_VALUE = 14003 VIX_E_HOST_DISK_SECTORSIZE = 14004 VIX_E_HOST_FILE_ERROR_EOF = 14005 VIX_E_HOST_NETBLKDEV_HANDSHAKE = 14006 VIX_E_HOST_SOCKET_CREATION_ERROR = 14007 VIX_E_HOST_SERVER_NOT_FOUND = 14008 VIX_E_HOST_NETWORK_CONN_REFUSED = 14009 VIX_E_HOST_TCP_SOCKET_ERROR = 14010 VIX_E_HOST_TCP_CONN_LOST = 14011 VIX_E_HOST_NBD_HASHFILE_VOLUME = 14012 VIX_E_HOST_NBD_HASHFILE_INIT = 14013 VIX_E_DISK_INVAL = 16000 VIX_E_DISK_NOINIT = 16001 VIX_E_DISK_NOIO = 16002 VIX_E_DISK_PARTIALCHAIN = 16003 VIX_E_DISK_NEEDSREPAIR = 16006 VIX_E_DISK_OUTOFRANGE = 16007 VIX_E_DISK_CID_MISMATCH = 16008 VIX_E_DISK_CANTSHRINK = 16009 VIX_E_DISK_PARTMISMATCH = 16010 VIX_E_DISK_UNSUPPORTEDDISKVERSION = 16011 VIX_E_DISK_OPENPARENT = 16012 VIX_E_DISK_NOTSUPPORTED = 16013 VIX_E_DISK_NEEDKEY = 16014 VIX_E_DISK_NOKEYOVERRIDE = 16015 VIX_E_DISK_NOTENCRYPTED = 16016 VIX_E_DISK_NOKEY = 16017 VIX_E_DISK_INVALIDPARTITIONTABLE = 16018 VIX_E_DISK_NOTNORMAL = 16019 VIX_E_DISK_NOTENCDESC = 16020 VIX_E_DISK_NEEDVMFS = 16022 VIX_E_DISK_RAWTOOBIG = 16024 VIX_E_DISK_TOOMANYOPENFILES = 16027 VIX_E_DISK_TOOMANYREDO = 16028 VIX_E_DISK_RAWTOOSMALL = 16029 VIX_E_DISK_INVALIDCHAIN = 16030 VIX_E_DISK_KEY_NOTFOUND = 16052 VIX_E_DISK_SUBSYSTEM_INIT_FAIL = 16053 VIX_E_DISK_INVALID_CONNECTION = 16054 VIX_E_DISK_ENCODING = 16061 VIX_E_DISK_CANTREPAIR = 16062 VIX_E_DISK_INVALIDDISK = 16063 VIX_E_DISK_NOLICENSE = 16064 VIX_E_DISK_NODEVICE = 16065 VIX_E_DISK_UNSUPPORTEDDEVICE = 16066 VIX_E_CRYPTO_UNKNOWN_ALGORITHM = 17000 VIX_E_CRYPTO_BAD_BUFFER_SIZE = 17001 VIX_E_CRYPTO_INVALID_OPERATION = 17002 VIX_E_CRYPTO_RANDOM_DEVICE = 17003 VIX_E_CRYPTO_NEED_PASSWORD = 17004 VIX_E_CRYPTO_BAD_PASSWORD = 17005 VIX_E_CRYPTO_NOT_IN_DICTIONARY = 17006 VIX_E_CRYPTO_NO_CRYPTO = 17007 VIX_E_CRYPTO_ERROR = 17008 VIX_E_CRYPTO_BAD_FORMAT = 17009 VIX_E_CRYPTO_LOCKED = 17010 VIX_E_CRYPTO_EMPTY = 17011 VIX_E_CRYPTO_KEYSAFE_LOCATOR = 17012 VIX_E_CANNOT_CONNECT_TO_HOST = 18000 VIX_E_NOT_FOR_REMOTE_HOST = 18001 VIX_E_INVALID_HOSTNAME_SPECIFICATION = 18002 VIX_E_SCREEN_CAPTURE_ERROR = 19000 VIX_E_SCREEN_CAPTURE_BAD_FORMAT = 19001 VIX_E_SCREEN_CAPTURE_COMPRESSION_FAIL = 19002 VIX_E_SCREEN_CAPTURE_LARGE_DATA = 19003 VIX_E_GUEST_VOLUMES_NOT_FROZEN = 20000 VIX_E_NOT_A_FILE = 20001 VIX_E_NOT_A_DIRECTORY = 20002 VIX_E_NO_SUCH_PROCESS = 20003 VIX_E_FILE_NAME_TOO_LONG = 20004 VIX_E_TOOLS_INSTALL_NO_IMAGE = 21000 VIX_E_TOOLS_INSTALL_IMAGE_INACCESIBLE = 21001 VIX_E_TOOLS_INSTALL_NO_DEVICE = 21002 VIX_E_TOOLS_INSTALL_DEVICE_NOT_CONNECTED = 21003 VIX_E_TOOLS_INSTALL_CANCELLED = 21004 VIX_E_TOOLS_INSTALL_INIT_FAILED = 21005 VIX_E_TOOLS_INSTALL_AUTO_NOT_SUPPORTED = 21006 VIX_E_TOOLS_INSTALL_GUEST_NOT_READY = 21007 VIX_E_TOOLS_INSTALL_SIG_CHECK_FAILED = 21008 VIX_E_TOOLS_INSTALL_ERROR = 21009 VIX_E_TOOLS_INSTALL_ALREADY_UP_TO_DATE = 21010 VIX_E_TOOLS_INSTALL_IN_PROGRESS = 21011 VIX_E_WRAPPER_WORKSTATION_NOT_INSTALLED = 22001 VIX_E_WRAPPER_VERSION_NOT_FOUND = 22002 VIX_E_WRAPPER_SERVICEPROVIDER_NOT_FOUND = 22003 VIX_E_WRAPPER_PLAYER_NOT_INSTALLED = 22004 VIX_E_WRAPPER_RUNTIME_NOT_INSTALLED = 22005 VIX_E_WRAPPER_MULTIPLE_SERVICEPROVIDERS = 22006 VIX_E_MNTAPI_MOUNTPT_NOT_FOUND = 24000 VIX_E_MNTAPI_MOUNTPT_IN_USE = 24001 VIX_E_MNTAPI_DISK_NOT_FOUND = 24002 VIX_E_MNTAPI_DISK_NOT_MOUNTED = 24003 VIX_E_MNTAPI_DISK_IS_MOUNTED = 24004 VIX_E_MNTAPI_DISK_NOT_SAFE = 24005 VIX_E_MNTAPI_DISK_CANT_OPEN = 24006 VIX_E_MNTAPI_CANT_READ_PARTS = 24007 VIX_E_MNTAPI_UMOUNT_APP_NOT_FOUND = 24008 VIX_E_MNTAPI_UMOUNT = 24009 VIX_E_MNTAPI_NO_MOUNTABLE_PARTITONS = 24010 VIX_E_MNTAPI_PARTITION_RANGE = 24011 VIX_E_MNTAPI_PERM = 24012 VIX_E_MNTAPI_DICT = 24013 VIX_E_MNTAPI_DICT_LOCKED = 24014 VIX_E_MNTAPI_OPEN_HANDLES = 24015 VIX_E_MNTAPI_CANT_MAKE_VAR_DIR = 24016 VIX_E_MNTAPI_NO_ROOT = 24017 VIX_E_MNTAPI_LOOP_FAILED = 24018 VIX_E_MNTAPI_DAEMON = 24019 VIX_E_MNTAPI_INTERNAL = 24020 VIX_E_MNTAPI_SYSTEM = 24021 VIX_E_MNTAPI_NO_CONNECTION_DETAILS = 24022 VIX_E_MNTAPI_INCOMPATIBLE_VERSION = 24300 VIX_E_MNTAPI_OS_ERROR = 24301 VIX_E_MNTAPI_DRIVE_LETTER_IN_USE = 24302 VIX_E_MNTAPI_DRIVE_LETTER_ALREADY_ASSIGNED = 24303 VIX_E_MNTAPI_VOLUME_NOT_MOUNTED = 24304 VIX_E_MNTAPI_VOLUME_ALREADY_MOUNTED = 24305 VIX_E_MNTAPI_FORMAT_FAILURE = 24306 VIX_E_MNTAPI_NO_DRIVER = 24307 VIX_E_MNTAPI_ALREADY_OPENED = 24308 VIX_E_MNTAPI_ITEM_NOT_FOUND = 24309 VIX_E_MNTAPI_UNSUPPROTED_BOOT_LOADER = 24310 VIX_E_MNTAPI_UNSUPPROTED_OS = 24311 VIX_E_MNTAPI_CODECONVERSION = 24312 VIX_E_MNTAPI_REGWRITE_ERROR = 24313 VIX_E_MNTAPI_UNSUPPORTED_FT_VOLUME = 24314 VIX_E_MNTAPI_PARTITION_NOT_FOUND = 24315 VIX_E_MNTAPI_PUTFILE_ERROR = 24316 VIX_E_MNTAPI_GETFILE_ERROR = 24317 VIX_E_MNTAPI_REG_NOT_OPENED = 24318 VIX_E_MNTAPI_REGDELKEY_ERROR = 24319 VIX_E_MNTAPI_CREATE_PARTITIONTABLE_ERROR = 24320 VIX_E_MNTAPI_OPEN_FAILURE = 24321 VIX_E_MNTAPI_VOLUME_NOT_WRITABLE = 24322 VIX_E_NET_HTTP_UNSUPPORTED_PROTOCOL = 30001 VIX_E_NET_HTTP_URL_MALFORMAT = 30003 VIX_E_NET_HTTP_COULDNT_RESOLVE_PROXY = 30005 VIX_E_NET_HTTP_COULDNT_RESOLVE_HOST = 30006 VIX_E_NET_HTTP_COULDNT_CONNECT = 30007 VIX_E_NET_HTTP_HTTP_RETURNED_ERROR = 30022 VIX_E_NET_HTTP_OPERATION_TIMEDOUT = 30028 VIX_E_NET_HTTP_SSL_CONNECT_ERROR = 30035 VIX_E_NET_HTTP_TOO_MANY_REDIRECTS = 30047 VIX_E_NET_HTTP_TRANSFER = 30200 VIX_E_NET_HTTP_SSL_SECURITY = 30201 VIX_E_NET_HTTP_GENERIC = 30202 VIX_PROPERTYTYPE_ANY = 0 VIX_PROPERTYTYPE_INTEGER = 1 VIX_PROPERTYTYPE_STRING = 2 VIX_PROPERTYTYPE_BOOL = 3 VIX_PROPERTYTYPE_HANDLE = 4 VIX_PROPERTYTYPE_INT64 = 5 VIX_PROPERTYTYPE_BLOB = 6 VIX_PROPERTY_NONE = 0 VIX_PROPERTY_META_DATA_CONTAINER = 2 VIX_PROPERTY_HOST_HOSTTYPE = 50 VIX_PROPERTY_HOST_API_VERSION = 51 VIX_PROPERTY_VM_NUM_VCPUS = 101 VIX_PROPERTY_VM_VMX_PATHNAME = 103 VIX_PROPERTY_VM_VMTEAM_PATHNAME = 105 VIX_PROPERTY_VM_MEMORY_SIZE = 106 VIX_PROPERTY_VM_READ_ONLY = 107 VIX_PROPERTY_VM_NAME = 108 VIX_PROPERTY_VM_GUESTOS = 109 VIX_PROPERTY_VM_IN_VMTEAM = 128 VIX_PROPERTY_VM_POWER_STATE = 129 VIX_PROPERTY_VM_TOOLS_STATE = 152 VIX_PROPERTY_VM_IS_RUNNING = 196 VIX_PROPERTY_VM_SUPPORTED_FEATURES = 197 VIX_PROPERTY_VM_IS_RECORDING = 236 VIX_PROPERTY_VM_IS_REPLAYING = 237 VIX_PROPERTY_JOB_RESULT_ERROR_CODE = 3000 VIX_PROPERTY_JOB_RESULT_VM_IN_GROUP = 3001 VIX_PROPERTY_JOB_RESULT_USER_MESSAGE = 3002 VIX_PROPERTY_JOB_RESULT_EXIT_CODE = 3004 VIX_PROPERTY_JOB_RESULT_COMMAND_OUTPUT = 3005 VIX_PROPERTY_JOB_RESULT_HANDLE = 3010 VIX_PROPERTY_JOB_RESULT_GUEST_OBJECT_EXISTS = 3011 VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_ELAPSED_TIME = 3017 VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_EXIT_CODE = 3018 VIX_PROPERTY_JOB_RESULT_ITEM_NAME = 3035 VIX_PROPERTY_JOB_RESULT_FOUND_ITEM_DESCRIPTION = 3036 VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_COUNT = 3046 VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_HOST = 3048 VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_FLAGS = 3049 VIX_PROPERTY_JOB_RESULT_PROCESS_ID = 3051 VIX_PROPERTY_JOB_RESULT_PROCESS_OWNER = 3052 VIX_PROPERTY_JOB_RESULT_PROCESS_COMMAND = 3053 VIX_PROPERTY_JOB_RESULT_FILE_FLAGS = 3054 VIX_PROPERTY_JOB_RESULT_PROCESS_START_TIME = 3055 VIX_PROPERTY_JOB_RESULT_VM_VARIABLE_STRING = 3056 VIX_PROPERTY_JOB_RESULT_PROCESS_BEING_DEBUGGED = 3057 VIX_PROPERTY_JOB_RESULT_SCREEN_IMAGE_SIZE = 3058 VIX_PROPERTY_JOB_RESULT_SCREEN_IMAGE_DATA = 3059 VIX_PROPERTY_JOB_RESULT_FILE_SIZE = 3061 VIX_PROPERTY_JOB_RESULT_FILE_MOD_TIME = 3062 VIX_PROPERTY_JOB_RESULT_EXTRA_ERROR_INFO = 3084 VIX_PROPERTY_FOUND_ITEM_LOCATION = 4010 VIX_PROPERTY_SNAPSHOT_DISPLAYNAME = 4200 VIX_PROPERTY_SNAPSHOT_DESCRIPTION = 4201 VIX_PROPERTY_SNAPSHOT_POWERSTATE = 4205 VIX_PROPERTY_SNAPSHOT_IS_REPLAYABLE = 4207 VIX_PROPERTY_GUEST_SHAREDFOLDERS_SHARES_PATH = 4525 VIX_PROPERTY_VM_ENCRYPTION_PASSWORD = 7001 VIX_EVENTTYPE_JOB_COMPLETED = 2 VIX_EVENTTYPE_JOB_PROGRESS = 3 VIX_EVENTTYPE_FIND_ITEM = 8 VIX_EVENTTYPE_CALLBACK_SIGNALLED = 2 VIX_FILE_ATTRIBUTES_DIRECTORY = 0x0001 VIX_FILE_ATTRIBUTES_SYMLINK = 0x0002 VIX_HOSTOPTION_USE_EVENT_PUMP = 0x0008 VIX_SERVICEPROVIDER_DEFAULT = 1 VIX_SERVICEPROVIDER_VMWARE_SERVER = 2 VIX_SERVICEPROVIDER_VMWARE_WORKSTATION = 3 VIX_SERVICEPROVIDER_VMWARE_PLAYER = 4 VIX_SERVICEPROVIDER_VMWARE_VI_SERVER = 10 VIX_API_VERSION = -1 VIX_FIND_RUNNING_VMS = 1 VIX_FIND_REGISTERED_VMS = 4 VIX_VMOPEN_NORMAL = 0x0 VIX_PUMPEVENTOPTION_NONE = 0 VIX_VMPOWEROP_NORMAL = 0 VIX_VMPOWEROP_FROM_GUEST = 0x0004 VIX_VMPOWEROP_SUPPRESS_SNAPSHOT_POWERON = 0x0080 VIX_VMPOWEROP_LAUNCH_GUI = 0x0200 VIX_VMPOWEROP_START_VM_PAUSED = 0x1000 VIX_VMDELETE_DISK_FILES = 0x0002 VIX_POWERSTATE_POWERING_OFF = 0x0001 VIX_POWERSTATE_POWERED_OFF = 0x0002 VIX_POWERSTATE_POWERING_ON = 0x0004 VIX_POWERSTATE_POWERED_ON = 0x0008 VIX_POWERSTATE_SUSPENDING = 0x0010 VIX_POWERSTATE_SUSPENDED = 0x0020 VIX_POWERSTATE_TOOLS_RUNNING = 0x0040 VIX_POWERSTATE_RESETTING = 0x0080 VIX_POWERSTATE_BLOCKED_ON_MSG = 0x0100 VIX_POWERSTATE_PAUSED = 0x0200 VIX_POWERSTATE_RESUMING = 0x0800 VIX_TOOLSSTATE_UNKNOWN = 0x0001 VIX_TOOLSSTATE_RUNNING = 0x0002 VIX_TOOLSSTATE_NOT_INSTALLED = 0x0004 VIX_VM_SUPPORT_SHARED_FOLDERS = 0x0001 VIX_VM_SUPPORT_MULTIPLE_SNAPSHOTS = 0x0002 VIX_VM_SUPPORT_TOOLS_INSTALL = 0x0004 VIX_VM_SUPPORT_HARDWARE_UPGRADE = 0x0008 VIX_LOGIN_IN_GUEST_REQUIRE_INTERACTIVE_ENVIRONMENT = 0x08 VIX_RUNPROGRAM_RETURN_IMMEDIATELY = 0x0001 VIX_RUNPROGRAM_ACTIVATE_WINDOW = 0x0002 VIX_VM_GUEST_VARIABLE = 1 VIX_VM_CONFIG_RUNTIME_ONLY = 2 VIX_GUEST_ENVIRONMENT_VARIABLE = 3 VIX_SNAPSHOT_REMOVE_CHILDREN = 0x0001 VIX_SNAPSHOT_INCLUDE_MEMORY = 0x0002 VIX_SHAREDFOLDER_WRITE_ACCESS = 0x04 VIX_CAPTURESCREENFORMAT_PNG = 0x01 VIX_CAPTURESCREENFORMAT_PNG_NOCOMPRESS = 0x02 VIX_CLONETYPE_FULL = 0 VIX_CLONETYPE_LINKED = 1 VIX_INSTALLTOOLS_MOUNT_TOOLS_INSTALLER = 0x00 VIX_INSTALLTOOLS_AUTO_UPGRADE = 0x01 VIX_INSTALLTOOLS_RETURN_IMMEDIATELY = 0x02 # functions vix.Vix_GetErrorText.restype = c_char_p vix.Vix_GetErrorText.argtypes = [VixError,c_char_p] vix.Vix_ReleaseHandle.restype = None vix.Vix_ReleaseHandle.argtypes = [VixHandle] vix.Vix_AddRefHandle.restype = None vix.Vix_AddRefHandle.argtypes = [VixHandle] vix.Vix_GetHandleType.restype = VixHandleType vix.Vix_GetHandleType.argtypes = [VixHandle] vix.Vix_GetProperties.restype = VixError # warning - vix.Vix_GetProperties takes variable argument list vix.Vix_GetProperties.argtypes = [VixHandle,VixPropertyID] vix.Vix_GetPropertyType.restype = VixError vix.Vix_GetPropertyType.argtypes = [VixHandle,VixPropertyID,POINTER(VixPropertyType)] vix.Vix_FreeBuffer.restype = None vix.Vix_FreeBuffer.argtypes = [c_void_p] vix.VixHost_Connect.restype = VixHandle vix.VixHost_Connect.argtypes = [c_int,VixServiceProvider,c_char_p,c_int,c_char_p,c_char_p,VixHostOptions,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixHost_Disconnect.restype = None vix.VixHost_Disconnect.argtypes = [VixHandle] vix.VixHost_RegisterVM.restype = VixHandle vix.VixHost_RegisterVM.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixHost_UnregisterVM.restype = VixHandle vix.VixHost_UnregisterVM.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixHost_FindItems.restype = VixHandle vix.VixHost_FindItems.argtypes = [VixHandle,VixFindItemType,VixHandle,c_int32,POINTER(VixEventProc),c_void_p] vix.VixHost_OpenVM.restype = VixHandle vix.VixHost_OpenVM.argtypes = [VixHandle,c_char_p,VixVMOpenOptions,VixHandle,POINTER(VixEventProc),c_void_p] vix.Vix_PumpEvents.restype = None vix.Vix_PumpEvents.argtypes = [VixHandle,VixPumpEventsOptions] vix.VixPropertyList_AllocPropertyList.restype = VixError # warning - vix.VixPropertyList_AllocPropertyList takes variable argument list vix.VixPropertyList_AllocPropertyList.argtypes = [VixHandle,POINTER(VixHandle),c_int] vix.VixVM_Open.restype = VixHandle vix.VixVM_Open.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixVM_PowerOn.restype = VixHandle vix.VixVM_PowerOn.argtypes = [VixHandle,VixVMPowerOpOptions,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_PowerOff.restype = VixHandle vix.VixVM_PowerOff.argtypes = [VixHandle,VixVMPowerOpOptions,POINTER(VixEventProc),c_void_p] vix.VixVM_Reset.restype = VixHandle vix.VixVM_Reset.argtypes = [VixHandle,VixVMPowerOpOptions,POINTER(VixEventProc),c_void_p] vix.VixVM_Suspend.restype = VixHandle vix.VixVM_Suspend.argtypes = [VixHandle,VixVMPowerOpOptions,POINTER(VixEventProc),c_void_p] vix.VixVM_Pause.restype = VixHandle vix.VixVM_Pause.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_Unpause.restype = VixHandle vix.VixVM_Unpause.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_Delete.restype = VixHandle vix.VixVM_Delete.argtypes = [VixHandle,VixVMDeleteOptions,POINTER(VixEventProc),c_void_p] vix.VixVM_BeginRecording.restype = VixHandle vix.VixVM_BeginRecording.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_EndRecording.restype = VixHandle vix.VixVM_EndRecording.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_BeginReplay.restype = VixHandle vix.VixVM_BeginReplay.argtypes = [VixHandle,VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_EndReplay.restype = VixHandle vix.VixVM_EndReplay.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_WaitForToolsInGuest.restype = VixHandle vix.VixVM_WaitForToolsInGuest.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_LoginInGuest.restype = VixHandle vix.VixVM_LoginInGuest.argtypes = [VixHandle,c_char_p,c_char_p,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_LogoutFromGuest.restype = VixHandle vix.VixVM_LogoutFromGuest.argtypes = [VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_RunProgramInGuest.restype = VixHandle vix.VixVM_RunProgramInGuest.argtypes = [VixHandle,c_char_p,c_char_p,VixRunProgramOptions,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_ListProcessesInGuest.restype = VixHandle vix.VixVM_ListProcessesInGuest.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_KillProcessInGuest.restype = VixHandle vix.VixVM_KillProcessInGuest.argtypes = [VixHandle,c_uint64,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_RunScriptInGuest.restype = VixHandle vix.VixVM_RunScriptInGuest.argtypes = [VixHandle,c_char_p,c_char_p,VixRunProgramOptions,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_OpenUrlInGuest.restype = VixHandle vix.VixVM_OpenUrlInGuest.argtypes = [VixHandle,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_CopyFileFromHostToGuest.restype = VixHandle vix.VixVM_CopyFileFromHostToGuest.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_CopyFileFromGuestToHost.restype = VixHandle vix.VixVM_CopyFileFromGuestToHost.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_DeleteFileInGuest.restype = VixHandle vix.VixVM_DeleteFileInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixVM_FileExistsInGuest.restype = VixHandle vix.VixVM_FileExistsInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixVM_RenameFileInGuest.restype = VixHandle vix.VixVM_RenameFileInGuest.argtypes = [VixHandle,c_char_p,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_CreateTempFileInGuest.restype = VixHandle vix.VixVM_CreateTempFileInGuest.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_GetFileInfoInGuest.restype = VixHandle vix.VixVM_GetFileInfoInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixVM_ListDirectoryInGuest.restype = VixHandle vix.VixVM_ListDirectoryInGuest.argtypes = [VixHandle,c_char_p,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_CreateDirectoryInGuest.restype = VixHandle vix.VixVM_CreateDirectoryInGuest.argtypes = [VixHandle,c_char_p,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_DeleteDirectoryInGuest.restype = VixHandle vix.VixVM_DeleteDirectoryInGuest.argtypes = [VixHandle,c_char_p,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_DirectoryExistsInGuest.restype = VixHandle vix.VixVM_DirectoryExistsInGuest.argtypes = [VixHandle,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixVM_ReadVariable.restype = VixHandle vix.VixVM_ReadVariable.argtypes = [VixHandle,c_int,c_char_p,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_WriteVariable.restype = VixHandle vix.VixVM_WriteVariable.argtypes = [VixHandle,c_int,c_char_p,c_char_p,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_GetNumRootSnapshots.restype = VixError vix.VixVM_GetNumRootSnapshots.argtypes = [VixHandle,POINTER(c_int)] vix.VixVM_GetRootSnapshot.restype = VixError vix.VixVM_GetRootSnapshot.argtypes = [VixHandle,c_int,POINTER(VixHandle)] vix.VixVM_GetCurrentSnapshot.restype = VixError vix.VixVM_GetCurrentSnapshot.argtypes = [VixHandle,POINTER(VixHandle)] vix.VixVM_GetNamedSnapshot.restype = VixError vix.VixVM_GetNamedSnapshot.argtypes = [VixHandle,c_char_p,POINTER(VixHandle)] vix.VixVM_RemoveSnapshot.restype = VixHandle vix.VixVM_RemoveSnapshot.argtypes = [VixHandle,VixHandle,VixRemoveSnapshotOptions,POINTER(VixEventProc),c_void_p] vix.VixVM_RevertToSnapshot.restype = VixHandle vix.VixVM_RevertToSnapshot.argtypes = [VixHandle,VixHandle,VixVMPowerOpOptions,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_CreateSnapshot.restype = VixHandle vix.VixVM_CreateSnapshot.argtypes = [VixHandle,c_char_p,c_char_p,VixCreateSnapshotOptions,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_EnableSharedFolders.restype = VixHandle vix.VixVM_EnableSharedFolders.argtypes = [VixHandle,c_byte,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_GetNumSharedFolders.restype = VixHandle vix.VixVM_GetNumSharedFolders.argtypes = [VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_GetSharedFolderState.restype = VixHandle vix.VixVM_GetSharedFolderState.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_SetSharedFolderState.restype = VixHandle vix.VixVM_SetSharedFolderState.argtypes = [VixHandle,c_char_p,c_char_p,VixMsgSharedFolderOptions,POINTER(VixEventProc),c_void_p] vix.VixVM_AddSharedFolder.restype = VixHandle vix.VixVM_AddSharedFolder.argtypes = [VixHandle,c_char_p,c_char_p,VixMsgSharedFolderOptions,POINTER(VixEventProc),c_void_p] vix.VixVM_RemoveSharedFolder.restype = VixHandle vix.VixVM_RemoveSharedFolder.argtypes = [VixHandle,c_char_p,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_CaptureScreenImage.restype = VixHandle vix.VixVM_CaptureScreenImage.argtypes = [VixHandle,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_Clone.restype = VixHandle vix.VixVM_Clone.argtypes = [VixHandle,VixHandle,VixCloneType,c_char_p,c_int,VixHandle,POINTER(VixEventProc),c_void_p] vix.VixVM_UpgradeVirtualHardware.restype = VixHandle vix.VixVM_UpgradeVirtualHardware.argtypes = [VixHandle,c_int,POINTER(VixEventProc),c_void_p] vix.VixVM_InstallTools.restype = VixHandle vix.VixVM_InstallTools.argtypes = [VixHandle,c_int,c_char_p,POINTER(VixEventProc),c_void_p] vix.VixJob_Wait.restype = VixError # warning - vix.VixJob_Wait takes variable argument list vix.VixJob_Wait.argtypes = [VixHandle,VixPropertyID] vix.VixJob_CheckCompletion.restype = VixError vix.VixJob_CheckCompletion.argtypes = [VixHandle,POINTER(c_byte)] vix.VixJob_GetError.restype = VixError vix.VixJob_GetError.argtypes = [VixHandle] vix.VixJob_GetNumProperties.restype = c_int vix.VixJob_GetNumProperties.argtypes = [VixHandle,c_int] vix.VixJob_GetNthProperties.restype = VixError # warning - vix.VixJob_GetNthProperties takes variable argument list vix.VixJob_GetNthProperties.argtypes = [VixHandle,c_int,c_int] vix.VixSnapshot_GetNumChildren.restype = VixError vix.VixSnapshot_GetNumChildren.argtypes = [VixHandle,POINTER(c_int)] vix.VixSnapshot_GetChild.restype = VixError vix.VixSnapshot_GetChild.argtypes = [VixHandle,c_int,POINTER(VixHandle)] vix.VixSnapshot_GetParent.restype = VixError vix.VixSnapshot_GetParent.argtypes = [VixHandle,POINTER(VixHandle)] A: The original tutorial is quite good. You are going to need to be more specific about what you don't understand. As a quick start: import ctypes PATH_DLL = "C:/path/to/vmware/dll.dll" dllLib = ctypes.cdll.LoadLibrary(PATH_DLL) someFunc = dllLib.funcExportedFromDLL ## what c function are you trying to use someFunc.restype = ctypes.c_long ## tell ctypes the expected return type of the C function returnValue = someFunc(ctypes.c_int(1), ctypes.c_double(1.0)) ## call the c function with ctypes converted args ...etc.. A: I suggest you write a extension module using Cython. It is a lot easier than using ctypes, and the results are way better. At least it segfaults less frequently.
Use of ctypes module
I need to program VIX API of VMware. It´s a dll wrote with C functions... I want program in python calling this functions using ctypes and I don´t understand the documentation of ctypes in python web page... Can someone give some samples with how to do this???? Thanks,
[ "I've been meaning to do something like this for a while. I downloaded the VIX API kit, and extracted the vix.h file, containing all of the VIX API function prototypes. I then wrote a short pyparsing parser to extract the typedefs and function declarations, and convert them to ctypes definitions. With these defi...
[ 3, 2, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003687762_ctypes_python.txt
Q: Writing white-space delimited text to be human readable in Python I have a list of lists that looks something like this: data = [['seq1', 'ACTAGACCCTAG'], ['sequence287653', 'ACTAGNACTGGG'], ['s9', 'ACTAGAAACTAG']] I write the information to a file like this: for i in data: for j in i: file.write('\t') file.write(j) file.write('\n') The output looks like this: seq1 ACTAGACCCTAG sequence287653 ACTAGNACTGGG s9 ACTAGAAACTAG The columns don't line up neatly because of variation in the length of the first element in each internal list. How can I write appropriate amounts of whitespace between the first and second elements to make the second column line up for human readability? A: You need a format string: for i,j in data: file.write('%-15s %s\n' % (i,j)) %-15s means left justify a 15-space field for a string. Here's the output: seq1 ACTAGACCCTAG sequence287653 ACTAGNACTGGG s9 ACTAGAAACTAG A: data = [['seq1', 'ACTAGACCCTAG'], ['sequence287653', 'ACTAGNACTGGG'], ['s9', 'ACTAGAAACTAG']] with open('myfile.txt', 'w') as file: file.write('\n'.join('%-15s %s' % (i,j) for i,j in data) ) for me is even clearer than expression with loop A: "%10s" % obj will ensure minimum 10 spaces with the string representation of obj aligned on the right. "%-10s" % obj does the same, but aligns to the left.
Writing white-space delimited text to be human readable in Python
I have a list of lists that looks something like this: data = [['seq1', 'ACTAGACCCTAG'], ['sequence287653', 'ACTAGNACTGGG'], ['s9', 'ACTAGAAACTAG']] I write the information to a file like this: for i in data: for j in i: file.write('\t') file.write(j) file.write('\n') The output looks like this: seq1 ACTAGACCCTAG sequence287653 ACTAGNACTGGG s9 ACTAGAAACTAG The columns don't line up neatly because of variation in the length of the first element in each internal list. How can I write appropriate amounts of whitespace between the first and second elements to make the second column line up for human readability?
[ "You need a format string:\nfor i,j in data:\n file.write('%-15s %s\\n' % (i,j))\n\n%-15s means left justify a 15-space field for a string. Here's the output:\nseq1 ACTAGACCCTAG\nsequence287653 ACTAGNACTGGG\ns9 ACTAGAAACTAG\n\n", "data = [['seq1', 'ACTAGACCCTAG'],\n ['sequence2...
[ 10, 1, 0 ]
[]
[]
[ "human_readable", "python", "whitespace" ]
stackoverflow_0003689936_human_readable_python_whitespace.txt
Q: Django DB design to glob words quickly I need to quickly look up words for a web application that I am writing in Django. I was thinking of putting each character of the word in an integerfield of its own, indexed by position. class Word(models.Model): word = models.CharField(max_length=5) length = models.IntegerField() c0 = models.IntegerField(blank=True, null=True) c1 = models.IntegerField(blank=True, null=True) c2 = models.IntegerField(blank=True, null=True) c3 = models.IntegerField(blank=True, null=True) c4 = models.IntegerField(blank=True, null=True) mapping = [c0, c1, c2, c3, c4,] def save(self): self.length = len(self.word) for (idx, char) in enumerate(self.word): self.mapping[idx] = ord(char) models.Model.save(self) Then I could make queries like Word.objects.filter(length=4, mapping[2]=ord('A')) to find all words of length four that have an A in the third position. I'm not really sure about the design and some of the mechanics so I thought I would ask for suggestions here before I went and tried to implement it. I'm not entirely sure about the syntax for making queries. So, I guess the questions would be Do you have any suggestions for the design? Would mapping[2] work? Would I be able to pass in a dictionary to the filter command so that I can have a variable number of keyword arguments? Thanks! A: Would mapping[2] work? No, it wouldn't. Would I be able to pass in a dictionary to the filter command so that I can have a variable number of keyword arguments? Certainly. For instance: conditions = dict(word__startswith = 'A', length = 5) Word.objects.filter(**conditions) would find all Word instances starting with A and are five characters long. Do you have any suggestions for the design? This feels to me is like a case of premature optimization. I suspect that for moderate volumes of data you should be able to combine a suitable database function with Django's filter to get what you need. For example: to find all words of length four that have an A in the third position. you can combine a Django filter with (Postgresql's) strpos. contains, position = 'A', 3 where = ["strpos(word, '%s') = %s" % (contains, position)] Word.objects.filter(length = 4, word__contains = contains).extra(where = where)
Django DB design to glob words quickly
I need to quickly look up words for a web application that I am writing in Django. I was thinking of putting each character of the word in an integerfield of its own, indexed by position. class Word(models.Model): word = models.CharField(max_length=5) length = models.IntegerField() c0 = models.IntegerField(blank=True, null=True) c1 = models.IntegerField(blank=True, null=True) c2 = models.IntegerField(blank=True, null=True) c3 = models.IntegerField(blank=True, null=True) c4 = models.IntegerField(blank=True, null=True) mapping = [c0, c1, c2, c3, c4,] def save(self): self.length = len(self.word) for (idx, char) in enumerate(self.word): self.mapping[idx] = ord(char) models.Model.save(self) Then I could make queries like Word.objects.filter(length=4, mapping[2]=ord('A')) to find all words of length four that have an A in the third position. I'm not really sure about the design and some of the mechanics so I thought I would ask for suggestions here before I went and tried to implement it. I'm not entirely sure about the syntax for making queries. So, I guess the questions would be Do you have any suggestions for the design? Would mapping[2] work? Would I be able to pass in a dictionary to the filter command so that I can have a variable number of keyword arguments? Thanks!
[ "\nWould mapping[2] work?\n\nNo, it wouldn't.\n\nWould I be able to pass in a dictionary to the filter command so that I can have a variable number of keyword arguments?\n\nCertainly. For instance:\nconditions = dict(word__startswith = 'A', length = 5)\nWord.objects.filter(**conditions)\n\nwould find all Word insta...
[ 0 ]
[]
[]
[ "database_design", "django", "glob", "python" ]
stackoverflow_0003689971_database_design_django_glob_python.txt
Q: Best way to suppress exceptions raised when third-party service is unavailable? I've written a Django application which interacts with a third-party API (Disqus, although this detail is unimportant) via a Python wrapper. When the service is unavailable, the Python wrapper raises an exception. The best way for the application to handle such exceptions is to suppress them so that the rest of the page's content can still be displayed to the user. The following works fine. try: somemodule.method_that_may_raise_exception(args) except somemodule.APIError: pass Certain views contain several such calls. Is wrapping each call in try/except the best way to suppress possible exceptions? A: Making API calls from views is not so good idea. You should probably create another module, that does the job. ie. when I make Facebook apps I create publish.py file to store all "publish to live stream" calls. Functions in that module are named based on when they should be called. Ie.: # publish.py def authorise_application(user): # API call "User joined app." def post_anwser(anwser): # API call "User posted anwser to quiz". Then your views are very clean: # views.py def post_anwser(request): ... if form.is_valid(): form.save() publish.post_anwser(form.instance) When you have your code organised that way, you can create decorator for ignoring exceptions: # publish.py def ignore_api_error(fun): def res(*args, **kwargs): try: return fun(*args, **kwargs): except someservice.ApiError: return None return res @ignore_api_error def authorised_application(user): # API call "User joined app." @ignore_api_error def posted_anwser(user, anwser): # API call "User posted anwser to quiz". Also you can create function, that is not "ignored" by default, and add ignore code in view: # publish.py def some_function(user, message): pass # views.py def my_view(): ... publish.ignore_api_error(publish.some_function)(user, message) ... A: Certain views contain several such calls. Is wrapping each call in try/except the best way to suppress possible exceptions? You can wrap the API call inside another function. Say: def make_api_call(*args, **kwargs): try: return somemodule.method_that_may_raise_exception(*args, **kwargs) except somemodule.APIError: log.warn("....") This function can be called instead of the try/except block in each view. This will at least serve to reduce the number of lines of code you write and provide a common place for handling such exceptions. Update @Yorirou is correct. Changing code to add this good practice.
Best way to suppress exceptions raised when third-party service is unavailable?
I've written a Django application which interacts with a third-party API (Disqus, although this detail is unimportant) via a Python wrapper. When the service is unavailable, the Python wrapper raises an exception. The best way for the application to handle such exceptions is to suppress them so that the rest of the page's content can still be displayed to the user. The following works fine. try: somemodule.method_that_may_raise_exception(args) except somemodule.APIError: pass Certain views contain several such calls. Is wrapping each call in try/except the best way to suppress possible exceptions?
[ "Making API calls from views is not so good idea. You should probably create another module, that does the job.\nie. when I make Facebook apps I create publish.py file to store all \"publish to live stream\" calls. Functions in that module are named based on when they should be called. Ie.:\n# publish.py\ndef autho...
[ 2, 1 ]
[]
[]
[ "django", "exception_handling", "python" ]
stackoverflow_0003690077_django_exception_handling_python.txt
Q: Parse JavaScript variable with Python How can I convert a JavaScript variable (not JSON format) into a python variable? Example JavaScript variable: { title: "TITLE", name: "NAME", active: false, info: { key1: "value1", dict1: { sub_key1: "sub_value1", sub_key2: "sub_value2", }, dict2: { sub_key3: "sub_value3", sub_key4: "sub_value4", sub_key5: "sub_value5" }, }, list1: ["element1", "element2", "element2"], } A: This format looks just like the input in this question. Try adapting the pyparsing parser I posted there. A: Convert it to JSON and read it in python. I really do not understand what is the problem? e.g. JSON.stringify gives {"title":"TITLE","name":"NAME","active":false,"info":{"key1":"value1","dict1":{"sub_key1":"sub_value1","sub_key2":"sub_value2"},"dict2":{"sub_key3":"sub_value3","sub_key4":"sub_value4","sub_key5":"sub_value5"}},"list1":["element1","element2","element2"]} Which can be read by python json module, so question is where from you are getting javascript and why can't you convert it to JSON? Edit: if the source of javascript if totally out of your control, you can use javascript as a command line scripting language e.g. spidermonkey (used in firefox), rhino, V8 (used in google chrome) or on windows WSH. Using javascript interpreter you can modify javascript , stringify it and then process it with python if needed. It is better to user already implemented and tested interpreter than to build one by yourselves. You can also try python-spidermonkey
Parse JavaScript variable with Python
How can I convert a JavaScript variable (not JSON format) into a python variable? Example JavaScript variable: { title: "TITLE", name: "NAME", active: false, info: { key1: "value1", dict1: { sub_key1: "sub_value1", sub_key2: "sub_value2", }, dict2: { sub_key3: "sub_value3", sub_key4: "sub_value4", sub_key5: "sub_value5" }, }, list1: ["element1", "element2", "element2"], }
[ "This format looks just like the input in this question. Try adapting the pyparsing parser I posted there.\n", "Convert it to JSON and read it in python.\nI really do not understand what is the problem?\ne.g. JSON.stringify gives\n{\"title\":\"TITLE\",\"name\":\"NAME\",\"active\":false,\"info\":{\"key1\":\"value...
[ 3, 1 ]
[]
[]
[ "javascript", "python", "variables" ]
stackoverflow_0003690116_javascript_python_variables.txt
Q: Many-To-One Relation Query in Django Can someone tell me, how I can access all contacts relating to a specific group? I'm new to Django and did this (according to the docs): def view_group(request, group_id): groups = Group.objects.all() group = Group.objects.get(pk=group_id) contacts = group.contacts.all() return render_to_response('manage/view_group.html', { 'groups' : groups, 'group' : group, 'contacts' : contacts }) "groups" is for something different, I tried it with "group" and "contacts" but get a 'Group' object has no attribute 'contacts' exception. Here's the model I'm using from django.db import models # Create your models here. class Group(models.Model): name = models.CharField(max_length=255) def __unicode__(self): return self.name class Contact(models.Model): group = models.ForeignKey(Group) forname = models.CharField(max_length=255) surname = models.CharField(max_length=255) company = models.CharField(max_length=255) address = models.CharField(max_length=255) zip = models.CharField(max_length=255) city = models.CharField(max_length=255) tel = models.CharField(max_length=255) fax = models.CharField(max_length=255) email = models.CharField(max_length=255) url = models.CharField(max_length=255) salutation = models.CharField(max_length=255) title = models.CharField(max_length=255) note = models.TextField() def __unicode__(self): return self.surname Thanks in advance! EDIT: Oh and can someone tell me how I can add a contact to a group? A: One way: group = Group.objects.get(pk=group_id) contacts_in_group = Contact.objects.filter(group=group) Another, more idomatic, way: group = Group.objects.get(pk=group_id) contacts_in_group = group.contact_set.all() contact_set is the default related_name for the relation as shown in the related objects docs. If you wanted to, you could specify your own related_name, such as related_name='contacts' when defining the field and then you could do group.contacts.all() To add a new Contact to a group, you just need to assign the relevant group to contact via the group field and save the Contact: the_group = Group.objects.get(pk=the_group_id) newcontact = Contact() ...fill in various details of your Contact here... newcontact.group = the_group newcontact.save() Sounds like you'd enjoy reading the free Django Book to get to grips with these fundamentals. A: You will need to modify your code as shown below: contacts = group.contact_set.all() See the relevant documentation for more details.
Many-To-One Relation Query in Django
Can someone tell me, how I can access all contacts relating to a specific group? I'm new to Django and did this (according to the docs): def view_group(request, group_id): groups = Group.objects.all() group = Group.objects.get(pk=group_id) contacts = group.contacts.all() return render_to_response('manage/view_group.html', { 'groups' : groups, 'group' : group, 'contacts' : contacts }) "groups" is for something different, I tried it with "group" and "contacts" but get a 'Group' object has no attribute 'contacts' exception. Here's the model I'm using from django.db import models # Create your models here. class Group(models.Model): name = models.CharField(max_length=255) def __unicode__(self): return self.name class Contact(models.Model): group = models.ForeignKey(Group) forname = models.CharField(max_length=255) surname = models.CharField(max_length=255) company = models.CharField(max_length=255) address = models.CharField(max_length=255) zip = models.CharField(max_length=255) city = models.CharField(max_length=255) tel = models.CharField(max_length=255) fax = models.CharField(max_length=255) email = models.CharField(max_length=255) url = models.CharField(max_length=255) salutation = models.CharField(max_length=255) title = models.CharField(max_length=255) note = models.TextField() def __unicode__(self): return self.surname Thanks in advance! EDIT: Oh and can someone tell me how I can add a contact to a group?
[ "One way:\ngroup = Group.objects.get(pk=group_id)\ncontacts_in_group = Contact.objects.filter(group=group)\n\nAnother, more idomatic, way:\ngroup = Group.objects.get(pk=group_id)\ncontacts_in_group = group.contact_set.all() \n\ncontact_set is the default related_name for the relation as shown in the related objects...
[ 6, 3 ]
[]
[]
[ "django", "exception", "foreign_key_relationship", "orm", "python" ]
stackoverflow_0003690825_django_exception_foreign_key_relationship_orm_python.txt
Q: This piece of python code should print out some information, but doesn't The code I'm tring to get should look something like this: send: 'GET /xml/atom.xml HTTP/1.0\r\nHost: diveintomark.org\r\nUser-Agent: Python-urllib/1.17\r\n\r\n' reply: 'HTTP/1.1 410 Gone\r\n' header: Date: Sat, 11 Sep 2010 11:47:19 GMT header: Server: Apache header: Content-Length: 307 header: Connection: close header: Content-Type: text/html; charset=iso-8859-1 The code I'm typing in doesn't work. Can anyone please tell me what's wrong with it: import httplib, urllib2 httplib.HTTPConnection.debuglevel = 1 request = urllib2.Request('http://www.google.co.uk/') opener = urllib2.build_opener() feeddata = opener.open(request).read() A: I believe the example is simply wrong, try this instead: import urllib2 request = urllib2.Request('http://www.google.co.uk/') http_handler = urllib2.HTTPHandler(debuglevel=1) opener = urllib2.build_opener(http_handler) feeddata = opener.open(request).read() A: I got something out of this: httplib.HTTPConnection.debuglevel = 1 request = urllib2.Request('http://www.google.co.uk/') opener = urllib2.build_opener() feeddata = opener.open(request).read() print feeddata Here's what I got: C:\Tools\Python-2.6.1\python.exe "C:/Documents and Settings/Michael/My Documents/Projects/Python/learning/core/src/so.py" <!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"><title>Google</title><script>window.google={kEI:"GnOLTKeBIIaQeMCv8IgG",kEXPI:"25856,25900,26446",kCSI:{e:"25856,25900,26446",ei:"GnOLTKeBIIaQeMCv8IgG",expi:"25856,25900,26446"},ml:function(){},kHL:"en",time:function(){return(new Date).getTime()},log:function(b,d,c){var a=new Image,e=google,g=e.lc,f=e.li;a.onerror=(a.onload=(a.onabort=function(){delete g[f]}));g[f]=a;c=c||"/gen_204?atyp=i&ct="+b+"&cad="+d+"&zx="+google.time();a.src=c;e.li=f+1},lc:[],li:0,Toolbelt:{}}; window.google.sn="webhp";window.google.timers={load:{t:{start:(new Date).getTime()}}};try{}catch(u){}window.google.jsrt_kill=1; var _gjwl=location;function _gjuc(){var e=_gjwl.href.indexOf("#");if(e>=0){var a=_gjwl.href.substring(e);if(a.indexOf("&q=")>0||a.indexOf("#q=")>=0){a=a.substring(1);if(a.indexOf("#")==-1){for(var c=0;c<a.length;){var d=c;if(a.charAt(d)=="&")++d;var b=a.indexOf("&",d);if(b==-1)b=a.length;var f=a.substring(d,b);if(f.indexOf("fp=")==0){a=a.substring(0,c)+a.substring(b,a.length);b=c}else if(f=="cad=h")return 0;c=b}_gjwl.href="/search?"+a+"&cad=h";return 1}}}return 0}function _gjp(){!(window._gjwl.hash&& window._gjuc())&&setTimeout(_gjp,500)}; window._gjp && _gjp()</script><style id=gstyle>body{margin:0}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}body,td,a,p,.h{font-family:arial,sans-serif}.h{color:#36c;font-size:20px}.q{color:#00c}.ts td{padding:0}.ts{border-collapse:collapse}em{font-weight:bold;font-style:normal}.lst{width:496px}.tiah{width:458px}input{font-family:inherit}a.gb1,a.gb2,a.gb3,a.gb4{color:#11c !important}#gbar,#guser{font-size:13px;padding-top:1px !important}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{color:#00c !important}body{background:#fff;color:black}input{-moz-box-sizing:content-box}a{color:#11c;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#4272db}a:visited{color:#551a8b}a.gb1,a.gb4{text-decoration:underline}a.gb3:hover{text-decoration:none}#ghead a.gb2:hover{color:#fff!important}.ds{display:-moz-inline-box}.ds{border-bottom:solid 1px #e7e7e7;border-right:solid 1px #e7e7e7;display:inline-block;margin:3px 0 4px;margin-left:4px}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px;}.lsbb{background:#eee;border:solid 1px;border-color:#ccc #999 #999 #ccc;height:30px;display:block}.lsb{background:url(/images/srpr/nav_logo14.png) bottom;font:15px arial,sans-serif;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;vertical-align:top}.lsb:active{background:#ccc}.lst:focus{outline:none}.ftl,#fll a{margin:0 12px}#addlang a{padding:0 3px}.gac_v div{display:none}.gac_v .gac_v2,.gac_bt{display:block!important}</style><script>google.y={};google.x=function(e,g){google.y[e.id]=[e,g];return false};</script></head><body bgcolor=#ffffff text=#000000 link=#0000cc vlink=#551a8b alink=#ff0000 onload="document.f.q.focus();if(document.images)new Image().src='/images/srpr/nav_logo14.png'" ><textarea id=csi style=display:none></textarea><div id=ghead><div id=gbar><nobr><b class=gb1>Web</b> <a onclick=gbar.qs(this) href="http://www.google.co.uk/imghp?hl=en&tab=wi" class=gb1>Images</a> <a onclick=gbar.qs(this) href="http://video.google.co.uk/?hl=en&tab=wv" class=gb1>Videos</a> <a onclick=gbar.qs(this) href="http://maps.google.co.uk/maps?hl=en&tab=wl" class=gb1>Maps</a> <a onclick=gbar.qs(this) href="http://news.google.co.uk/nwshp?hl=en&tab=wn" class=gb1>News</a> <a onclick=gbar.qs(this) href="http://www.google.co.uk/prdhp?hl=en&tab=wf" class=gb1>Shopping</a> <a href="http://mail.google.com/mail/?hl=en&tab=wm" class=gb1>Gmail</a> <a href="http://www.google.co.uk/intl/en/options/" class=gb1 style="text-decoration:none"><u>more</u> &raquo;</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe><a href="/url?sa=p&pref=ig&pval=3&q=http://www.google.co.uk/ig%3Fhl%3Den%26source%3Diglk&usg=AFQjCNH9dUJQAsNWnO3XKq2EIPgFbczqlA" class=gb4>iGoogle</a> | </span><a href="/preferences?hl=en" class=gb4>Settings</a> | <a href="https://www.google.com/accounts/Login?hl=en&continue=http://www.google.co.uk/" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div></div> <center><br clear=all id=lgpd><div id=lga><div style="padding:28px 0 3px"><div align=left style="background:url(/intl/en_com/images/srpr/logo1w.png) no-repeat;height:110px;width:276px" title="Google" id=logo onload="window.lol&&lol()"><div nowrap style="color:#777;font-size:16px;font-weight:bold;left:214px;position:relative;top:70px">UK</div></div></div><br></div><form action="/search" name=f><table cellpadding=0 cellspacing=0><tr valign=top><td width=25%>&nbsp;</td><td align=center nowrap><input name=hl type=hidden value=en><input name=source type=hidden value=hp><input type=hidden name=ie value="ISO-8859-1"><div class=ds style="height:32px;margin:4px 0"><input autocomplete="off" maxlength=2048 name=q class="lst" title="Google Search" value="" size=57 style="background:#fff;border:1px solid #ccc;border-bottom-color:#999;border-right-color:#999;color:#000;font:18px arial,sans-serif bold;height:25px;margin:0;padding:5px 8px 0 6px;vertical-align:top"></div><br style="line-height:0"><span class=ds ><span class=lsbb><input name=btnG type=submit value="Google Search" class=lsb></span></span><span class=ds><span class=lsbb><input name=btnI type=submit value="I&#39;m Feeling Lucky" class=lsb></span></span></td><td nowrap width=25% align=left class=sblc><a href="/advanced_search?hl=en">Advanced Search</a><a href="/language_tools?hl=en">Language Tools</a></td></tr></table></form><div style="font-size:83%;min-height:3.5em"><br></div><div id=res></div><span id=footer><center id=fctr><div style="font-size:10pt"><div id=fll style="margin:19px auto 19px auto;text-align:center"><a href="/intl/en/ads/">Advertising&nbsp;Programmes</a><a href="/services/">Business Solutions</a><a href="/intl/en/about.html">About Google</a><a href="http://www.google.com/ncr">Go to Google.com</a></div></div><p style="color:#767676;font-size:8pt">&copy; 2010 - <a href="/intl/en/privacy.html">Privacy</a></p></center></span> <div id=xjsd></div><div id=xjsi><script>if(google.y)google.y.first=[];if(google.y)google.y.first=[];google.dstr=[];google.rein=[];window.setTimeout(function(){var a=document.createElement("script");a.src="/extern_js/f/CgJlbhICdWsgACswRTgBLCswWjgALCswDjgALCswFzgALCswJzgELCswPDgALCswCjhzQB0sKzAWOAAsKzAlOM-IASwrMEA4EywrMEE4BSwrMFQ4ASwrMBg4ACwrMCY4DiyAAheQAhs/N_JFQ4PkHl4.js";(document.getElementById("xjsd")||document.body).appendChild(a);if(google.timers&&google.timers.load.t)google.timers.load.t.xjsls=(new Date).getTime();},0); google.neegg=1;google.y.first.push(function(){var form=document.f||document.f||document.gs;google.ac.i(form,form.q,'','','',{o:1,sw:1,r:0});google.mc = [[14,{}],[22,{"m_error":"<font color=red>Error:</font> The server could not complete your request. Try again in 30 seconds.","m_tip":"Click for more information"}],[64,{}]];google.med('init');google.History&&google.History.initialize('/')});if(google.j&&google.j.en&&google.j.xi){window.setTimeout(google.j.xi,0);google.fade=null;}</script></div><script>(function(){ var b,d,e,f;function g(a,c){if(a.removeEventListener){a.removeEventListener("load",c,false);a.removeEventListener("error",c,false)}else{a.detachEvent("onload",c);a.detachEvent("onerror",c)}}function h(a){f=(new Date).getTime();++d;a=a||window.event;var c=a.target||a.srcElement;g(c,h)}var i=document.getElementsByTagName("img");b=i.length;d=0;for(var j=0,k;j<b;++j){k=i[j];if(k.complete||typeof k.src!="string"||!k.src)++d;else if(k.addEventListener){k.addEventListener("load",h,false);k.addEventListener("error", h,false)}else{k.attachEvent("onload",h);k.attachEvent("onerror",h)}}e=b-d;function l(){if(!google.timers.load.t)return;google.timers.load.t.ol=(new Date).getTime();google.timers.load.t.iml=f;google.kCSI.imc=d;google.kCSI.imn=b;google.kCSI.imp=e;google.timers.load.t.xjs&&google.report&&google.report(google.timers.load,google.kCSI)}if(window.addEventListener)window.addEventListener("load",l,false);else if(window.attachEvent)window.attachEvent("onload",l);google.timers.load.t.prt=(f=(new Date).getTime()); })(); </script> Process finished with exit code 0 Why would you assume that something would be printed without a 'print' statement?
This piece of python code should print out some information, but doesn't
The code I'm tring to get should look something like this: send: 'GET /xml/atom.xml HTTP/1.0\r\nHost: diveintomark.org\r\nUser-Agent: Python-urllib/1.17\r\n\r\n' reply: 'HTTP/1.1 410 Gone\r\n' header: Date: Sat, 11 Sep 2010 11:47:19 GMT header: Server: Apache header: Content-Length: 307 header: Connection: close header: Content-Type: text/html; charset=iso-8859-1 The code I'm typing in doesn't work. Can anyone please tell me what's wrong with it: import httplib, urllib2 httplib.HTTPConnection.debuglevel = 1 request = urllib2.Request('http://www.google.co.uk/') opener = urllib2.build_opener() feeddata = opener.open(request).read()
[ "I believe the example is simply wrong, try this instead:\nimport urllib2\n\nrequest = urllib2.Request('http://www.google.co.uk/')\nhttp_handler = urllib2.HTTPHandler(debuglevel=1)\nopener = urllib2.build_opener(http_handler)\nfeeddata = opener.open(request).read()\n\n", "I got something out of this:\nhttplib.HTT...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003690923_python.txt
Q: I can't delete a folder that I just extracted from a zip file in python So here's my problem. I have a python script that takes a zipfile and extracts its contents. Then based on some constraint, I will try to delete the folder whose contents were just extracted. For some reason I get an error, WindowsError: [Error 5] Access is denied: 'Foldername' when i try to delete that folder. The simple code looks like the following wzip = zipfile.ZipFile('zipfile.zip') wzip.extractall() wzip.close() os.remove('ExtractedFolder') If I run this in the interpreter I get the following: Traceback (most recent call last): File "", line 1, in WindowsError: [Error 5] Access is denied: 'ExtractedFolder' I'm using Python 2.6 on Windows Vista 32-bit and I'm kinda baffled as to why this might be happening. A: Many reasons possible. You need to use os.rmdir to remove directories You need to empty the folder first - remember, the Windows command rmdir needs a /S option to remove the contents, and Python probably uses that. Is the unzip also using the archive's attributes? Read-only attributes may be applied. Are you reading anything from that folder, before you delete? You may not have closed it. Windows can cause similar problems with filenames containing unusual characters A: I see a possible problem on Windows, which is that you could have an opened file in this directory. Make sure that you close explicitly all the files that you have opened using file.close() (your sample code looks right, though). Also, it might be useful to have a look at shutils.rmtree: it can recursively remove directories, and capture errors.
I can't delete a folder that I just extracted from a zip file in python
So here's my problem. I have a python script that takes a zipfile and extracts its contents. Then based on some constraint, I will try to delete the folder whose contents were just extracted. For some reason I get an error, WindowsError: [Error 5] Access is denied: 'Foldername' when i try to delete that folder. The simple code looks like the following wzip = zipfile.ZipFile('zipfile.zip') wzip.extractall() wzip.close() os.remove('ExtractedFolder') If I run this in the interpreter I get the following: Traceback (most recent call last): File "", line 1, in WindowsError: [Error 5] Access is denied: 'ExtractedFolder' I'm using Python 2.6 on Windows Vista 32-bit and I'm kinda baffled as to why this might be happening.
[ "Many reasons possible. \n\nYou need to use os.rmdir to remove directories\nYou need to empty the folder\nfirst - remember, the Windows command\nrmdir needs a /S option to\nremove the contents, and Python probably uses that.\nIs the unzip\nalso using the archive's attributes?\nRead-only attributes may be applied.\n...
[ 4, 1 ]
[]
[]
[ "operating_system", "python", "windows", "windows_vista", "zip" ]
stackoverflow_0003688456_operating_system_python_windows_windows_vista_zip.txt
Q: Python: quickly loading 7 GB of text files into unicode strings I have a large directory of text files--approximately 7 GB. I need to load them quickly into Python unicode strings in iPython. I have 15 GB of memory total. (I'm using EC2, so I can buy more memory if absolutely necessary.) Simply reading the files will be too slow for my purposes. I have tried copying the files to a ramdisk and then loading them from there into iPython. That speeds things up but iPython crashes (not enough memory left over?) Here is the ramdisk setup: mount -t tmpfs none /var/ramdisk -o size=7g Anyone have any ideas? Basically, I'm looking for persistent in-memory Python objects. The iPython requirement precludes using IncPy: http://www.stanford.edu/~pgbovine/incpy.html . Thanks! A: There is much that is confusing here, which makes it more difficult to answer this question: The ipython requirement. Why do you need to process such large data files from within ipython instead of a stand-alone script? The tmpfs RAM disk. I read your question as implying that you read all of your input data into memory at once in Python. If that is the case, then python allocates its own buffers to hold all the data anyway, and the tmpfs filesystem only buys you a performance gain if you reload the data from the RAM disk many, many times. Mentioning IncPy. If your performance issues are something you could solve with memoization, why can't you just manually implement memoization for the functions where it would help most? So. If you actually need all the data in memory at once -- if your algorithm reprocesses the entire dataset multiple times, for example -- I would suggest looking at the mmap module. That will provide the data in raw bytes instead of unicode objects, which might entail a little more work in your algorithm (operating on the encoded data, for example), but will use a reasonable amount of memory. Reading the data into Python unicode objects all at once will require either 2x or 4x as much RAM as it occupies on disk (assuming the data is UTF-8). If your algorithm simply does a single linear pass over the data (as does the Aho-Corasick algorithm you mention), then you'd be far better off just reading in a reasonably sized chunk at a time: with codecs.open(inpath, encoding='utf-8') as f: data = f.read(8192) while data: process(data) data = f.read(8192) I hope this at least gets you closer. A: I saw the mention of IncPy and IPython in your question, so let me plug a project of mine that goes a bit in the direction of IncPy, but works with IPython and is well-suited to large data: http://packages.python.org/joblib/ If you are storing your data in numpy arrays (strings can be stored in numpy arrays), joblib can use memmap for intermediate results and be efficient for IO.
Python: quickly loading 7 GB of text files into unicode strings
I have a large directory of text files--approximately 7 GB. I need to load them quickly into Python unicode strings in iPython. I have 15 GB of memory total. (I'm using EC2, so I can buy more memory if absolutely necessary.) Simply reading the files will be too slow for my purposes. I have tried copying the files to a ramdisk and then loading them from there into iPython. That speeds things up but iPython crashes (not enough memory left over?) Here is the ramdisk setup: mount -t tmpfs none /var/ramdisk -o size=7g Anyone have any ideas? Basically, I'm looking for persistent in-memory Python objects. The iPython requirement precludes using IncPy: http://www.stanford.edu/~pgbovine/incpy.html . Thanks!
[ "There is much that is confusing here, which makes it more difficult to answer this question:\n\nThe ipython requirement. Why do you need to process such large data files from within ipython instead of a stand-alone script?\nThe tmpfs RAM disk. I read your question as implying that you read all of your input data...
[ 3, 2 ]
[]
[]
[ "ctypes", "ipython", "memory", "python", "shared_memory" ]
stackoverflow_0003647937_ctypes_ipython_memory_python_shared_memory.txt
Q: python html form library that supports forms within form (form as a field )? The question says it all, For example, In a contact book if someone has multiple addresses with each address having multiple fields I want to display an "add another address" button. This button would add another address form. (I want one round trip to the server, I do not want javascript or webforms2.) It would be nice if some built in library would support this. Examples are appreciated. Thanks. A: Try django-formsets, and if you want dynamic behavior use this http://code.google.com/p/django-dynamic-formset/
python html form library that supports forms within form (form as a field )?
The question says it all, For example, In a contact book if someone has multiple addresses with each address having multiple fields I want to display an "add another address" button. This button would add another address form. (I want one round trip to the server, I do not want javascript or webforms2.) It would be nice if some built in library would support this. Examples are appreciated. Thanks.
[ "Try django-formsets, and if you want dynamic behavior use this http://code.google.com/p/django-dynamic-formset/\n" ]
[ 1 ]
[]
[]
[ "form_processing", "forms", "python" ]
stackoverflow_0003691140_form_processing_forms_python.txt
Q: Counting content only in HTML page Is there anyway I can parse a website by just viewing the content as displayed to the user in his browser? That is, instead of downloading "page.htm"l and starting to parse the whole page with all the HTML/javascript tags, I will be able to retrieve the version as displayed to users in their browsers. I would like to "crawl" websites and rank them according to keywords popularity (viewing the HTML source version is problematic for that purpose). Thanks! Joel A: You could get the source and strip the tags out, leaving only non-tag text, which works for almost all pages, except those where JavaScript-generated content is essential. A: A browser also downloads the page.html and then renders it. You should work the same way. Use a html parser like lxml.html or BeautifulSoup, using those you can ask for only the text enclosed within tags (and arguments you do like, like title and alt attributes). A: The pyparsing wiki Examples page includes this html tag stripper.
Counting content only in HTML page
Is there anyway I can parse a website by just viewing the content as displayed to the user in his browser? That is, instead of downloading "page.htm"l and starting to parse the whole page with all the HTML/javascript tags, I will be able to retrieve the version as displayed to users in their browsers. I would like to "crawl" websites and rank them according to keywords popularity (viewing the HTML source version is problematic for that purpose). Thanks! Joel
[ "You could get the source and strip the tags out, leaving only non-tag text, which works for almost all pages, except those where JavaScript-generated content is essential.\n", "A browser also downloads the page.html and then renders it. You should work the same way. Use a html parser like lxml.html or BeautifulS...
[ 0, 0, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003690560_html_python.txt
Q: To IDE or Not? A beginner developer's dilemma Basically, me and a friend of mine are just planning to work on a Python project which would have GUI interface, and enable file transfer over and remote file listing. We have most of the tools which we are going to use, Glade, Python etcetera. I just want to know if I should use an IDE or not. I've heard only good things about Anjuta, but not convinced of its Python support; care to comment? And also is there any other good IDE I should check out? Currently I am just planning on coding as usual in vim. A: The ability to debug using an IDE makes your life so much easier. A: Python is a particularly strange language in that having a full-fledged IDE doesn't really add much (and some would argue that an IDE tends to severely limit your thinking-flow in Python). I've been using regular Vim and Gedit to develop in Python and never really missed using IDE. Text editors like Vim or Emacs itself can be configured quite flexibly to match an IDE power though, so it doesn't really matter which way you go. A: There are numerous IDEs you can check out. Take a look at PyDev, PIDA, Komodo, Eric. I personally don't think IDEs add that much to software development (on this scale and in this language). Python has fine external debugging tools and refactoring is not that hard with a program of this size. Do you currently use or want to use any features you miss in your current editor? If so, pick another one, else, stick with what you like most. As long as it has version control integration you should be fine. A: Personally I do most my Python coding in Vim, but once in a while I feel like using a full-IDE and I use Eclipse with Pydev at those times. It depends on your own preference, some people absolutely love Vim and won't use anything else. Others just can't work without an IDE. Here's a list of: Python IDEs: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Python editors: http://wiki.python.org/moin/PythonEditors A: In terms of using an IDE or not, it doesn't matter. I prefer using an IDE since I like having the tools I need bundled up into one nice, neat little package that can handle all of my development. However, using a text editor is just as good, especially ones as powerful and extensible as vi(m) and (x)emacs. The real reasons for using an IDE, though, are code completion, management of indentation, code folding, refactoring support, and debugging. If you want to check out other IDEs for Python development, I would suggest also looking at NetBeans and Eclipse with the appropriate plugins. I, personally, prefer NetBeans since I have a feeling that PyDev is going to be going downhill since Aptana bought them (previously, they ruined RadRails, which is the Eclipse plugin for Ruby on Rails development) and don't want to get comfortable with a tool that might not be useful long-term. A: With Java, I'd say no IDE for beginners, because you have to understand CLASSPATH first. With Python, I'd say PyCharm from JetBrains. IntelliJ is the best Java IDE; PyCharm is making my Python work a pleasure. A: IMHO, not using IDE to develop is just like using typewriter to write a novel. Nobody said you can't, but why you have to try that hard when you already have laptop? A: I code in Vim for python. If you want to use an IDE then I would recommend IntelliJ's PyCharm. I use vim because the actual editing is far superior and if you are a power user there is very little that you can't do easily. PyCharm provides help with api by providing completion and helps with some basic refactoring. These advantages though wear of sooner than you would expect. I use grep and vim regex to do refactoring - its a bit more work than pycharm but if you can manage it then the advantages of vim clearly outweigh using an ide. I assume that you are developing in a *nix environment, if you use windows then I would recommend using an Ide. A: As opposed to some other guys here, I think that an IDE does add much to software development, even for a dynamically typed language like Python which makes it harder to do static analysis. My preferred IDE for Python development is Eclipse with PyDev. Before that, I coded in Notepad++ which isn't much different than the PyDev editor in terms of features. PyDev has some great features that you won't find in a "normal" editor: It shows warnings and syntax errors (almost) in realtime. A text editor won't tell me about typos, but PyDev does. As another example, unresolved imports or undefined functions (e.g. because of a typo) are marked as warnings/errors. And there are many more common mistakes that are automatically detected, and PyDev can be integrated with pylint so that warnings and errors from pylint are displayed with the usual icons in the editor. Autocompletion by introspection Outline view of the current module and its classes Additionally, Eclipse itself is also great for any kind of programming project. I especially like the fully integrated interface - project explorer, editor, outline, console, problems overview, run configurations and so on. When using Vim, Emacs or similar, I guess you would have to install lots of plugins or custom scripts to achieve the same. As you said you want to do a project, I think that Eclipse is a good choice. For quickly hacking a small Python script, it's overkill of course. A: If you just start learning python/glade/gtk stack, I'd say you should start without an IDE just to learn how it works internally. This will help you later when your code will be bigger and more complex. However, good IDE helps in so many ways I wouldn't recommend against using any in the long run. This article might help you decide whether you need any: http://infoworld.com/d/developer-world/infoworld-review-nine-fine-python-development-tools-374 A: it's horses for courses, personally i'm much happier with textmate or vim and a nice cup of coffee but it's what feels more comfortable to you. there's no shame in using an IDE, if it's what gets your idea out there to the masses the most productive then use whatever you like. however when starting out i'd favour something with intellisense as it'll teach you the basics as you type, give it a year and you'll be a master at it. A: Two ways to approach this: Use what you're used to. If you have used an editor in the past and know its quirks, stick with it. You'll waste less time figuring out how to work with the tool and spend more time on the actual project. Use something new. Anjuta, vim, whatever, as long as you haven't spent too much time with it so far. You'll learn a whole lot of stuff besides your actual project, but the project itself won't be done as fast as could be. Personally, I prefer 2. Always learn something new, as long as it's not crunch time and it-has-to-be-done-by-friday. An IDE can help you only so much, but when you're still in the learning phase the more time you spend on the code yourself, the better. A: I'm not a Python programmer, but I prefer not to use IDEs. The reason for this is that I find IDEs are often big and do too many things for me, whereas using Notepad++ and the command prompt allows me to trim things down to suit my needs rather than being surrounded by features that I don't use. This allows me to learn more easily, because I have more control over what happens. A: Don't learn coding with an IDE. Code with it! A: I find using an IDE to dramatically help my Python code productivity. In particular, using wingide makes coding in python a pleasure. It has all the normal things you would expect (syntax highlighting, auto-complete, etc) but the killer features are the debugger and the debug probe. These two features are worth the cost of the program. It lets you see the live state of the application and try out python statements live at breakpoints. I find this especially helpful to explore the current state and to try out some code to see if it will work. I often write some of the trickier sections of code in the debug probe live and them copy them into my application. Very nice.
To IDE or Not? A beginner developer's dilemma
Basically, me and a friend of mine are just planning to work on a Python project which would have GUI interface, and enable file transfer over and remote file listing. We have most of the tools which we are going to use, Glade, Python etcetera. I just want to know if I should use an IDE or not. I've heard only good things about Anjuta, but not convinced of its Python support; care to comment? And also is there any other good IDE I should check out? Currently I am just planning on coding as usual in vim.
[ "The ability to debug using an IDE makes your life so much easier.\n", "Python is a particularly strange language in that having a full-fledged IDE doesn't really add much (and some would argue that an IDE tends to severely limit your thinking-flow in Python). I've been using regular Vim and Gedit to develop in P...
[ 8, 4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "anjuta", "ide", "python" ]
stackoverflow_0003690915_anjuta_ide_python.txt
Q: How is pip install using git different than just cloning a repository? I'm a beginner with Django and I'm having trouble installing django-basic-apps using pip. If I do this... $ cat requirements.txt git+git://github.com/nathanborror/django-basic-apps.git $ pip install -r requirements.txt I end up with lib/python2.6/site-packages/basic/blog that does NOT have a templates directory. If I do this... git clone http://github.com/nathanborror/django-basic-apps.git I end up with a copy of basic/blog that DOES have a templates directory. I suspect something about django-basic-apps or pip makes it not able to be installed via pip. I thought maybe reading django-basic-apps's setup.py would lead me to the answer, but I couldn't see it. (I should add that if I install without using pip, I'm able to get django-basic-apps working just fine.) A: When you use "pip" to install something, the package's setup.py is used to determine what packages to install. And this project's setup.py, if I'm reading it correctly, says "just install these Python packages inside the basic directory" — the setup.py makes absolutely no mention of any non-Python files it wants included in the install. This might be deliberate on the developer's part, since it is something of a tradition for Django packages to not include templates — notoriously, even something so basic as the built-in django.contrib.auth comes without any templates and makes you build its little forms from the ground up each time! (Or, to cut and paste from examples elsewhere on the web.) But if you yourself want the templates to be installed with this Python distribution, regardless of how the author has set things up, then just list the templates in the setup.py! First, add something like this to the setup.py file: template_patterns = [ 'templates/*.html', 'templates/*/*.html', 'templates/*/*/*.html', ] Then, add one last variable to the setup() call so that it ends like this: ... packages=packages, package_data=dict( (package_name, template_patterns) for package_name in packages )) This asserts to the setup() function that every package should be accompanied by data files that are found by searching for HTML files beneath each package's templates directory. Try it out, and let me know if this works on your machine too!
How is pip install using git different than just cloning a repository?
I'm a beginner with Django and I'm having trouble installing django-basic-apps using pip. If I do this... $ cat requirements.txt git+git://github.com/nathanborror/django-basic-apps.git $ pip install -r requirements.txt I end up with lib/python2.6/site-packages/basic/blog that does NOT have a templates directory. If I do this... git clone http://github.com/nathanborror/django-basic-apps.git I end up with a copy of basic/blog that DOES have a templates directory. I suspect something about django-basic-apps or pip makes it not able to be installed via pip. I thought maybe reading django-basic-apps's setup.py would lead me to the answer, but I couldn't see it. (I should add that if I install without using pip, I'm able to get django-basic-apps working just fine.)
[ "When you use \"pip\" to install something, the package's setup.py is used to determine what packages to install. And this project's setup.py, if I'm reading it correctly, says \"just install these Python packages inside the basic directory\" — the setup.py makes absolutely no mention of any non-Python files it wa...
[ 28 ]
[]
[]
[ "django", "pip", "python" ]
stackoverflow_0003689685_django_pip_python.txt
Q: How to detect when Firefox has finished loading a page using Python? Is it possible to use Python to detect when a web page has finished loading in the Firefox browser? I'm trying to automate some browser tasks using Python and this is the major stumbling block for me. Note that this is for small-scale personal use, not a server farm or anything like that. The Firefox browser is in an open window, so I can see what it is doing. BTW, I'm using Python version 2.6 on a Windows XP PC. Thanks in advance. A: selenium which can execute your scripts. PythonExt python extension for mozilla. Either of these should work.
How to detect when Firefox has finished loading a page using Python?
Is it possible to use Python to detect when a web page has finished loading in the Firefox browser? I'm trying to automate some browser tasks using Python and this is the major stumbling block for me. Note that this is for small-scale personal use, not a server farm or anything like that. The Firefox browser is in an open window, so I can see what it is doing. BTW, I'm using Python version 2.6 on a Windows XP PC. Thanks in advance.
[ "\nselenium which can execute your scripts.\n\nPythonExt python extension for mozilla.\nEither of these should work.\n\n\n" ]
[ 1 ]
[]
[]
[ "automation", "firefox", "python" ]
stackoverflow_0003691647_automation_firefox_python.txt
Q: Iterating over N dimensions in Python I have a map, let's call it M, which contains data mapped through N dimensions. # If it was a 2d map, I could iterate it thusly: start, size = (10, 10), (3, 3) for x in range(start[0], start[0]+size[0]): for y in range(start[1], start[1]+size[1]): M.get((x, y)) # A 3d map would add a for z in ... and access it thusly M.get((x, y, z)) # And so on. My question is: How do I make an iterator that can yield the correct iteration sequence? That is, given start, size = (10, 10), (3, 3) it would yield the 2-tuple sequence (10, 10), (10, 11), (10, 12), (11, 10), (11, 11) etc. And given start, size = (10, 10, 10), (3, 3, 3) it would yield the correct 3-tuple sequence. Yeah, I tried myself, but my head exploded. Or I can't justify spending time figuring it out, even though it's fun. Take your pick :) A: In Python 2.6+: itertools.product(*[xrange(i, i+j) for i,j in zip(start, size)]) A: With do it your self generator expreessions: start, size = (10, 10), (3, 3) values2=((x+xd,y+yd) for x,y in (start,) for xr,yr in (size,) for xd in range(xr) for yd in range(yr)) for x,y in values2: print x,y start, size = (10, 10, 10), (3, 3, 3) values3=((x+xd,y+yd, z+zd) for x,y,z in (start,) for xr,yr,zr in (size,) for xd in range(xr) for yd in range(yr) for zd in range(zr)) for x,y,z in values3: print x,y,z
Iterating over N dimensions in Python
I have a map, let's call it M, which contains data mapped through N dimensions. # If it was a 2d map, I could iterate it thusly: start, size = (10, 10), (3, 3) for x in range(start[0], start[0]+size[0]): for y in range(start[1], start[1]+size[1]): M.get((x, y)) # A 3d map would add a for z in ... and access it thusly M.get((x, y, z)) # And so on. My question is: How do I make an iterator that can yield the correct iteration sequence? That is, given start, size = (10, 10), (3, 3) it would yield the 2-tuple sequence (10, 10), (10, 11), (10, 12), (11, 10), (11, 11) etc. And given start, size = (10, 10, 10), (3, 3, 3) it would yield the correct 3-tuple sequence. Yeah, I tried myself, but my head exploded. Or I can't justify spending time figuring it out, even though it's fun. Take your pick :)
[ "In Python 2.6+:\nitertools.product(*[xrange(i, i+j) for i,j in zip(start, size)])\n\n", "With do it your self generator expreessions:\nstart, size = (10, 10), (3, 3)\nvalues2=((x+xd,y+yd)\n for x,y in (start,)\n for xr,yr in (size,)\n for xd in range(xr)\n for yd in range(yr))\n\nfor ...
[ 8, 0 ]
[]
[]
[ "iteration", "python", "recursion" ]
stackoverflow_0003691468_iteration_python_recursion.txt
Q: Make Python bool print 'On' or 'Off' rather than 'True' or 'False' What is the best way to make a variable that works exactly like a bool but prints On or Off rather than True or False? Currently the program is printing: Color: True, whereas Color: On would make more sense. For the record, I initially tried to make an OnOff class that inherits from bool: class OnOff(bool): def __str__(self): if self: return 'On' else: return 'Off' From the comments, I now understand that bool is a singleton, which is why this failed miserably: Traceback (most recent call last): class OnOff(bool): TypeError: Error when calling the metaclass bases type 'bool' is not an acceptable base type A: print ("Off", "On")[value] works too (because (False, True) == (0,1)) A: def Color(object): def __init__(self, color_value=False): self.color_value = color_value def __str__(self): if self.color_value: return 'On' else: return 'Off' def __cmp__(self, other): return self.color_value.__cmp__(other.color_value) Although this could be overkill for you. :) A: My favorite trick is to use the bool to index an array: return "Color: {0}".format(['Off','On'][has_color]) The caveat is that the value has to be False, True, 0, or 1. If you have something else, then you have to convert it to boolean first. A: print "On" if color else "Off" # Python 2.x print ("On" if color else "Off") # Python 3.x A: True and False are singletons. There is only one True and one False object in python. As a result attempting to inherit from them causes issues. (They just were not meant to be used in that way). You cannot overload the logical and/or operations which will prevent you from creating a really bool-like object. It'll constantly revert back to python's bool. So: Don't. If you don't want your values to print as True and False, don't call print on them directly. Print is for quick and dirty output. If you want something more then it gives then you'll need to do more work. In this case, all you need is to ToOnOff function. A: I am now using this solution based off Rahul's code: class OnOff(object): def __init__(self, value): self._value = value def __str__(self): if self._value: return 'On' else: return 'Off' def __cmp__(self, other): return self._value.__cmp__(other) I changed the __cmp__ function to enable the object to compare to bools and also changed some other minor stuff. Full credit to Rahul. A: mybool = {True: 'On', False: 'Off'} mybool[True] == 'On' mybool[False] == 'Off' A: If you don't want to mess with print... class BoolHack(object): def __init__(self): from sys import stdout self.realout = stdout def write(self, text): if text == 'False': text = 'Off' elif text == 'True': text = 'On' self.realout.write(text) import sys sys.stdout = BoolHack() print "Hello world" # ==> Hello world print 1 # ==> 1 print True, 10 # ==> On 10 print False # ==> Off print "True hack" # ==> True hack WARNING: Do not use in real production code! This is only for making your set of answers complete. print calls str() on objects to print, and only then puts the string to stdout... so you cant check type of object. But it is quite rare to just print 'False' or 'True' as a single string, so in your very very specific case it might work. A: class Color: def __init__(self,C): if C==True: self.col='On' else: self.col='Off' def __cmp__(self,other): return self.col A: Pity you can't do True.__str__=lambda:"On" Unfortunately it complains it is read-only. Anyway, that would be a VERY hackish way to do it! A: Try this curious one: a = True b = False print a and 'On' or 'Off' print b and 'On' or 'Off' A: Taking the advice of the public, I've changed my mind and found a better way to solve my problem than by creating a class: Convert the menu items to strings outside the class. Allowing me to use the solution proposed by THC4k. Unidiff: menu.items=(( ('Play Game', True), ' ', 'Speed: ', (speed, True), ' ', 'Screen: ', (screen_width, True), 'x', (screen_height, True), ' ', - 'Color: ', (color, True), + 'Color: ', (("Off", "On")[color], True), ' ', ('Exit', True) )) (I did the same for the other variables, I'm just trying to be succinct with the diff)
Make Python bool print 'On' or 'Off' rather than 'True' or 'False'
What is the best way to make a variable that works exactly like a bool but prints On or Off rather than True or False? Currently the program is printing: Color: True, whereas Color: On would make more sense. For the record, I initially tried to make an OnOff class that inherits from bool: class OnOff(bool): def __str__(self): if self: return 'On' else: return 'Off' From the comments, I now understand that bool is a singleton, which is why this failed miserably: Traceback (most recent call last): class OnOff(bool): TypeError: Error when calling the metaclass bases type 'bool' is not an acceptable base type
[ "print (\"Off\", \"On\")[value] works too (because (False, True) == (0,1))\n", "def Color(object):\n\n def __init__(self, color_value=False):\n self.color_value = color_value\n\n def __str__(self):\n if self.color_value:\n return 'On'\n else:\n return 'Off'\n\n def __...
[ 19, 10, 6, 4, 3, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "boolean", "printing", "python" ]
stackoverflow_0003687109_boolean_printing_python.txt
Q: A container for accessing contents by 2d/3d coordinates There are a lot of games that can generally be viewed as a bunch of objects spread out through space, and a very common operation is to pick all objects in a sub-area. The typical example would be a game with tons of units across a large map, and an explosion that affects units in a certain radius. This requires picking every unit in the radius in order to apply the effects of the explosion. Now, there are several ways to store objects that allows efficiently picking a sub-area. The easiest method is probably to divide the map into a grid; picking units in an area would involve selecting only the parts of the grid that is affected, and do a fine-grained coordinate check grid tiles that aren't 100% inside the area. What I don't like about this approach is answering "How large should the grid tiles be?" Too large, and efficiency may become a real problem. Too small, and the grid takes up tons of memory if the game world is large enough (and can become ridiculous if the game is 3d). There may not even be a suitable golden mean. The obvious solution to the above is to make a large grid with some kind of intelligent subdivision, like a pseudo tree-structure. And it is at this point I know for sure I am far into premature optimization. (Then there are proper dynamic quad/octrees, but that's even more complex to code and I'm not even confident it will perform any better.) So my question is: Is there a standard solution to the above problem? Something, in the lines of an STL container, that can just store any object with a coordinate, and retreive a list of objects within a certain area? It doesn't have to be different than what I described above, as long as it's something that has been thought out and deemed "good enough" for a start. Bonus points if there is an implementation of the algorithm in Python, but C would also do. A: The first step to writing a practical program is accepting that choices for some constants come from real-world considerations and not transcendent mathematical truths. This especially applies to game design/world simulation type coding, where you'd never get anywhere if you persisted in trying to optimally model the real world. :-) If your objects will all be of fairly uniform size, I would just choose a grid size proportional to the average object size, and go with that. It's the simplest - and keep in mind simplicity will buy you some speed even if you end up searching over a few more objects than absolutely necessary! Things get a big harder if your objects vary greatly in size - for example if you're trying to use the same engine to deal with bullets, mice, humans, giant monsters, vehicles, asteroids, planets, etc. If that's the case, a common accepted (but ugly) approach is to have different 'modes' of play depending on the type of situation you're in. Short of that, one idea might be to use a large grid with a binary-tree subdivision of grid cells after they accumulate too many small objects. One aside: if you're using floating point coordinates, you need to be careful with precision and rounding issues for your grid size, since points close to the origin have a lot more precision than those far away, which could lead to errors where grid cells miss some objects. A: Here is a free book available online that will answer your question. Specifically look at Chapter 18 on collision detection and intersection. A: I don't know anything about games programming, but I would imagine (based on intuition and what I've read in the past) that a complete grid will get very inefficient for large spaces; you'll lose out in both storage, and also in time, because you'll melt the cache. STL containers are fundamentally one-dimensional. Yes, things like set and map allow you to define arbitrary sort relationships, but it's still ordered in only one dimension. If you want to do better, you'll probably need to use a quad-tree, a kd-tree, or something like that.
A container for accessing contents by 2d/3d coordinates
There are a lot of games that can generally be viewed as a bunch of objects spread out through space, and a very common operation is to pick all objects in a sub-area. The typical example would be a game with tons of units across a large map, and an explosion that affects units in a certain radius. This requires picking every unit in the radius in order to apply the effects of the explosion. Now, there are several ways to store objects that allows efficiently picking a sub-area. The easiest method is probably to divide the map into a grid; picking units in an area would involve selecting only the parts of the grid that is affected, and do a fine-grained coordinate check grid tiles that aren't 100% inside the area. What I don't like about this approach is answering "How large should the grid tiles be?" Too large, and efficiency may become a real problem. Too small, and the grid takes up tons of memory if the game world is large enough (and can become ridiculous if the game is 3d). There may not even be a suitable golden mean. The obvious solution to the above is to make a large grid with some kind of intelligent subdivision, like a pseudo tree-structure. And it is at this point I know for sure I am far into premature optimization. (Then there are proper dynamic quad/octrees, but that's even more complex to code and I'm not even confident it will perform any better.) So my question is: Is there a standard solution to the above problem? Something, in the lines of an STL container, that can just store any object with a coordinate, and retreive a list of objects within a certain area? It doesn't have to be different than what I described above, as long as it's something that has been thought out and deemed "good enough" for a start. Bonus points if there is an implementation of the algorithm in Python, but C would also do.
[ "The first step to writing a practical program is accepting that choices for some constants come from real-world considerations and not transcendent mathematical truths. This especially applies to game design/world simulation type coding, where you'd never get anywhere if you persisted in trying to optimally model ...
[ 1, 0, 0 ]
[]
[]
[ "c", "containers", "python" ]
stackoverflow_0003691278_c_containers_python.txt
Q: How to know the path the script the python run? sys.arg[0] gives me the python script. For example 'python hello.py' returns hello.py for sys.arg[0]. But I need to know where the hello.py is located in full path. How can I do that with python? A: os.path.abspath(sys.argv[0]) A: import sys print(sys.path[0]) From the docs: As initialized upon program startup, the first item of this list, sys.path[0], is the directory containing the script that was used to invoke the Python interpreter. A: You can use __file__, a variable that contains the full path to the module from which you access it. This doesn't necessarily have to end with the ".py" extension, but can also be ".pyc" (or None). There is also documentation available on __file__.
How to know the path the script the python run?
sys.arg[0] gives me the python script. For example 'python hello.py' returns hello.py for sys.arg[0]. But I need to know where the hello.py is located in full path. How can I do that with python?
[ "os.path.abspath(sys.argv[0])\n\n", "import sys\nprint(sys.path[0])\n\nFrom the docs:\n\nAs initialized upon program startup,\n the first item of this list, sys.path[0],\n is the directory containing the script\n that was used to invoke the Python\n interpreter.\n\n", "You can use __file__, a variable that ...
[ 6, 4, 3 ]
[]
[]
[ "path", "python" ]
stackoverflow_0003691921_path_python.txt
Q: How to display user error in Python What is the best way (standard) to display an error to the user in Python (for example: bad syntax, invalid arguments, logic errors)? The method should print the error in the standard error and exit the program. A: In small programs, I use something like this: import sys def error(message): sys.stderr.write("error: %s\n" % message) sys.exit(1) For bigger tools, I use the logging package. def error(message): logging.error('error: ', message) sys.exit(1) A: In Python 2, for example: import sys print>>sys.stderr, "Found", numerrs, "errors in the input." sys.exit(1) In Python 3 (or 2.6 or 2.7 with the from __future__ import print_function statement at the top of your module), print becomes a function and the syntax for "printing to standard error" is now print("Found", numerrs, "errors in the input.", file=sys.stderr) (a somewhat more friendly syntax than the strange >> needed in Python 2;-). The (small) advantage of print versus (say) sys.stderr.write is that you get "all the modern conveniences": all parts of the error message are automatically turned into strings, they're output with space separators, and a line-end is output for you at the end (unless you specifically request otherwise). To use sys.stderr.write, you need to build the exact string to output, typically using string-formatting constructs -- not a big deal, of course, just a small matter of convenience. logging is usually preferred, but not when you specifically want the error message to go to standard error, and to standard error only: logging offers many, many more possibilities (send messages of various severity, filter some, put some to files, and so on), but therefore it's inevitably a little bit more complex.
How to display user error in Python
What is the best way (standard) to display an error to the user in Python (for example: bad syntax, invalid arguments, logic errors)? The method should print the error in the standard error and exit the program.
[ "In small programs, I use something like this:\nimport sys\n\ndef error(message):\n sys.stderr.write(\"error: %s\\n\" % message)\n sys.exit(1)\n\nFor bigger tools, I use the logging package.\ndef error(message):\n logging.error('error: ', message)\n sys.exit(1)\n\n", "In Python 2, for example:\nimport...
[ 4, 4 ]
[]
[]
[ "python", "standards" ]
stackoverflow_0003691798_python_standards.txt
Q: "%s" % format vs "{0}".format() vs "?" format In this post about SQLite, aaronasterling told me that cmd = "attach \"%s\" as toMerge" % "b.db" : is wrong cmd = 'attach "{0}" as toMerge'.format("b.db") : is correct cmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', )) : is right thing But, I've thought the first and second are the same. What are the differences between those three? A: "attach \"%s\" as toMerge" % "b.db" You should use ' instead of ", so you don't have to escape. You used the old formatting strings that are deprecated. 'attach "{0}" as toMerge'.format("b.db") This uses the new format string feature from newer Python versions that should be used instead of the old one if possible. "attach ? as toMerge"; cursor.execute(cmd, ('b.db', )) This one omits string formatting completely and uses a SQLite feature instead, so this is the right way to do it. Big advantage: no risk of SQL injection A: The first and second produce the same result, but the second method is prefered for formatting strings in newer versions of Python. However the third is the better approach here because it uses parameters instead of manipulating strings. This is both faster and safer. A: Because it is not being escaped. If you replaced the b.db with user input, it would leave you vulnerable to SQL injection.
"%s" % format vs "{0}".format() vs "?" format
In this post about SQLite, aaronasterling told me that cmd = "attach \"%s\" as toMerge" % "b.db" : is wrong cmd = 'attach "{0}" as toMerge'.format("b.db") : is correct cmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', )) : is right thing But, I've thought the first and second are the same. What are the differences between those three?
[ "\"attach \\\"%s\\\" as toMerge\" % \"b.db\"\n\nYou should use ' instead of \", so you don't have to escape.\nYou used the old formatting strings that are deprecated.\n'attach \"{0}\" as toMerge'.format(\"b.db\")\n\nThis uses the new format string feature from newer Python versions that should be used instead of th...
[ 20, 6, 3 ]
[]
[]
[ "pysqlite", "python", "string_formatting" ]
stackoverflow_0003691975_pysqlite_python_string_formatting.txt
Q: How to guess out the grammars of a list of sentences generated by some way? I have a lost of sentences generated from http://www.ywing.net/graphicspaper.php, a random computer graphics paper title generator, some of example sentences sorted are as following: Abstract Ambient Occlusion using Texture Mapping Abstract Ambient Texture Mapping Abstract Anisotropic Soft Shadows Abstract Approximation Abstract Approximation of Adaptive Soft Shadows using Culling Abstract Approximation of Ambient Occlusion using Hardware-accelerated Clustering Abstract Approximation of Distributed Surfaces using Estimation Abstract Approximation of Geometry for Texture-mapped Ambient Occlusion Abstract Approximation of Mipmaps for Opacity Abstract Approximation of Occlusion Fields for Subsurface Scattering Abstract Approximation of Soft Shadows using Reflective Texturing Abstract Arbitrary Rendering Abstract Attenuation and Displacement Mapping of Geometry Abstract Attenuation of Ambient Occlusion using View-dependent Texture Mapping Abstract Attenuation of Light Fields for Mipmaps Abstract Attenuation of Non-linear Ambient Occlusion Abstract Attenuation of Pre-computed Mipmaps using Re-meshing - ... I would like to try reverse engineering the grammar behind and learn how to do it in some sort of ways, like in common lisp way or NLTK way. Any ideas about that? -- Drake A: You may be interested in Alignment-Based Learning by Menno van Zaanen. It has been years since I read his papers, but the basic idea is to find a common substring assign it a grammar rule rewrite the text to use this rule check whether rewritten-text+grammar is shorter than original-text. Run this for all combinations of all common substrings to find the best grammar. This is a bit like what an optimal compression algorithm would do. The theory behind it is Minimum Description Length. A: This seems to be an interesting problem. How ever, I was under the impression that it is not easy to guess a generator from it's generated sequence of bits. What you can get is a model that may be or may not be a close approximation of the original generator. The approximation will be closer when a large number of sequences generated is processed. A simple technique would be to create a parse tree and create a vocabulary in each portion of the tree. Some thing like this: Abstract |--------| |Ambient , Anisotropic,(Approximation, Attenuation) | of | xxxx yyyy | | using for xxxx -> list of vocabularies yyyy -> list of vocabularies A: There are approaches to learning grammar of a language given a number of sentences based on genetic programming. E.g., Learning Context-Free Grammars using an Evolutionary Approach. Also wikipedia lists some other approaches.
How to guess out the grammars of a list of sentences generated by some way?
I have a lost of sentences generated from http://www.ywing.net/graphicspaper.php, a random computer graphics paper title generator, some of example sentences sorted are as following: Abstract Ambient Occlusion using Texture Mapping Abstract Ambient Texture Mapping Abstract Anisotropic Soft Shadows Abstract Approximation Abstract Approximation of Adaptive Soft Shadows using Culling Abstract Approximation of Ambient Occlusion using Hardware-accelerated Clustering Abstract Approximation of Distributed Surfaces using Estimation Abstract Approximation of Geometry for Texture-mapped Ambient Occlusion Abstract Approximation of Mipmaps for Opacity Abstract Approximation of Occlusion Fields for Subsurface Scattering Abstract Approximation of Soft Shadows using Reflective Texturing Abstract Arbitrary Rendering Abstract Attenuation and Displacement Mapping of Geometry Abstract Attenuation of Ambient Occlusion using View-dependent Texture Mapping Abstract Attenuation of Light Fields for Mipmaps Abstract Attenuation of Non-linear Ambient Occlusion Abstract Attenuation of Pre-computed Mipmaps using Re-meshing - ... I would like to try reverse engineering the grammar behind and learn how to do it in some sort of ways, like in common lisp way or NLTK way. Any ideas about that? -- Drake
[ "You may be interested in Alignment-Based Learning by Menno van Zaanen. It has been years since I read his papers, but the basic idea is to \n\nfind a common substring\nassign it a grammar rule\nrewrite the text to use this rule\ncheck whether rewritten-text+grammar is shorter than original-text.\n\nRun this for al...
[ 1, 0, 0 ]
[]
[]
[ "lisp", "nlp", "python" ]
stackoverflow_0003689855_lisp_nlp_python.txt
Q: How do I access outer functions variables inside a closure(python 2.6)? From wikipedia I need to access outer functions variables in a similar manner as using the 'nonlocal' keyword from python 3.x. Is there some way to do that in python 2.6? (Not necessarily using the nonlocal keyword) A: I always use helper objects in that case: def outerFunction(): class Helper: val = None helper = Helper() def innerFunction(): helper.val = "some value" This also comes in handy when you start a new thread that should write a value to the outer function scope. In that case, helper would be passed as an argument to innerFunction (the thread's function).
How do I access outer functions variables inside a closure(python 2.6)?
From wikipedia I need to access outer functions variables in a similar manner as using the 'nonlocal' keyword from python 3.x. Is there some way to do that in python 2.6? (Not necessarily using the nonlocal keyword)
[ "I always use helper objects in that case:\ndef outerFunction():\n class Helper:\n val = None\n helper = Helper()\n\n def innerFunction():\n helper.val = \"some value\"\n\nThis also comes in handy when you start a new thread that should write a value to the outer function scope. In that case,...
[ 5 ]
[]
[]
[ "python", "python_2.6", "python_nonlocal" ]
stackoverflow_0003692357_python_python_2.6_python_nonlocal.txt
Q: Rename dictionary keys/values in python What I'm trying to do is this. I have a dictionary laid out as such: legJointConnectors = {'L_hip_jnt': ['L_knee_jnt'], 'L_knee_jnt': ['L_ankle_jnt'], 'L_ankle_jnt': ['L_ball_jnt'], 'L_ball_jnt': ['L_toe_jnt']} What I want to be able to do is iterate through this, but change the L_ to R_. Here's how I tried to do it, but it failed, because it's expecting a string and I'm passing it a list. for key, value in legJointConnectors.iteritems(): if side == 'L': cmds.connectJoint(value, key, pm=True) else: key = re.sub('L_', 'R_', key) value = re.sub('L_', 'R_', value) cmds.connectJoint(value, key, pm=True) Obviously I'm not doing this correctly, so how can I do this? Should I create an empty dictionary and populate it with the necessary data on the fly? Or is there a better way to do it? Thanks for the help! [edit] The if side == 'L' is testing to see what side we're currently working on. This script is being used within Maya, so I'm creating joints based on the side and then connecting them. Based off of KennyTM's suggestion I tried this: for key, value in legJointConnectors.iteritems(): if side == 'L': cmds.connectJoint(value, key, pm=True) else: for v in value: value = 'R_' + v[2:] for k in key: key = 'R_' + k[2:] print key print value but while it returns the correct key, the value returns as R_ A: Do the substitution on every element of the list then. for key, value in legJointConnectors.iteritems(): if side != 'L': key = 'R_' + key[2:] value = ['R_' + v[2:] for v in value] cmds.connectJoint(value, key, pm=True) (BTW, it is better to use v.replace('L_', 'R_'), or just 'R_' + v[2:] to perform the replacement then using regex for this.)
Rename dictionary keys/values in python
What I'm trying to do is this. I have a dictionary laid out as such: legJointConnectors = {'L_hip_jnt': ['L_knee_jnt'], 'L_knee_jnt': ['L_ankle_jnt'], 'L_ankle_jnt': ['L_ball_jnt'], 'L_ball_jnt': ['L_toe_jnt']} What I want to be able to do is iterate through this, but change the L_ to R_. Here's how I tried to do it, but it failed, because it's expecting a string and I'm passing it a list. for key, value in legJointConnectors.iteritems(): if side == 'L': cmds.connectJoint(value, key, pm=True) else: key = re.sub('L_', 'R_', key) value = re.sub('L_', 'R_', value) cmds.connectJoint(value, key, pm=True) Obviously I'm not doing this correctly, so how can I do this? Should I create an empty dictionary and populate it with the necessary data on the fly? Or is there a better way to do it? Thanks for the help! [edit] The if side == 'L' is testing to see what side we're currently working on. This script is being used within Maya, so I'm creating joints based on the side and then connecting them. Based off of KennyTM's suggestion I tried this: for key, value in legJointConnectors.iteritems(): if side == 'L': cmds.connectJoint(value, key, pm=True) else: for v in value: value = 'R_' + v[2:] for k in key: key = 'R_' + k[2:] print key print value but while it returns the correct key, the value returns as R_
[ "Do the substitution on every element of the list then.\nfor key, value in legJointConnectors.iteritems():\n if side != 'L':\n key = 'R_' + key[2:]\n value = ['R_' + v[2:] for v in value]\n cmds.connectJoint(value, key, pm=True)\n\n(BTW, it is better to use v.replace('L_', 'R_'), or just 'R_' + ...
[ 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003692430_dictionary_python.txt
Q: Security considerations - office website/portal on GAE If one needs to create an office website (that serves as a platform for clients/customers/employees) to login and access shared data, what are the security considerations. to give you some more detail, The office portal has been developed in django/python and hosted through GAE. Essentially, the end point comes with a login/password to enter into the portal and access data. I would like to know: a) what are the things we can do to bring in a high level of security. Essentially the data is critical and hence need to be accessed by authorized people only. So would like to make it such that "The app is as safe as - how safely one keeps his password. Meaning, the only way to enter the system (unauthorized) is through a password leak (by the person) and not in any hackish way." :) b) can we host the apps on GAE (appspot.com) with https? c) are there better ways to secure other than passwords (i have heard about ssh keys/certificates). But the ultimate users may not be highly tech savvy. A: There is always the choice between usabiity and secutity. The more security features you implent, the more difficult it gets to use it. can we host the apps on GAE (appspot.com) with https? Yes, but not on your own domain, only on appspot.com. If you are serving your app off of an own domain, you must direct all secure traffic through your app's appspot domain (on your own domain, you'd have to buy a SSL certificate, and you would need a dedicated IP etc.). If you really have to, there are ways to route SSL traffic over your own domain, but as this requires another server running something like stunnel, it gives attackers another attack target. If your app has username/password authentication, the app is really as safe as how safely one keeps his password, if you have no bugs in your code that could be exploited. About the "hackish way": on GAE, you don't have to care about server security, the only possible attack target is your code. These are some strategies for securing your app: good QA and code review to find critical bugs; Django has already built-in protection against most trivial attacks like XSRF and SQL injection, so look at the parts of your own code that are related to critical data and authentication think of other authentication methods like client side certificates (easy to use for the end user, most browser support this natively and modern operating systems have a certificate storage; probably not an easy thing to do on GAE) the weakest point of every secure enviromnent is the user, so you should inform the users about good practices on handling sensitive data and passwords (BTW, requiring a password change every few months does not improves security at all as it usally results in users writing down their passwords as they can't remember it, you loose more security than you gain) you should have good intrusion detection to lock out an attacker as soon as possible, as example behaviour analysis; Example: if a user from the USA logs in from an IP in Estonia, this is suspicious network access restrictions: you could block all IP ranges except those from your enterprise of accessing critical data, if a password gets leaked, this minimizes the possible impact improve end user security: if one of the users have a trojan on their computer that makes screen captures or keylogs, all your security is lost as the attacker could just watch the user while he's vieweing sensitive data; you should have a good security police in your enterprise force users to access your site over SSL, you should not let the users choose if they prefer security ocer comfort of not
Security considerations - office website/portal on GAE
If one needs to create an office website (that serves as a platform for clients/customers/employees) to login and access shared data, what are the security considerations. to give you some more detail, The office portal has been developed in django/python and hosted through GAE. Essentially, the end point comes with a login/password to enter into the portal and access data. I would like to know: a) what are the things we can do to bring in a high level of security. Essentially the data is critical and hence need to be accessed by authorized people only. So would like to make it such that "The app is as safe as - how safely one keeps his password. Meaning, the only way to enter the system (unauthorized) is through a password leak (by the person) and not in any hackish way." :) b) can we host the apps on GAE (appspot.com) with https? c) are there better ways to secure other than passwords (i have heard about ssh keys/certificates). But the ultimate users may not be highly tech savvy.
[ "There is always the choice between usabiity and secutity. The more security features you implent, the more difficult it gets to use it.\n\ncan we host the apps on GAE (appspot.com) with https?\n\nYes, but not on your own domain, only on appspot.com. If you are serving your app off of an own domain, you must direct...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python", "security" ]
stackoverflow_0003692526_django_google_app_engine_python_security.txt
Q: creating a masked array from text fields The numpy documentation shows an example of masking existing values with ma.masked a posteriori (after array creation), or creating a masked array from an list of what seem to be valid data types (integer if dtype=int). I am trying to read in data from a file (and requires some text manipulation) but at some point I will have a list of lists (or tuples) containing strings from which I want to make a numeric (float) array. An example of the data might be textdata='1\t2\t3\n4\t\t6' (typical flat text format after cleaning). One problem I have is that missing values may be encoded as '', which when trying to convert to float using the dtype argument, will tell me ValueError: setting an array element with a sequence. So I've created this function def makemaskedarray(X,missing='',fillvalue='-999.',dtype=float): arr = lambda x: x==missing and fillvalue or x mask = lambda x: x==missing and 1 or 0 triple = dict(zip(('data','mask','dtype'), zip(*[(map(arr,x),map(mask,x)) for x in X])+ [dtype])) return ma.array(**triple) which seems to do the trick: >>> makemaskedarray([('1','2','3'),('4','','6')]) masked_array(data = [[1.0 2.0 3.0] [4.0 -- 6.0]], mask = [[False False False] [False True False]], fill_value = 1e+20) Is this the way to do it? Or there is a built-in function? A: The way you're doing it is fine. (though you could definitely make it a bit more readable by avoiding building the temporary "triple" dict, just to expand it a step later, i.m.o.) The built-in way is to use numpy.genfromtxt. Depending on the amount of pre-processing you need to do to your text file, it may or may not do what you need. However, as a basic example: (Using StringIO to simulate a file...) from StringIO import StringIO import numpy as np txt_data = """ 1\t2\t3 4\t\t6 7t\8t\9""" infile = StringIO(txt_data) data = np.genfromtxt(infile, usemask=True, delimiter='\t') Which yields: masked_array(data = [[1.0 2.0 3.0] [4.0 -- 6.0] [7.0 8.0 9.0]], mask = [[False False False] [False True False] [False False False]], fill_value = 1e+20) One word of caution: If you do use tabs as your delimiter and an empty string as your missing value marker, you'll have issues with missing values at the start of a line. (genfromtxt essentially calls line.strip().split(delimiter)). You'd be better off using something like "xxx" as a marker for missing values, if you can.
creating a masked array from text fields
The numpy documentation shows an example of masking existing values with ma.masked a posteriori (after array creation), or creating a masked array from an list of what seem to be valid data types (integer if dtype=int). I am trying to read in data from a file (and requires some text manipulation) but at some point I will have a list of lists (or tuples) containing strings from which I want to make a numeric (float) array. An example of the data might be textdata='1\t2\t3\n4\t\t6' (typical flat text format after cleaning). One problem I have is that missing values may be encoded as '', which when trying to convert to float using the dtype argument, will tell me ValueError: setting an array element with a sequence. So I've created this function def makemaskedarray(X,missing='',fillvalue='-999.',dtype=float): arr = lambda x: x==missing and fillvalue or x mask = lambda x: x==missing and 1 or 0 triple = dict(zip(('data','mask','dtype'), zip(*[(map(arr,x),map(mask,x)) for x in X])+ [dtype])) return ma.array(**triple) which seems to do the trick: >>> makemaskedarray([('1','2','3'),('4','','6')]) masked_array(data = [[1.0 2.0 3.0] [4.0 -- 6.0]], mask = [[False False False] [False True False]], fill_value = 1e+20) Is this the way to do it? Or there is a built-in function?
[ "The way you're doing it is fine. (though you could definitely make it a bit more readable by avoiding building the temporary \"triple\" dict, just to expand it a step later, i.m.o.)\nThe built-in way is to use numpy.genfromtxt. Depending on the amount of pre-processing you need to do to your text file, it may or ...
[ 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0003692401_numpy_python_scipy.txt
Q: Storing passwords with python I have a program I'm writing in python, and I have the need to store some passwords. These passwords will be the passwords to ftp servers, so it's important that they're not just plainly visible to everybody. This also means that I can't store a non-reversible hash of the password like you would on a webserver, because I'm not checking if somebody inputs the right password, I'm just relaying the password to somebody else. So what's the best way to store passwords? I'm using python, and the program will be linux-only. A: You could use the system's key ring, e.g. GNOME key ring or KDE wallet. There's a Python module called keyring that supports multiple key ring providers. I have only tried it on Windows, where it doesn't yet work correctly. Seems like development isn't very active, but you should give it a try. You can also try the package "python-gnomekeyring" which is specific to GNOME and more low-level. A: Depending on the distribution you can probably store it in the keychain if one is available. Otherwise take a look at some of the encryption algorithms available (PGP/GPG, DES, AES etc) and their Python ports/modules but this is hard stuff which you have to get right. A: There's the convenient and insecure way: just store them as plaintext and if you are truly using FTP (and not, for example SFTP) then they will be as secure as the machine they are hosted upon (which means not really very secure). FTP was written in a time when sending a plaintext password over the wire was considered "safe enough"; those days are gone. Even encoding the plaintext passwords in the python source doesn't really help you as at some point you have to un-encode them. Secure methods require a little more setup. Here is a decent tutorial, I expect there are better ones. A: Check out netrc on Linux (use man or this) and then look at this Python module If the netrc has the appropriate information you can use ftp at the command line without entering user and password - they are looked up in the file. Some things to note: the file has be restricted to user read/write only (0600) or it may be rejected by ftp. If that works, then you are ready to use it from Python. A much better idea would be to avoid ftp altogether (where the password is sent in plain-text) and use sftp. Copy your public key from the machine running the Python script to each target machine and let ssh automatically login for you in a secure fashion.
Storing passwords with python
I have a program I'm writing in python, and I have the need to store some passwords. These passwords will be the passwords to ftp servers, so it's important that they're not just plainly visible to everybody. This also means that I can't store a non-reversible hash of the password like you would on a webserver, because I'm not checking if somebody inputs the right password, I'm just relaying the password to somebody else. So what's the best way to store passwords? I'm using python, and the program will be linux-only.
[ "You could use the system's key ring, e.g. GNOME key ring or KDE wallet.\nThere's a Python module called keyring that supports multiple key ring providers. I have only tried it on Windows, where it doesn't yet work correctly. Seems like development isn't very active, but you should give it a try. You can also try t...
[ 6, 2, 2, 0 ]
[ "I would recommend hashing the password a hash is a one way function so can't be worked back to find a plain text version of the password (unlike an encryption).\nMD5 is a algorithm that I like and is already implemented in Python. You could always add a salt to the hash like abdPasswordABDA where Password is the p...
[ -4 ]
[ "passwords", "python", "storage" ]
stackoverflow_0003691587_passwords_python_storage.txt
Q: How to properly store object reference in treemodel? I'm trying to store an object reference in the rows of a treemodel so that I can access and modify the data in the underlying data structure. What would be the proper way to do this? The only way I've found so far to accomplish this is to inherit my data structure nodes from gobject, and then store a gobject column in each row. Is there a more preferred way to do this? A: Model column type of: gobject.TYPE_PYOBJECT Can be anything!
How to properly store object reference in treemodel?
I'm trying to store an object reference in the rows of a treemodel so that I can access and modify the data in the underlying data structure. What would be the proper way to do this? The only way I've found so far to accomplish this is to inherit my data structure nodes from gobject, and then store a gobject column in each row. Is there a more preferred way to do this?
[ "Model column type of:\ngobject.TYPE_PYOBJECT\n\nCan be anything!\n" ]
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003653639_pygtk_python.txt
Q: Adding shared python packages to multiple virtualenvs Current Python Workflow I have pip, distribute, virtualenv, and virtualenvwrapper installed into my Python 2.7 site-packages (a framework Python install on Mac OS X). In my ~/.bash_profile I have the line export PIP_DOWNLOAD_CACHE=$HOME/.pip_download_cache This gives a workflow as follows: $ mkvirtualenv pip-test $ pip install nose # downloaded and installed from PyPi $ pip install mock # downloaded and installed from PyPi $ mkvirtualenv pip-test2 $ pip install nose # installed from pip's download cache $ pip install mock # installed from pip's download cache Questions Since I'm not downloading packages that have been previously installed in another virtualenv, this workflow saves time and bandwidth. However, it doesn't save disk space, since each package will be installed into each virtualenv. Therefore, I'm wondering: Question #1 Is there a modification to this workflow that would allow me to conserve disk space by having multiple virtualenvs reference one Python package that is not installed in my Python 2.7 site-packages? I've tried using add2virtualenv which is part of virtualenvwrapper. While this "adds the specified directories to the Python path for the currently-active virtualenv," it doesn't add any of the executables found in the virtualenv/bin directory. Therefore, the following will fail: $ mkvirtualenv pip-test3 $ add2virtualenv ~/.virtualenvs/pip-test/lib/python2.7/site-packages/nose/ $ nosetests # Fails since missing ~/.virtualenvs/pip-test3/bin/nosetests Question #2 Am I missing something about the way add2virtualenv works? Question #1 Rephrased Is there a better method than add2virtualenv that allows multiple virtualenvs to reference one Python package that is not installed in my Python 2.7 site-packages? Question #3 If there is a method to install a shared Python package into multiple virtualenvs, is there a performance penalty that isn't there compared to installing Python packages separately into each virtualenv? Question #4 Should I just give up on conserving disk space and stick with my current workflow? A: Unless you are doing development on an embedded system, I find that chasing disk space in this way is always counter-productive. It took me a long time to reach this realization, because I grew up when a very large hard drive was a few megabytes in size, and RAM was measured in K. But today, unless you are under very special and unusual constraints, the benefit of having your projects be orthogonal (you can delete any directories on your system anywhere outside your project, and have its Python packages still there) seems to always far outweigh the disk-space benefit that, if you're busy developing, you'll never — in my experience — even notice anyway. So I guess that's the lesson I'm offering from my own experience: you'll never notice the disk space you've lost, but you will notice it if trying to clean up a directory in one place on your disk breaks projects under development somewhere else.
Adding shared python packages to multiple virtualenvs
Current Python Workflow I have pip, distribute, virtualenv, and virtualenvwrapper installed into my Python 2.7 site-packages (a framework Python install on Mac OS X). In my ~/.bash_profile I have the line export PIP_DOWNLOAD_CACHE=$HOME/.pip_download_cache This gives a workflow as follows: $ mkvirtualenv pip-test $ pip install nose # downloaded and installed from PyPi $ pip install mock # downloaded and installed from PyPi $ mkvirtualenv pip-test2 $ pip install nose # installed from pip's download cache $ pip install mock # installed from pip's download cache Questions Since I'm not downloading packages that have been previously installed in another virtualenv, this workflow saves time and bandwidth. However, it doesn't save disk space, since each package will be installed into each virtualenv. Therefore, I'm wondering: Question #1 Is there a modification to this workflow that would allow me to conserve disk space by having multiple virtualenvs reference one Python package that is not installed in my Python 2.7 site-packages? I've tried using add2virtualenv which is part of virtualenvwrapper. While this "adds the specified directories to the Python path for the currently-active virtualenv," it doesn't add any of the executables found in the virtualenv/bin directory. Therefore, the following will fail: $ mkvirtualenv pip-test3 $ add2virtualenv ~/.virtualenvs/pip-test/lib/python2.7/site-packages/nose/ $ nosetests # Fails since missing ~/.virtualenvs/pip-test3/bin/nosetests Question #2 Am I missing something about the way add2virtualenv works? Question #1 Rephrased Is there a better method than add2virtualenv that allows multiple virtualenvs to reference one Python package that is not installed in my Python 2.7 site-packages? Question #3 If there is a method to install a shared Python package into multiple virtualenvs, is there a performance penalty that isn't there compared to installing Python packages separately into each virtualenv? Question #4 Should I just give up on conserving disk space and stick with my current workflow?
[ "Unless you are doing development on an embedded system, I find that chasing disk space in this way is always counter-productive. It took me a long time to reach this realization, because I grew up when a very large hard drive was a few megabytes in size, and RAM was measured in K. But today, unless you are under v...
[ 11 ]
[]
[]
[ "pip", "python", "virtualenv", "virtualenvwrapper" ]
stackoverflow_0003692632_pip_python_virtualenv_virtualenvwrapper.txt
Q: from list to select menu in django I thought I had it figured out but now I'm missing something. First I have a QuerySet, records records = Record.objects.all() Now I want to make this into a list of one of the columns of the table, columnA alist = records.values_list('columnA') And then I want to pass this list in as a parameter to a custom form. FilterForm(alist) Here's my form class FilterForm(forms.Form,list): numbers = forms.ChoiceField(list) but keep getting an error that 'type' object is not iterable. I'm not sure the problem has to do with the passing of the list because when I try and run this code in the shell, I get the error message when just importing the FilterForm EDIT: I changed my FilterForm so now it looks like this. class FilterForm(forms.Form): def __init__(self,numbers): number = forms.ChoiceField(numbers) so now I think it's more evident what I'm trying to do, pass in a list to the FilterForm. However when I render my template and pass the form, no form field shows up. No error message though EDIT EDIT: Also tried this, saw it online class FilterForm(forms.Form): number = forms.ChoiceField() def __init__(self,numbers): super(FilterForm,self).__init__() self.fields['number'].choices=numbers but error: Exception Type: TemplateSyntaxError Exception Value: Caught ValueError while rendering: need more than 1 value to unpack A: The problem is the word list in this line: numbers = forms.ChoiceField(list) You need to provide a specific list to ChoiceField. A: Here's an error: class FilterForm(forms.Form,list): numbers = forms.ChoiceField(list) You make FilterForm a subclass of forms.Form and list; then you expect list to be available as argument to the ChoiceField. I think you are looking for dynamic ChoiceFields. Further reading: django model/modelForm - How to get dynamic choices in choiceField?
from list to select menu in django
I thought I had it figured out but now I'm missing something. First I have a QuerySet, records records = Record.objects.all() Now I want to make this into a list of one of the columns of the table, columnA alist = records.values_list('columnA') And then I want to pass this list in as a parameter to a custom form. FilterForm(alist) Here's my form class FilterForm(forms.Form,list): numbers = forms.ChoiceField(list) but keep getting an error that 'type' object is not iterable. I'm not sure the problem has to do with the passing of the list because when I try and run this code in the shell, I get the error message when just importing the FilterForm EDIT: I changed my FilterForm so now it looks like this. class FilterForm(forms.Form): def __init__(self,numbers): number = forms.ChoiceField(numbers) so now I think it's more evident what I'm trying to do, pass in a list to the FilterForm. However when I render my template and pass the form, no form field shows up. No error message though EDIT EDIT: Also tried this, saw it online class FilterForm(forms.Form): number = forms.ChoiceField() def __init__(self,numbers): super(FilterForm,self).__init__() self.fields['number'].choices=numbers but error: Exception Type: TemplateSyntaxError Exception Value: Caught ValueError while rendering: need more than 1 value to unpack
[ "The problem is the word list in this line:\nnumbers = forms.ChoiceField(list)\n\nYou need to provide a specific list to ChoiceField.\n", "Here's an error:\nclass FilterForm(forms.Form,list):\n numbers = forms.ChoiceField(list)\n\nYou make FilterForm a subclass of forms.Form and list; then you expect list to b...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003692922_django_python.txt
Q: python qt, display text/label above another widget(phonon) I'm making a video player using PySide which is a python bind to the Qt framework. I'm using phonon(a module) to display the video and I want to display text above the video as a subtitle. How can I put another widget above my phonon widget. Is opengl an option? A: If you just create your label and set the phonon widget as the parent, the label should appear over it. QLabel *label = new QLabel(phononWidget); label->setText("Text over video!"); (I realize this is C++ and you are working in Python but it should be similar) Update: The above will not work for hardware accelerated video playback. An alternative that does work is to create a graphics scene and add the video widget or player to the scene and use a QGraphicsTextItem for the text. Setting the viewport to a QGLWidget will enable hardware acceleration: QGraphicsScene *scene = new QGraphicsScene(this); Phonon::VideoPlayer *v = new Phonon::VideoPlayer(); v->load(Phonon::MediaSource("video_file")); QGraphicsProxyWidget *pvideoWidget = scene->addWidget(v); QGraphicsView *view = new QGraphicsView(scene); view->setViewport(new QGLWidget); //Enable hardware acceleration! QGraphicsTextItem *label = new QGraphicsTextItem("Text Over Video!", pvideoWidget); label->moveBy(100, 100); v->play();
python qt, display text/label above another widget(phonon)
I'm making a video player using PySide which is a python bind to the Qt framework. I'm using phonon(a module) to display the video and I want to display text above the video as a subtitle. How can I put another widget above my phonon widget. Is opengl an option?
[ "If you just create your label and set the phonon widget as the parent, the label should appear over it.\nQLabel *label = new QLabel(phononWidget);\nlabel->setText(\"Text over video!\");\n\n(I realize this is C++ and you are working in Python but it should be similar)\nUpdate:\nThe above will not work for hardware ...
[ 5 ]
[]
[]
[ "pyqt", "pyside", "python", "qt", "widget" ]
stackoverflow_0003692712_pyqt_pyside_python_qt_widget.txt
Q: How to dynamically define functions? I have functions like this: def activate_field_1(): print 1 def activate_field_2(): print 2 def activate_field_3(): print 3 How do I define activate_field_[x] for x=1:10, without typing out each one of them? I'd much rather pass a parameter, of course, but for my purposes this is not possible. A: Do you want to define these individually in your source file, statically? Then your best option would be to write a script to generate them. If on the other hand you want these functions at runtime you can use a higher order function. For e.g. >>> def make_func(value_to_print): ... def _function(): ... print value_to_print ... return _function ... >>> f1 = make_func(1) >>> f1() 1 >>> f2 = make_func(2) >>> f2() 2 You can generate a list of these and store, again at runtime. >>> my_functions = [make_func(i) for i in range(1, 11)] >>> for each in my_functions: ... each() ... 1 2 3 ... A: Here's something that produces function names exactly like you wanted (and is a little simpler than the Dynamic/runtime method creation's accepted answer mentioned in @Goutham's now deleted answer): FUNC_TEMPLATE = """def activate_field_{0}(): print({0})""" for x in range(1, 11): exec(FUNC_TEMPLATE.format(x)) >>> activate_field_1() 1 >>> activate_field_7() 7 In Python versions 3.6+, it can be written as shown below using so-called f-string literals: for x in range(1, 11): exec(f"""def activate_field_{x}(): print({x})""") A: You may put new symbols into the dictionary of current variable bindings returned by vars(): for i in range(1, 11): def f(x): def g(): print x return g vars()['activate_field_%d' % i] = f(i) >>> activate_field_3() 3 But this trick is generally not recommented unless you definitely sure you need it. A: Maybe you could adapt this recipe for your needs. from functools import partial class FunctionPool: def __init__(self,function): self.function = function def __getitem__(self,item): return partial(self.function,item) >>> @FunctionPool def func(item,param): print "function#{item} called with {param}".format( item = item, param = param ) >>> f = func[2] >>> f(3) function#2 called with 3
How to dynamically define functions?
I have functions like this: def activate_field_1(): print 1 def activate_field_2(): print 2 def activate_field_3(): print 3 How do I define activate_field_[x] for x=1:10, without typing out each one of them? I'd much rather pass a parameter, of course, but for my purposes this is not possible.
[ "Do you want to define these individually in your source file, statically? Then your best option would be to write a script to generate them.\nIf on the other hand you want these functions at runtime you can use a higher order function. For e.g. \n>>> def make_func(value_to_print):\n... def _function():\n... ...
[ 22, 11, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003687682_python.txt
Q: Python GTK/threading/sockets error I'm trying to build a Python application using pyGTK, treads, and sockets. I'm having this weird error, but given all the modules involved, I'm not entirely sure where the error is. I did a little debugging with some print statements to narrow things down a bit and I think the error is somewhere in this snippet of code: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect(("localhost", 5005)) self.collectingThread = threading.Thread(target=self.callCollect) self.collectingThread.daemon = True self.collectingThread.start() def callCollect(self): gobject.timeout_add(500, self.collectData) def collectData(self): print "hello" try: print self.sock.recv(1024) except: print "except" print "return" return True So basically what I'm trying to do is setup a socket, connect to a "server" script (which is really just another python script running locally), and create a separate thread to collect all incoming data from the server script. This thread is set to run the collectData method every 500 milliseconds. After inserting the print statements into the collectData method here is what I notice when running the program: -Initially the GUI is fully functional -then the following is printed in the terminal: hello **all data received from server script and printed here** return hello -after the text is printed in the terminal, the GUI becomes completely nonfunctional (buttons cant be pressed, etc.) and I have to force quit to close the application What seems to be happening is that the thread prints "hello", prints the data from the server, and prints "return". 500 milliseconds later, it runs the collectData method again, prints "hello", then tries to print data from the server. However, because there is no data left it raises an exception, but for some unknown reason it doesn't execute the code in the exception block and everything just hangs from there. Any idea on what is going wrong? A: timeout_add is scheduling the action to happen on the main thread -- so the recv just blocks the main thread (when it's just waiting for data) and therefore the GUI, so, no exception unless you put a timeout or set the socket to non-blocking. You need to delegate the receiving to the thread from the scheduled action rather than viceversa to get the effect you're after: have the thread e.g. wait on an event object, and the scheduled action signal that event every 500 milliseconds. A: No, obviously the sock.recv call blocks because the socket wasn't closed yet and socket receives are blocking by default. Make sure you close the connection at some point. It would make more sense to run the receive call in a new thread, or else it might block the GUI because your current implementation runs the recv call in the GUI thread (using timeout_add). The way you're currently doing it only makes sense if the answer is received very fast and/or you have to access widgets. By the way, creating a new thread for calling gobject.timeout_add is totally unnecessary. timeout_add() and idle_add() register the specified callback function and return immediately. The GTK event loop then automatically executes the callback after the timeout (or on idle status for idle_add).
Python GTK/threading/sockets error
I'm trying to build a Python application using pyGTK, treads, and sockets. I'm having this weird error, but given all the modules involved, I'm not entirely sure where the error is. I did a little debugging with some print statements to narrow things down a bit and I think the error is somewhere in this snippet of code: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect(("localhost", 5005)) self.collectingThread = threading.Thread(target=self.callCollect) self.collectingThread.daemon = True self.collectingThread.start() def callCollect(self): gobject.timeout_add(500, self.collectData) def collectData(self): print "hello" try: print self.sock.recv(1024) except: print "except" print "return" return True So basically what I'm trying to do is setup a socket, connect to a "server" script (which is really just another python script running locally), and create a separate thread to collect all incoming data from the server script. This thread is set to run the collectData method every 500 milliseconds. After inserting the print statements into the collectData method here is what I notice when running the program: -Initially the GUI is fully functional -then the following is printed in the terminal: hello **all data received from server script and printed here** return hello -after the text is printed in the terminal, the GUI becomes completely nonfunctional (buttons cant be pressed, etc.) and I have to force quit to close the application What seems to be happening is that the thread prints "hello", prints the data from the server, and prints "return". 500 milliseconds later, it runs the collectData method again, prints "hello", then tries to print data from the server. However, because there is no data left it raises an exception, but for some unknown reason it doesn't execute the code in the exception block and everything just hangs from there. Any idea on what is going wrong?
[ "timeout_add is scheduling the action to happen on the main thread -- so the recv just blocks the main thread (when it's just waiting for data) and therefore the GUI, so, no exception unless you put a timeout or set the socket to non-blocking.\nYou need to delegate the receiving to the thread from the scheduled act...
[ 1, 0 ]
[]
[]
[ "gtk", "multithreading", "python", "sockets" ]
stackoverflow_0003693083_gtk_multithreading_python_sockets.txt
Q: how to define a structure like in C I am going to define a structure and pass it into a function: In C: struct stru { int a; int b; }; s = new stru() s->a = 10; func_a(s); How this can be done in Python? A: Unless there's something special about your situation that you're not telling us, just use something like this: class stru: def __init__(self): self.a = 0 self.b = 0 s = stru() s.a = 10 func_a(s) A: use named tuples if you are ok with an immutable type. import collections struct = collections.namedtuple('struct', 'a b') s = struct(1, 2) Otherwise, just define a class if you want to be able to make more than one. A dictionary is another canonical solution. If you want, you can use this function to create mutable classes with the same syntax as namedtuple def Struct(name, fields): fields = fields.split() def init(self, *values): for field, value in zip(fields, values): self.__dict__[field] = value cls = type(name, (object,), {'__init__': init}) return cls you might want to add a __repr__ method for completeness. call it like s = Struct('s', 'a b'). s is then a class that you can instantiate like a = s(1, 2). There's a lot of room for improvement but if you find yourself doing this sort of stuff alot, it would pay for itself. A: Sorry to answer the question 5 days later, but I think this warrants telling. Use the ctypes module like so: from ctypes import * class stru(Structure): _fields_ = [ ("a", c_int), ("b", c_int), ] When you need to do something C-like (i.e. C datatypes or even use C DLLs), ctypes is the module. Also, it comes standard A: Use classes and code Python thinking in Python, avoid to just write the same thing but in another syntax. If you need the struct by how it's stored in memory, try module struct
how to define a structure like in C
I am going to define a structure and pass it into a function: In C: struct stru { int a; int b; }; s = new stru() s->a = 10; func_a(s); How this can be done in Python?
[ "Unless there's something special about your situation that you're not telling us, just use something like this:\nclass stru:\n def __init__(self):\n self.a = 0\n self.b = 0\n\ns = stru()\ns.a = 10\n\nfunc_a(s)\n\n", "use named tuples if you are ok with an immutable type.\nimport collections\n\ns...
[ 34, 12, 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003648442_python.txt
Q: Django/python is converting my post data from JavaScript When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending: info {'mid':1,'sid':27,'name':'aa','desc':'Enter info' } Yet when I access it in the django request I am seeing: u'{\'mid\':1,\'sid\':27,\'name\':\'aa\',\'desc\':\'Enter Info\'} When I try to parse this with json.loads it dies with an invalid JSON message. I am posting with: data.info = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }"; $.ajax({url: cmdAjaxAddress, type: "POST", data: data, success: function(txt) { result = txt; }, async: false }); I am reading the POST in django like this: if request.is_ajax() and request.method == 'POST': infoJson = request.POST['info'] info = json.loads(infoJson); Any help would be appreciated. A: How are you encoding your JSON string? The single quotes need to be double quotes, per the spec: In [40]: s1 = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }" In [41]: simplejson.loads(s1) JSONDecodeError: Expecting property name: line 1 column 1 (char 1) In [42]: s2 = '{"mid":1,"sid":27,"name":"aa","desc":"Enter info" }' In [43]: simplejson.loads(s2) Out[43]: {'desc': 'Enter info', 'mid': 1, 'name': 'aa', 'sid': 27}
Django/python is converting my post data from JavaScript
When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending: info {'mid':1,'sid':27,'name':'aa','desc':'Enter info' } Yet when I access it in the django request I am seeing: u'{\'mid\':1,\'sid\':27,\'name\':\'aa\',\'desc\':\'Enter Info\'} When I try to parse this with json.loads it dies with an invalid JSON message. I am posting with: data.info = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }"; $.ajax({url: cmdAjaxAddress, type: "POST", data: data, success: function(txt) { result = txt; }, async: false }); I am reading the POST in django like this: if request.is_ajax() and request.method == 'POST': infoJson = request.POST['info'] info = json.loads(infoJson); Any help would be appreciated.
[ "How are you encoding your JSON string? The single quotes need to be double quotes, per the spec:\nIn [40]: s1 = \"{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }\"\n\nIn [41]: simplejson.loads(s1)\nJSONDecodeError: Expecting property name: line 1 column 1 (char 1)\n\nIn [42]: s2 = '{\"mid\":1,\"sid\":27,\"nam...
[ 7 ]
[]
[]
[ "django", "javascript", "json", "python", "unicode" ]
stackoverflow_0003693621_django_javascript_json_python_unicode.txt
Q: How to detect if a file path is wrapped in " .. " with Python? I read the ini file to open a file in python. The thing is that the file info is sometimes inside the "..", but sometimes it's not. For example, fileA = "/a/b/c.txt" fileB = /a/b/d.txt Is there easy way to detect if a string is wrapped in "..", and return the string inside the quotation? A: The simple detection would involve checking s[:1] == s[-1:] == '"' (carefully phrasing it with slicing rather than indexing to avoid exceptions if s is an empty string), and the conditional removal of exactly one quote from each end if one is present at both ends is if s[:1] == s[-1:] == '"': s = s[1:-1] Alternatively, the approach in @Magnus's answer, as he says, removes all leading and trailing quote, and does so unconditionally; so, for example, if s starts with three quotes but doesn't end with any (and in all sort of other weird cases, outside of your specs as stated), the snippet in my answer won't alter s, @Magnus's will strip the three leading quotes. "You pay your money and you take your choice"... if you don't care one way or another (i.e. you're sure that the situation where the two answers differ is "totally and utterly impossible"...), then I think @Magnus's higher-abstraction-level approach is neater (but, it's a matter of style -- both his approach and mine are correct Python solutions when you don't care about unmatched or unbalanced quotes;-). A: To remove all leading and trailing quotes: fileA = fileA.strip('"')
How to detect if a file path is wrapped in " .. " with Python?
I read the ini file to open a file in python. The thing is that the file info is sometimes inside the "..", but sometimes it's not. For example, fileA = "/a/b/c.txt" fileB = /a/b/d.txt Is there easy way to detect if a string is wrapped in "..", and return the string inside the quotation?
[ "The simple detection would involve checking s[:1] == s[-1:] == '\"' (carefully phrasing it with slicing rather than indexing to avoid exceptions if s is an empty string), and the conditional removal of exactly one quote from each end if one is present at both ends is\nif s[:1] == s[-1:] == '\"':\n s = s[1:-1]\n...
[ 3, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003693744_python_string.txt
Q: How to check if user likes a given page on facebook, from an external site? I'm building an app using facebook likes, under GAE with python. I'd like do different actions if user likes the page or not: page_url=url if user likes page_url: #do something else: #do something else I'm interested in checking if the user already likes the page, not in the action of clicking the like button. Also I'd like to do this without requiring facebook connect. Thanks! A: Use GraphApi "me/likes" with the authenticated user, then search through the results and search for you your app / page id.
How to check if user likes a given page on facebook, from an external site?
I'm building an app using facebook likes, under GAE with python. I'd like do different actions if user likes the page or not: page_url=url if user likes page_url: #do something else: #do something else I'm interested in checking if the user already likes the page, not in the action of clicking the like button. Also I'd like to do this without requiring facebook connect. Thanks!
[ "Use GraphApi \"me/likes\" with the authenticated user, then search through the results and search for you your app / page id.\n" ]
[ 2 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0003690799_facebook_google_app_engine_python.txt
Q: Is this statically bound? Say that I have a C program and it has this line: int a = 12; Is the value of 12 bound to 'a' during compile time? Or is the value placed into memory during run time when the scope of the program hits 'a'? What about programming languages like Python and Ruby? Are there languages/instances where a value is statically bound to a variable? I've been thinking about this for a while now and I honestly can't think of a logical reason for statically binding a value to a primitive type. A: Compilers and virtual machines effectively "implement" programming languages. They only have to do what is specified by the language semantics and observable for a given program in order to be correct. When you write the definition statement int a = 12; in a C program, you are informing the compiler that there is a variable named a whose initial value is set to the constant literal twelve. If you never observe a, the compiler can completely get rid of it, because you can't tell the difference during program execution per the language specification. (For example, if you were to pause the program and scan the stack at that point, the value 12 need not be there at all. Its necessity for being on the machine stack is not part of the language specification.) If you observe a but find that it's impossible for your program to mutate its value, the compiler has inferred that it is actually static const and can perform an optimization called "constant propagation" to push a hard-coded twelve into the dependent instructions. If you take a reference to a, a la int *aptr = &a;, then the language specification says that a must have a location in memory (IIRC). This means that, per the specification, there will be a valid, int-sized slot in memory (on the stack, in any reasonable implementation) that will contain 12. In other languages there are obviously other specifications. Technically, in dynamic languages the compiler can perform similar optimizations. If you have a Python function: def do_nothing(): a = 12 You could imagine that the Python compiler, which turns the language text into bytecodes, might choose to omit the body of that function entirely (for pedants: except the implicit return None). Traditionally, Python implementations have no such optimizations because its language philosophy mandates debuggability, VM implementation simplicity, and programmer comprehension above optimizations. There are also some tricky constructs in dynamic languages that make inference more difficult. For example, Python allows a great deal of code object inspection that is expected to work across implementations. Acquiring/inspecting stack traces and the local arguments of activated frames requires at least slow-path fallback mechanisms, which increase optimization complexity significantly. We're ditching support for some of these kinds of language-level-runtime-stack-inspection things in JavaScript with ECMAScript revision 5. Supporting debuggers is hard, let's go optimizing! A: The value 12 is not statically bound to a. Rather, a is bound to a memory location, which is initialized to the value 12. If a were declared as const and nothing ever took the address of it, the compiler would not need to allocate storage and may use it as a compile-time constant, in which case the value 12 would be statically bound to a. A: It really depends on the context of the variables use and the compiler optimizations you have enabled. If the variable is never updated and used in a small enough scope, its likely to be compiled out in the final output, even in the lightest of optimizations. If compiler detects the variable is passed around or updated later (or potentially updated later) it may load the integer on to the stack. This is dependent on the architecture but if its only updated a short time later and then disposed, it may load it into a register if it can and work with it there. In CPython, it can do similar optimizations in some cases if it can scope the variable (unless its global, then it will be loaded in the heap). In regular Ruby, it may do something like this as well. In Jython and JRuby, they will definitely optimize the same way durning the JIT process. I'm not a complete expert, as I've only written very basic compilers that output to bytecode to be JITed later and that was years ago. A: I think a cannot be statically bound, because a is not a constant and that means there might be more than one value of a at the same time (e.g. declaring a in a recursive function). It is important that each value of a must have separated address in the memory, which implies that a cannot be statically bound to a specific single memory address.
Is this statically bound?
Say that I have a C program and it has this line: int a = 12; Is the value of 12 bound to 'a' during compile time? Or is the value placed into memory during run time when the scope of the program hits 'a'? What about programming languages like Python and Ruby? Are there languages/instances where a value is statically bound to a variable? I've been thinking about this for a while now and I honestly can't think of a logical reason for statically binding a value to a primitive type.
[ "Compilers and virtual machines effectively \"implement\" programming languages. They only have to do what is specified by the language semantics and observable for a given program in order to be correct.\nWhen you write the definition statement int a = 12; in a C program, you are informing the compiler that there ...
[ 10, 2, 1, 0 ]
[]
[]
[ "binding", "c", "compiler_construction", "python", "ruby" ]
stackoverflow_0003687600_binding_c_compiler_construction_python_ruby.txt
Q: Python: 'Nontype' object has no attribute keys def index_dir(self, base_path): num_files_indexed = 0 allfiles = os.listdir(base_path) #print allfiles num_files_indexed = len(allfiles) #print num_files_indexed docnumber = 0 self._inverted_index = {} #dictionary for file in allfiles: self.documents = [base_path+file] #list of all text files f = open(base_path+file, 'r') lines = f.read() # Tokenize the file into words tokens = self.tokenize(lines) docnumber = docnumber + 1 print 'docnumber', docnumber for term in tokens: # check if the key already exists in the dictionary, if yes, # just add a new value for the key #if self._inverted_index.has_key(term) if term in sorted(self._inverted_index.keys()): docnumlist = self._inverted_index.get(term) docnumlist = docnumlist.append(docnumber) else: # if the key doesn't exist in dictionary, add the key (term) # and associate the docnumber value with it. self._inverted_index = self._inverted_index.update({term: docnumber}) #self._inverted_index[term] = docnumber f.close() print 'dictionary', self._inverted_index print 'keys', self._inverted_index.keys() return num_files_indexed I'm working on an information retrieval project where we are supposed to crawl through multiple text file, tokenize the files and store the words in an inverted list (dictionary) data structure. ex: doc1.txt: "the dog ran" doc2.txt: "the cat slept" _inverted_index = { 'the': [0,1], 'dog': [0], 'ran': [0], 'cat': [1], 'slept': [1] } where 0,1 are docIDs I'm getting the following error: 'Nontype' object has no attribute keys. line#95 All help is highly appreciated. A: When self._inverted_index is a dictionary, self._inverted_index.update will update it in-place and return None (like most mutators do). So, the disastrous bug in your code is the line: self._inverted_index = self._inverted_index.update({term: docnumber}) which sets self._inverted_index to None. Just change it to self._inverted_index.update({term: docnumber}) simply accepting the in-place update (mutation) and without the erroneous assignment!
Python: 'Nontype' object has no attribute keys
def index_dir(self, base_path): num_files_indexed = 0 allfiles = os.listdir(base_path) #print allfiles num_files_indexed = len(allfiles) #print num_files_indexed docnumber = 0 self._inverted_index = {} #dictionary for file in allfiles: self.documents = [base_path+file] #list of all text files f = open(base_path+file, 'r') lines = f.read() # Tokenize the file into words tokens = self.tokenize(lines) docnumber = docnumber + 1 print 'docnumber', docnumber for term in tokens: # check if the key already exists in the dictionary, if yes, # just add a new value for the key #if self._inverted_index.has_key(term) if term in sorted(self._inverted_index.keys()): docnumlist = self._inverted_index.get(term) docnumlist = docnumlist.append(docnumber) else: # if the key doesn't exist in dictionary, add the key (term) # and associate the docnumber value with it. self._inverted_index = self._inverted_index.update({term: docnumber}) #self._inverted_index[term] = docnumber f.close() print 'dictionary', self._inverted_index print 'keys', self._inverted_index.keys() return num_files_indexed I'm working on an information retrieval project where we are supposed to crawl through multiple text file, tokenize the files and store the words in an inverted list (dictionary) data structure. ex: doc1.txt: "the dog ran" doc2.txt: "the cat slept" _inverted_index = { 'the': [0,1], 'dog': [0], 'ran': [0], 'cat': [1], 'slept': [1] } where 0,1 are docIDs I'm getting the following error: 'Nontype' object has no attribute keys. line#95 All help is highly appreciated.
[ "When self._inverted_index is a dictionary, self._inverted_index.update will update it in-place and return None (like most mutators do). So, the disastrous bug in your code is the line:\n self._inverted_index = self._inverted_index.update({term: docnumber})\n\nwhich sets self._inverted_index to None. Just change ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003693940_python.txt
Q: python auto restarting script I need script which starts itself at the end of process. I use this code but it wait for execfile. How to run it async? To do the effect of script restarting. import time print "start" time.sleep(5) print "go exec" execfile('res.py') print "stop exec" A: One of the many os.exec... functions (on Unix-y systems, including e.g. Linux and Mac, and also on Windows) may be what you want. You'll need to execute the sys.executable (that's the .exe -- or equivalent executable file on non-Windows OSs -- with the Python version currently in use) with (roughly) the same arguments as are listed in sys.argv (though there may be a bit more work if you also need to reproduce some Python command-line flags, such as e.g. -u for unbuffered std I/O). A: To execute a program asynchronously from Python, you can use the Popen function as shown here: import subprocess # ... pid = subprocess.Popen(["/usr/bin/python2.7", "res.py"]).pid That said, if you are invoking something over and over again, you probably want to use cron (all UNIX variants, including Linux and Mac OS X) or launchd (Mac OS X). You can create a cron job by invoking the command crontab -e and then adding a line such as the following (the asterisks below mean "each" and correspond to minutes, hours, days of the month, months, and days of the week): * * * * * /usr/bin/python2.7 script_to_execute.py >/dev/null 2>&1 The line above will run "script_to_execute.py" every minute. You can see some of the examples on the cron Wikipedia page for specifying different intervals at which a script should run.
python auto restarting script
I need script which starts itself at the end of process. I use this code but it wait for execfile. How to run it async? To do the effect of script restarting. import time print "start" time.sleep(5) print "go exec" execfile('res.py') print "stop exec"
[ "One of the many os.exec... functions (on Unix-y systems, including e.g. Linux and Mac, and also on Windows) may be what you want. You'll need to execute the sys.executable (that's the .exe -- or equivalent executable file on non-Windows OSs -- with the Python version currently in use) with (roughly) the same argu...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003693935_python.txt
Q: storing passwords in class variables in python I'm working on a python script that stores ssh passwords only during the current session. What I'm doing is declaring a class variable credentials = {}. When the script needs access to a specific server, it checks in credentials to see if credentials['server'] exists. If it does, it uses the password there, if it doesn't, it prompts the user. This is all working fine, but I'm just wondering if that's a bad way of implementing this? This isn't running anywhere critical that I need to be THAT concerned about security. I was just thinking it'd be nice if I could declare credentials as private. Is this a reasonable approach? Is there a more pythonic way to do this or one that's better suited for how python deals with class member access? A: A bit of a digression, but when I've built scripts do this in the past, the security minded recommended using an ssh-agent approach. The agent is a background processes, independent of the python but running under the same user, that will store the credentials. Then the script doesn't need to worry about prompting or handling passwords at all.
storing passwords in class variables in python
I'm working on a python script that stores ssh passwords only during the current session. What I'm doing is declaring a class variable credentials = {}. When the script needs access to a specific server, it checks in credentials to see if credentials['server'] exists. If it does, it uses the password there, if it doesn't, it prompts the user. This is all working fine, but I'm just wondering if that's a bad way of implementing this? This isn't running anywhere critical that I need to be THAT concerned about security. I was just thinking it'd be nice if I could declare credentials as private. Is this a reasonable approach? Is there a more pythonic way to do this or one that's better suited for how python deals with class member access?
[ "A bit of a digression, but when I've built scripts do this in the past, the security minded recommended using an ssh-agent approach. The agent is a background processes, independent of the python but running under the same user, that will store the credentials. Then the script doesn't need to worry about prompting...
[ 1 ]
[]
[]
[ "class_variables", "passwords", "python", "security" ]
stackoverflow_0003693965_class_variables_passwords_python_security.txt
Q: how to use python to read .cbr files? How can i use python to read .cbr/.cbt files? cbr/cbt files are a RAR archive format used for comic book files. A: .cbr is a RAR archive. .cbt is a TAR archive. You can use standard tarfile module for latter but you need to use rar/unrar for former. You can look for the code you need in comix (more precisely, archive.py).
how to use python to read .cbr files?
How can i use python to read .cbr/.cbt files? cbr/cbt files are a RAR archive format used for comic book files.
[ ".cbr is a RAR archive. .cbt is a TAR archive. You can use standard tarfile module for latter but you need to use rar/unrar for former. You can look for the code you need in comix (more precisely, archive.py).\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003694194_python.txt
Q: WTForms extension for Django templates not working I feel like I am missing something really obvious. I'm trying to use the WTForms template extensions with Django. I have a project on my development server which is working great (IE the extensions are working properly) but when I put it out on a test server, suddenly they are broken. Both servers have the same versions of Python, Django, WTForms installed. Settings.py is the same on both, including: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'wtforms.ext.django', ) Within the template, I am doing: {% load wtforms %} {% autoescape off %} <form id='returnform' action='{{form.action}}' method='POST' ENCTYPE="multipart/form-data"> And in the actual form, action is defined as: class UserForm(wtforms.Form): #Some fields and such here def action(self): return "/Admin/H/requests/" So, on the Dev server, my page loads with the proper 'action=url' like I expect. But on my test server, it returns a page that has 'action=<bound method UserForm.action of <pulseman.admin.forms.UserForm object at 0x9c8598c>>' Any thoughts on what I'm missing here? Thanks. A: I'm not sure what the cause of this is, but I can assure you it's not WTForms. We don't do anything funky with the classes, so if Django isn't invoking action properly, it's something in Django. Have you tried renaming the function, to see if it's a weird issue with the name "action"? Alternately, you could try turning action into a property using the @property decorator, or simply define the action as a string on the class. With that said, I would suggest not embedding URLs into the form on the python side. This is better solved by using URL reversing with the {% url %} templatetag.
WTForms extension for Django templates not working
I feel like I am missing something really obvious. I'm trying to use the WTForms template extensions with Django. I have a project on my development server which is working great (IE the extensions are working properly) but when I put it out on a test server, suddenly they are broken. Both servers have the same versions of Python, Django, WTForms installed. Settings.py is the same on both, including: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'wtforms.ext.django', ) Within the template, I am doing: {% load wtforms %} {% autoescape off %} <form id='returnform' action='{{form.action}}' method='POST' ENCTYPE="multipart/form-data"> And in the actual form, action is defined as: class UserForm(wtforms.Form): #Some fields and such here def action(self): return "/Admin/H/requests/" So, on the Dev server, my page loads with the proper 'action=url' like I expect. But on my test server, it returns a page that has 'action=<bound method UserForm.action of <pulseman.admin.forms.UserForm object at 0x9c8598c>>' Any thoughts on what I'm missing here? Thanks.
[ "I'm not sure what the cause of this is, but I can assure you it's not WTForms. We don't do anything funky with the classes, so if Django isn't invoking action properly, it's something in Django. Have you tried renaming the function, to see if it's a weird issue with the name \"action\"?\nAlternately, you could try...
[ 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003685313_django_django_templates_python.txt
Q: How to return an apache error page from a wsgi app? I have a simple working wsgi app. I can successfully return whatever HTTP status code, headers, and HTML I want. What I would like to do, is that when I'm returning a status code other than '200 OK', for WSGI to let apache fall back to its error handling and display whatever page apache is configured to display according to its 'ErrorDocument' setting. For example, this works fine when my WSGI app crashes unintentionally, then I see the default 'internal server error' page from apache. My question is, how can I do this in a controlled, deliberate manner? For example, I can then do my own authentication, and fallback to the default apache page I have set up. Any ideas? A: Presuming you actually mean with mod_wsgi under Apache, ensure you are using mod_wsgi daemon mode and set: WSGIErrorOverride On There is a brief mention of this in mod_wsgi version 3.0 release notes. http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300 If you are using Apache as proxy in front of distinct Python web server running WSGI application, then use Apache ProxyErrorOverride directive instead.
How to return an apache error page from a wsgi app?
I have a simple working wsgi app. I can successfully return whatever HTTP status code, headers, and HTML I want. What I would like to do, is that when I'm returning a status code other than '200 OK', for WSGI to let apache fall back to its error handling and display whatever page apache is configured to display according to its 'ErrorDocument' setting. For example, this works fine when my WSGI app crashes unintentionally, then I see the default 'internal server error' page from apache. My question is, how can I do this in a controlled, deliberate manner? For example, I can then do my own authentication, and fallback to the default apache page I have set up. Any ideas?
[ "Presuming you actually mean with mod_wsgi under Apache, ensure you are using mod_wsgi daemon mode and set:\nWSGIErrorOverride On\n\nThere is a brief mention of this in mod_wsgi version 3.0 release notes.\nhttp://code.google.com/p/modwsgi/wiki/ChangesInVersion0300\nIf you are using Apache as proxy in front of disti...
[ 5 ]
[]
[]
[ "apache", "python", "wsgi" ]
stackoverflow_0003691204_apache_python_wsgi.txt
Q: Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with the definition (photos = ...) makes the plus sign appear. However, in order to use a custom Field/Widget I need to figure this out. class GalleryForm(ModelForm): photos = ModelMultipleChoiceField(queryset=Photo.objects.all(), label="Photos") def __init__(self, *args, **kwargs): super(GalleryForm, self).__init__(*args, **kwargs) I've peeked at the Django source code and it seems like I have to wrap my widget in a RelatedFieldWidgetWrapper, but I haven't quite gotten my head around it. Any help is apprecietad! A: With the help from lazerscience and this post I ended up with the following. The ModelAdmin: class GalleryAdmin(admin.ModelAdmin): form = GalleryForm def __init__(self, model, admin_site): self.form.admin_site = admin_site super(GalleryAdmin, self).__init__(model, admin_site) And my form: from django.contrib.admin.widgets import RelatedFieldWidgetWrapper class GalleryForm(ModelForm): photos = ThumbnailChoiceField(queryset=Photo.objects.all(), label='Photos', widget=MyWidget(), required=False) def __init__(self, *args, **kwargs): super(GalleryForm, self).__init__(*args, **kwargs) rel = ManyToOneRel(self.instance.photos.model, 'id') self.fields['photos'].widget = RelatedFieldWidgetWrapper(self.fields['photos'].widget, rel, self.admin_site) A: Yes you are right, you have to wrap your widget with django.contrib.admin.widgets.RelatedFieldWidgetWrapper, which turns out to be a bit complicated since it expects the current admin site as a parameter for initialization! Maybe you will find this post helpful!
Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form
The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with the definition (photos = ...) makes the plus sign appear. However, in order to use a custom Field/Widget I need to figure this out. class GalleryForm(ModelForm): photos = ModelMultipleChoiceField(queryset=Photo.objects.all(), label="Photos") def __init__(self, *args, **kwargs): super(GalleryForm, self).__init__(*args, **kwargs) I've peeked at the Django source code and it seems like I have to wrap my widget in a RelatedFieldWidgetWrapper, but I haven't quite gotten my head around it. Any help is apprecietad!
[ "With the help from lazerscience and this post I ended up with the following.\nThe ModelAdmin:\nclass GalleryAdmin(admin.ModelAdmin):\n\n form = GalleryForm\n \n def __init__(self, model, admin_site):\n self.form.admin_site = admin_site \n super(GalleryAdmin, self).__init__(model, admin_site)...
[ 12, 8 ]
[]
[]
[ "django", "django_admin", "many_to_many", "python" ]
stackoverflow_0003692822_django_django_admin_many_to_many_python.txt
Q: Global static variables in Python def Input(): c = raw_input ('Enter data1,data2: ') data = c.split(',') return data I need to use list data in other functions, but I don't want to enter raw_input everytime. How I can make data like a global static in c++ and put it everywhere where it needed? A: Add the global keyword to your function: def Input(): global data c = raw_input ('Enter data1,data2: ') data = c.split(',') return data The global data statement is a declaration that makes data a global variable. After calling Input() you will be able to refer to data in other functions. A: using global variables is usually considered bad practice. It's better to use proper object orientation and wrap 'data' in a proper class / object, e.g. class Questionaire(object): def __init__(self): self.data = '' def input(self): c = raw_input('Enter data1, data2:') self.data = c.split(',') def results(self): print "You entered", self.data q = Questionaire() q.input() q.results()
Global static variables in Python
def Input(): c = raw_input ('Enter data1,data2: ') data = c.split(',') return data I need to use list data in other functions, but I don't want to enter raw_input everytime. How I can make data like a global static in c++ and put it everywhere where it needed?
[ "Add the global keyword to your function:\ndef Input():\n global data\n c = raw_input ('Enter data1,data2: ')\n data = c.split(',')\n return data\n\nThe global data statement is a declaration that makes data a global variable. After calling Input() you will be able to refer to data in other functions.\n...
[ 18, 4 ]
[]
[]
[ "global", "python", "static", "variables" ]
stackoverflow_0003694580_global_python_static_variables.txt
Q: Python 2.6.5: Divide timedelta with timedelta I'm trying to divide one timedelta object with another to calculate a server uptime: >>> import datetime >>> installation_date=datetime.datetime(2010,8,01) >>> down_time=datetime.timedelta(seconds=1400) >>> server_life_period=datetime.datetime.now()-installation_date >>> down_time_percentage=down_time/server_life_period Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'datetime.timedelta' I know this has been solved in Python 3.2, but is there a convenient way to handle it in prior versions of Python, apart from calculating the number of microseconds, seconds and days and dividing? Thanks, Adam A: In Python ≥2.7, there is a .total_seconds() method to compute the total seconds contained in the timedelta: >>> down_time.total_seconds() / server_life_period.total_seconds() 0.0003779903727652387 Otherwise, there is no way but to compute the total microseconds (for versions < 2.7) >>> def get_total_seconds(td): return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6 ... >>> get_total_seconds(down_time) / get_total_seconds(server_life_period) 0.0003779903727652387
Python 2.6.5: Divide timedelta with timedelta
I'm trying to divide one timedelta object with another to calculate a server uptime: >>> import datetime >>> installation_date=datetime.datetime(2010,8,01) >>> down_time=datetime.timedelta(seconds=1400) >>> server_life_period=datetime.datetime.now()-installation_date >>> down_time_percentage=down_time/server_life_period Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'datetime.timedelta' I know this has been solved in Python 3.2, but is there a convenient way to handle it in prior versions of Python, apart from calculating the number of microseconds, seconds and days and dividing? Thanks, Adam
[ "In Python ≥2.7, there is a .total_seconds() method to compute the total seconds contained in the timedelta:\n>>> down_time.total_seconds() / server_life_period.total_seconds()\n0.0003779903727652387\n\nOtherwise, there is no way but to compute the total microseconds (for versions < 2.7)\n>>> def get_total_seconds(...
[ 33 ]
[]
[]
[ "division", "python", "timedelta" ]
stackoverflow_0003694835_division_python_timedelta.txt
Q: Python: Should I put my data in lists or object attributes? I am looking for an appropriate data structure in Python for processing variably structured forms. By variably structured forms I mean that the number of form fields and the types of the form's contents are not known in advance. They are defined by the user who populates the forms with his input. What are the pros and cons of putting data in A) object attributes (e.g. of an otherwise empty "form"-class) or B) simply lists/dicts? Consider that I have to preserve the sequence of form fields, the form field names and the types. (Strangely, it has been difficult to find conclusive information on this topic. As I am still new to Python, it's possible that I have searched for the wrong terms. If my question is not clear enough, please ask in the comments and I will try to clarify.) A: In Python, as in all object-oriented languages, the purpose of classes is to associate data and closely-related methods that act on that data. If there's no real encapsulation going on (i.e. the methods help define the ways you can interact with the data), the best choice is a conglomeration of builtin types like lists and dictionaries as you mention and perhaps some utility functions that act on those sorts of data structures. A: Python classes are literally just two dicts (one for functions, one for data), a name and the rules how Python looks for keys. When you access existing keys, there is absolutely no difference to a dict (unless you overwrote the access rules of cause). That means that there is no drawback (besides more code) to using classes at all and you should never be afraid to write a class. In your particular case I think you should go with classes, for one simple reason: You might want to extend them later. Maybe you want to add constraints on the name (length, allowed letters, uniqueness, ...) or the value (not empty, length, type, ...) of a field one day. Maybe you want to validate all fields in a form. If you use a class you can do this without changing any code outside the class! And as I said before, even if you don't, there are no drawbacks! I guess my rule of thumb for classes is: Don't use a class if you're absolutely sure that there is nothing to add to it. If not just write those few extra lines. A: It's not very Pythonic to randomly add members to an object. It would be more Pythonic if you used member methods to do it, but still not the way things are usually done. Every library I've seen for this kind of thing uses dictionaries or lists. So that is the idiomatically Python way to handle the problem. Sometimes they use an object that overrides __getitem__ so it can behave like a dictionary or list, but it's still dictionary syntax that's used to access the fields. I think all the pros and cons have to do with people understanding your code, and since I've never seen code that handles this by having an object with members that can appear I don't think many people will find code that does do that to be very understandable. A: A list of dictionaries (e.g. [{"type": "text", "name": "field_name", "value": "test value"}, ...]) would be a usable structure, if I understand your requirement correctly. Whether object are better in this case depends on what you're doing later. If you use the objects just as data storage, you don't gain anything. Maybe a list of field objects, which implement some appropriate methods to deal with your data, would also be a good choice. A: maybe if you set up an object to use for each field and store those in a list, but that is practically ending up like a glorified dictionary then you could access it like fields[2].name fields[2].value ect
Python: Should I put my data in lists or object attributes?
I am looking for an appropriate data structure in Python for processing variably structured forms. By variably structured forms I mean that the number of form fields and the types of the form's contents are not known in advance. They are defined by the user who populates the forms with his input. What are the pros and cons of putting data in A) object attributes (e.g. of an otherwise empty "form"-class) or B) simply lists/dicts? Consider that I have to preserve the sequence of form fields, the form field names and the types. (Strangely, it has been difficult to find conclusive information on this topic. As I am still new to Python, it's possible that I have searched for the wrong terms. If my question is not clear enough, please ask in the comments and I will try to clarify.)
[ "In Python, as in all object-oriented languages, the purpose of classes is to associate data and closely-related methods that act on that data. If there's no real encapsulation going on (i.e. the methods help define the ways you can interact with the data), the best choice is a conglomeration of builtin types like ...
[ 5, 4, 0, 0, 0 ]
[]
[]
[ "attributes", "data_structures", "list", "object", "python" ]
stackoverflow_0003694284_attributes_data_structures_list_object_python.txt
Q: Fetch a random entity from the datastore Pretty simple, in my AppEngine application, I have over 1 million entities of one kind, what is the best way to pick one at random? A: Maybe one solution but i don't know if it's the best :) import random from google.appengine.ext import db from google.appengine.api import memcache DATA_KEY = "models/keys/random" def get_data(): data = memcache.get (DATA_KEY) if data is None: offset = random.randint (1, 1000000) data = self.MyModel.all (keys_only=True).fetch (100, offset) memcache.add (DATA_KEY, data, 60) entity_key = random.choice (data) return db.get (entity_key) A: See this question: Fetching a random record from the Google App Engine Datastore?
Fetch a random entity from the datastore
Pretty simple, in my AppEngine application, I have over 1 million entities of one kind, what is the best way to pick one at random?
[ "Maybe one solution but i don't know if it's the best :)\nimport random\nfrom google.appengine.ext import db\nfrom google.appengine.api import memcache\n\nDATA_KEY = \"models/keys/random\"\n\ndef get_data():\n data = memcache.get (DATA_KEY)\n if data is None:\n offset = random.randint (1, 1000000)\n ...
[ 0, -1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "random" ]
stackoverflow_0003694177_google_app_engine_google_cloud_datastore_python_random.txt
Q: python check url type I wrote a crawler in python, fetched urls has different types: it can be url with html and url with image or big archives or other files. So i need fast determine this case to prevent of reading of big files such as big archives and continue crawling. How is the best way to determine url type at start of page loading? i understand what i can do it by url name (end's with .rar .jpg etc) but i think it's not full solution. I need check header or something like that for this? also i need some page size predicition to prevent of large downloads. In other words set limit of downloaded page size, to prevent fast memory eating. A: If you use a HTTP HEAD request on the resource, you will get relevant metadata on the resource without the resource data itself. Specifically, the content-length and content-type headers will be of interest. E.g. HEAD /stackoverflow/img/favicon.ico HTTP/1.1 host: sstatic.net HTTP/1.1 200 OK Cache-Control: max-age=604800 Content-Length: 1150 Content-Type: image/x-icon Last-Modified: Mon, 02 Aug 2010 06:04:04 GMT Accept-Ranges: bytes ETag: "2187d82832cb1:0" X-Powered-By: ASP.NET Date: Sun, 12 Sep 2010 13:38:36 GMT You can do this in python using httplib: >>> import httplib >>> conn = httplib.HTTPConnection("sstatic.net") >>> conn.request("HEAD", "/stackoverflow/img/favicon.ico") >>> res = conn.getresponse() >>> print res.getheaders() [('content-length', '1150'), ('x-powered-by', 'ASP.NET'), ('accept-ranges', 'bytes'), ('last-modified', 'Mon, 02 Aug 2010 06:04:04 GMT'), ('etag', '"2187d82832cb1:0"'), ('cache-control', 'max-age=604800'), ('date', 'Sun, 12 Sep 2010 13:39:26 GMT'), ('content-type', 'image/x-icon')] This tells you it's an image (image/* mime-type) of 1150 bytes. Enough information for you to decide if you want to fetch the full resource. Additionally, this header tells you the server accepts HTTP partial content request (accept-ranges header) which allows you to retrieve data in batches. You will get the same header information if you do a GET directly, but this will also start sending the resource data in the body of the response, something you want to avoid. If you want to learn more about HTTP headers and their meaning, you can use an online tool such as 'Fetch'
python check url type
I wrote a crawler in python, fetched urls has different types: it can be url with html and url with image or big archives or other files. So i need fast determine this case to prevent of reading of big files such as big archives and continue crawling. How is the best way to determine url type at start of page loading? i understand what i can do it by url name (end's with .rar .jpg etc) but i think it's not full solution. I need check header or something like that for this? also i need some page size predicition to prevent of large downloads. In other words set limit of downloaded page size, to prevent fast memory eating.
[ "If you use a HTTP HEAD request on the resource, you will get relevant metadata on the resource without the resource data itself. Specifically, the content-length and content-type headers will be of interest.\nE.g.\nHEAD /stackoverflow/img/favicon.ico HTTP/1.1\nhost: sstatic.net\n\nHTTP/1.1 200 OK\nCache-Control: m...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0003695018_python.txt
Q: help me use proxy with twill I read help here http://twill.idyll.org/browsing.html, then i open python and write export http_proxy="http://www.someproxy.com:3128" but i just receive an error. How can i use proxy with twill to browser web ? A: the export command is something you need to type on your shell (assuming unix/linux). It's not a python statement!
help me use proxy with twill
I read help here http://twill.idyll.org/browsing.html, then i open python and write export http_proxy="http://www.someproxy.com:3128" but i just receive an error. How can i use proxy with twill to browser web ?
[ "the export command is something you need to type on your shell (assuming unix/linux). It's not a python statement!\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003695055_python.txt
Q: Confused about behaviour of base class This follows a question I asked a few hours ago. I have this code: class A(object): def __init__(self, a): print 'A called.' self.a = a class B(A): def __init__(self, b, a): print 'B called.' x = B(1, 2) print x.a This gives the error: AttributeError: 'B' object has no attribute 'a', as expected. I can fix this by calling super(B, self).__init__(a). However, I have this code: class A(object): def __init__(self, a): print 'A called.' self.a = a class B(A): def __init__(self, b, a): print 'B called.' print a x = B(1, 2) Whose output is: B called. 2 Why does this work? And more importantly, how does it work when I have not initialized the base class? Also, notice that it does not call the initializer of A. Is it because when I do a: def __init__(self, b, a) I am declaring b to be an attribute of B? If yes, how can I check b is an attribute of which class - the subclass or the superclass? A: The way you defined it B does not have any attributes. When you do print a the a refers to the local variable a in the __init__ method, not to any attribute. If you replace print a with print self.a you will get the same error message as before. A: In your second code, calling print a works because you are printing the variable passed as a parameter to B's __init__ function, not the self.a variable (which is not initialized because A.__init__ was not called). Once you leave the scope of the __init__ function you will loose access to the a. A: The short answer is that __init__ isn't a constructor in the sense of other languages, like C++. It's really just a function that runs on an object after the "bare" object is created. B's __init__ function is conventionally responsible for calling A's __init__, but it doesn't have to - if A.__init__ never gets called, then then A's attribute a doesn't get added to the object, and so you get an error when you try to access it. A: To fix this problem, you'll need to use class B(A): def __init__(self, b, a): super(A, self).__init__(a) Make sure you declare the classes as new style objects, something you're already doing [edit: clarification]
Confused about behaviour of base class
This follows a question I asked a few hours ago. I have this code: class A(object): def __init__(self, a): print 'A called.' self.a = a class B(A): def __init__(self, b, a): print 'B called.' x = B(1, 2) print x.a This gives the error: AttributeError: 'B' object has no attribute 'a', as expected. I can fix this by calling super(B, self).__init__(a). However, I have this code: class A(object): def __init__(self, a): print 'A called.' self.a = a class B(A): def __init__(self, b, a): print 'B called.' print a x = B(1, 2) Whose output is: B called. 2 Why does this work? And more importantly, how does it work when I have not initialized the base class? Also, notice that it does not call the initializer of A. Is it because when I do a: def __init__(self, b, a) I am declaring b to be an attribute of B? If yes, how can I check b is an attribute of which class - the subclass or the superclass?
[ "The way you defined it B does not have any attributes. When you do print a the a refers to the local variable a in the __init__ method, not to any attribute.\nIf you replace print a with print self.a you will get the same error message as before.\n", "In your second code, calling print a works because you are pr...
[ 4, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003695218_python.txt
Q: Pylons - How to get the current controller and action (current route)? I'm in a Mako template, and I want to know what the current controller and action is (of the current page). How can I do this? I tried c.controller and c.action, but it didn't work. I also listed the keys of the context object but didn't find it. As a workaround, I've been setting c.controller and c.action from within each controller method, but I know there must be a better way. class MainController(BaseController): def index(self): c.controller, c.action = 'main', 'index' return render("/main.html") A: In a template: Current url: ${url.current()} Controller and action: ${url.environ['pylons.routes_dict']['controller']} ${url.environ['pylons.routes_dict']['action']}
Pylons - How to get the current controller and action (current route)?
I'm in a Mako template, and I want to know what the current controller and action is (of the current page). How can I do this? I tried c.controller and c.action, but it didn't work. I also listed the keys of the context object but didn't find it. As a workaround, I've been setting c.controller and c.action from within each controller method, but I know there must be a better way. class MainController(BaseController): def index(self): c.controller, c.action = 'main', 'index' return render("/main.html")
[ "In a template:\nCurrent url: \n${url.current()}\n\nController and action: \n${url.environ['pylons.routes_dict']['controller']}\n${url.environ['pylons.routes_dict']['action']}\n\n" ]
[ 6 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003695107_pylons_python.txt
Q: Python (or maybe JavaScript / Ruby): open source projects that will give me a (bit) of hand-holding Ive been roaming around the interwebs looking for my first open-source project to contribute to - and most cool ones seem to be one-man bands on github, which I could fork - but wouldnt quite provide the code review etc. i think i want, so i can improve my python abilities. Web.py, flask, celery, twisted etc look interesting - so far only the latter seems like a candidate for something I could properly contribute to, but even though im a decent(ish) python programmer, I think the whole event driven thing is probably too steep a learning curve for me to be able to contribute meaningfully for a while... so i'd probably like to start elsewhere. Any suggestions? btw. yes, there is a duplicate question here: https://stackoverflow.com/questions/117561/what-are-good-open-source-projects-in-python-for-which-i-can-be-a-contributor - but it is two years old, I think it is fair to assume new stuff / projects will have emerged in the interim. Thanks! A: You could have a look and see if you find RCTK interesting to contribute to. I'm trying to be as pythonic as possible, it actually supports python 3 if you find that interesting, and even writing demo applications is considered very useful. I (the head developer) currently already have two contributes whose code I review. This seems to work well. A: Looking through the google summer of code proposals is a possibility -- not all the projects have been picked by students, and the organizations probably still would welcome anyone willing to work on them. Participating in gsoc is another option, of course!
Python (or maybe JavaScript / Ruby): open source projects that will give me a (bit) of hand-holding
Ive been roaming around the interwebs looking for my first open-source project to contribute to - and most cool ones seem to be one-man bands on github, which I could fork - but wouldnt quite provide the code review etc. i think i want, so i can improve my python abilities. Web.py, flask, celery, twisted etc look interesting - so far only the latter seems like a candidate for something I could properly contribute to, but even though im a decent(ish) python programmer, I think the whole event driven thing is probably too steep a learning curve for me to be able to contribute meaningfully for a while... so i'd probably like to start elsewhere. Any suggestions? btw. yes, there is a duplicate question here: https://stackoverflow.com/questions/117561/what-are-good-open-source-projects-in-python-for-which-i-can-be-a-contributor - but it is two years old, I think it is fair to assume new stuff / projects will have emerged in the interim. Thanks!
[ "You could have a look and see if you find RCTK interesting to contribute to. I'm trying to be as pythonic as possible, it actually supports python 3 if you find that interesting, and even writing demo applications is considered very useful.\nI (the head developer) currently already have two contributes whose code ...
[ 2, 1 ]
[]
[]
[ "javascript", "open_source", "python", "ruby" ]
stackoverflow_0003694265_javascript_open_source_python_ruby.txt
Q: Boost.Python function pointers as class constructor argument I have a C++ class that requires a function pointer in it's constructor (float(*myfunction)(vector<float>*)) I've already exposed some function pointers to Python. The ideal way to use this class is something like this: import mymodule mymodule.some_class(mymodule.some_function) So I tell Boost about this class like so: class_<SomeClass>("some_class", init<float(*)(vector<float>*)>); But I get: error: no matching function for call to 'register_shared_ptr1(Sample (*)(std::vector<double, std::allocator<double> >*))' when I try to compile it. So, does anyone have any ideas on how I can fix the error without losing the flexibility gained from function pointers (ie no falling back to strings that indicate which function to call)? Also, the main point of writing this code in C++ is for speed. So it would be nice if I was still able to keep that benefit (the function pointer gets assigned to a member variable during initialization and will get called over a million times later on). A: OK, so this is a fairly difficult question to answer in general. The root cause of your problem is that there really is no python type which is exactly equivalent to a C function pointer. Python functions are sort-of close, but their interface doesn't match for a few reasons. Firstly, I want to mention the technique for wrapping a constructor from here: http://wiki.python.org/moin/boost.python/HowTo#namedconstructors.2BAC8factories.28asPythoninitializers.29. This lets you write an __init__ function for your object that doesn't directly correspond to an actual C++ constructor. Note also, that you might have to specify boost::python::no_init in the boost::python::class_ construction, and then def a real __init__ function later, if your object isn't default-constructible. Back to the question: Is there only a small set of functions that you'll usually want to pass in? In that case, you could just declare a special enum (or specialized class), make an overload of your constructor that accepts the enum, and use that to look up the real function pointer. You can't directly call the functions yourself from python using this approach, but it's not that bad, and the performance will be the same as using real function pointers. If you want to provide a general approach that will work for any python callable, things get more complex. You'll have to add a constructor to your C++ object that accepts a general functor, e.g. using boost::function or std::tr1::function. You could replace the existing constructor if you wanted, because function pointers will convert to this type correctly. So, assuming you've added a boost::function constructor to SomeClass, you should add these functions to your python wrapping code: struct WrapPythonCallable { typedef float * result_type; explicit WrapPythonCallable(const boost::python::object & wrapped) : wrapped_(wrapped) { } float * operator()(vector<float>* arg) const { //Do whatever you need to do to convert into a //boost::python::object here boost::python::object arg_as_python_object = /* ... */; //Call out to python with the object - note that wrapped_ //is callable using an operator() overload, and returns //a boost::python::object. //Also, the call can throw boost::python::error_already_set - //you might want to handle that here. boost::python::object result_object = wrapped_(arg_as_python_object); //Do whatever you need to do to extract a float * from result_object, //maybe using boost::python::extract float * result = /* ... */; return result; } boost::python::object wrapped_; }; //This function is the "constructor wrapper" that you'll add to SomeClass. //Change the return type to match the holder type for SomeClass, like if it's //held using a shared_ptr. std::auto_ptr<SomeClass> CreateSomeClassFromPython( const boost::python::object & callable) { return std::auto_ptr<SomeClass>( new SomeClass(WrapPythonCallable(callable))); } //Later, when telling Boost.Python about SomeClass: class_<SomeClass>("some_class", no_init) .def("__init__", make_constructor(&CreateSomeClassFromPython)); I've left out details on how to convert pointers to and from python - that's obviously something that you'll have to work out, because there are object lifetime issues there. If you need to call the function pointers that you'll pass in to this function from Python, then you'll need to def these functions using Boost.Python at some point. This second approach will work fine with these def'd functions, but calling them will be slow, because objects will be unnecessarily converted to and from Python every time they're called. To fix this, you can modify CreateSomeClassFromPython to recognize known or common function objects, and replace them with their real function pointers. You can compare python objects' identity in C++ using object1.ptr() == object2.ptr(), equivalent to id(object1) == id(object2) in python. Finally, you can of course combine the general approach with the enum approach. Be aware when doing this, that boost::python's overloading rules are different from C++'s, and this can bite you when dealing with functions like CreateSomeClassFromPython. Boost.Python tests functions in the order that they are def'd to see if the runtime arguments can be converted to the C++ argument types. So, CreateSomeClassFromPython will prevent single-argument constructors def'd later than it from being used, because its argument matches any python object. Be sure to put it after other single-argument __init__ functions. If you find yourself doing this sort of thing a lot, then you might want to look at the general boost::function wrapping technique (mentioned on the same page with the named constructor technique): http://wiki.python.org/moin/boost.python/HowTo?action=AttachFile&do=view&target=py_boost_function.hpp.
Boost.Python function pointers as class constructor argument
I have a C++ class that requires a function pointer in it's constructor (float(*myfunction)(vector<float>*)) I've already exposed some function pointers to Python. The ideal way to use this class is something like this: import mymodule mymodule.some_class(mymodule.some_function) So I tell Boost about this class like so: class_<SomeClass>("some_class", init<float(*)(vector<float>*)>); But I get: error: no matching function for call to 'register_shared_ptr1(Sample (*)(std::vector<double, std::allocator<double> >*))' when I try to compile it. So, does anyone have any ideas on how I can fix the error without losing the flexibility gained from function pointers (ie no falling back to strings that indicate which function to call)? Also, the main point of writing this code in C++ is for speed. So it would be nice if I was still able to keep that benefit (the function pointer gets assigned to a member variable during initialization and will get called over a million times later on).
[ "OK, so this is a fairly difficult question to answer in general. The root cause of your problem is that there really is no python type which is exactly equivalent to a C function pointer. Python functions are sort-of close, but their interface doesn't match for a few reasons.\nFirstly, I want to mention the techni...
[ 2 ]
[]
[]
[ "boost_python", "compiler_errors", "function_pointers", "performance", "python" ]
stackoverflow_0003641334_boost_python_compiler_errors_function_pointers_performance_python.txt
Q: How do I include an image in a window with pygtk? I'm trying to make a program in python which creates a fullscreen window and includes an image, but I don't really know how to do that. I've tried to read documentations on pygtk and I've searched in both goodle and stackoverflow, without any success. Here's my current code. def __init__(self): pixbuf = gtk.gdk.pixbuf_new_from_file("test.png") image = gtk.Image() self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.fullscreen() self.window.show() image.set_from_pixbuf(pixbuf) image.show() Question: how do I include an image in a window? A: Please provide a little more context (e.g. class definition, imports). Do not forget to add the image object to your window (before showing image and window): self.window.add(image) The tutorial example adds the image to a button, but you can try adding it directly to the main window: # an image widget to contain the pixmap image = gtk.Image() image.set_from_pixmap(pixmap, mask) image.show() # a button to contain the image widget button = gtk.Button() button.add(image) window.add(button) button.show() button.connect("clicked", self.button_clicked)
How do I include an image in a window with pygtk?
I'm trying to make a program in python which creates a fullscreen window and includes an image, but I don't really know how to do that. I've tried to read documentations on pygtk and I've searched in both goodle and stackoverflow, without any success. Here's my current code. def __init__(self): pixbuf = gtk.gdk.pixbuf_new_from_file("test.png") image = gtk.Image() self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.fullscreen() self.window.show() image.set_from_pixbuf(pixbuf) image.show() Question: how do I include an image in a window?
[ "Please provide a little more context (e.g. class definition, imports).\nDo not forget to add the image object to your window (before showing image and window):\nself.window.add(image)\n\nThe tutorial example adds the image to a button, but you can try adding it directly to the main window:\n# an image widget to co...
[ 4 ]
[]
[]
[ "gtk", "image", "pygtk", "python" ]
stackoverflow_0003695371_gtk_image_pygtk_python.txt
Q: how could we obtain magnitude of frequency from a set of complex numbers obtained after performing FFT in python? i don't know what to do after obtaining a set of complex numbers from FFT on a wav file.How could i obtain the corresponding frequencies.This is output i got after performing FFT which is shown below [ 12535945.00000000 +0.j -30797.74496367 +6531.22295858j -26330.14948055-11865.08322966j ..., 34265.08792783+31937.15794965j -26330.14948055+11865.08322966j -30797.74496367 -6531.22295858j] A: Actually the abs(x) operation only converts a real/imaginary pair from your result list into a magnitude. Do that unless you want to keep the imaginary portion for future use. So after conversion, each number in the result list represents a magnitude of signal at a certain frequency in your frequency spectrum. So frequency is represented by list index. When you plot the data on an XY graph, what you see is the magnitude of frequencies that your source signal contains. Don't forget that only your first half of data is valid. The other half is usually a mirror image of the first half due to aliasing. For example say you run a 1024 point FFT on a wav file that contains data sampled at 10Khz. The FFT will take that 10Khz spectrum and divide that into 1024 'bins'. Then the FFT will decide how much each chunk of spectrum is present in the source wav file. Your output should be those bins. Generally when I do a frequency analysis, the actual numbers I get back aren't what's important. Its the magnitudes relative to surrounding bins that I'm interested in. For a little more detail, we're relying on the principle of superposition which states that any time-varying signal containing many frequencies can be split up into many signals containing one component frequency each and vice versa. So the FFT output reflects this property. Each value of your output list represents a magnitude for a signal at a single frequency (usually called a 'bin') that is present in your source signal. Combine all those signals together and you should get your source signal back. Oh and in case you didn't know, only the first half of your result list is valid due to Nyquist's Rule (or law, not sure) which says that all sampling systems can only reproduce frequencies in a signal that is at most half the sampling frequency. So if you sample a signal at 10Khz, you can only reproduce frequencies up to 5Khz from the data taken during your sampling. The same principle is the reason why only the first half of your FFT data is valid. The second half is an alias of the first half. Sorry for the long-winded explanation, your question doesn't indicate what experience you have so I thought an explanation of the general gist of an FFT is needed. A: As @KennyTM already explained on the duplicate question: The frequency is determined by the index of the array. Each element corresponds to a frequency. To determine the frequency of that each element represents, you need to know the sampling frequency of your data and the length of the array. Basically, it would be something like: sampling_freq = 1000.0 # in Hz freq = np.linspace(0, (1.0 / sampling_freq / 2.0), (x.size / 2) + 1) For one half of the fft array (which is symmetric about the center). My memory is rusty, though, so this may be a bit off... Either way, numpy has a helper function to do it for you: numpy.fft.fftfreq A: If I'm not mistaken, the frequency can be obtained by calculating the magnitude of the complex number. So a simple abs(x) on each of those complex numbers should return the frequency.
how could we obtain magnitude of frequency from a set of complex numbers obtained after performing FFT in python?
i don't know what to do after obtaining a set of complex numbers from FFT on a wav file.How could i obtain the corresponding frequencies.This is output i got after performing FFT which is shown below [ 12535945.00000000 +0.j -30797.74496367 +6531.22295858j -26330.14948055-11865.08322966j ..., 34265.08792783+31937.15794965j -26330.14948055+11865.08322966j -30797.74496367 -6531.22295858j]
[ "Actually the abs(x) operation only converts a real/imaginary pair from your result list into a magnitude. Do that unless you want to keep the imaginary portion for future use. So after conversion, each number in the result list represents a magnitude of signal at a certain frequency in your frequency spectrum. ...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003695202_python.txt
Q: I can't upload a file with CGIHTTPServer I'm using the CGIHTTPServer to implement a simple cgi server. I'm trying to upload a file by a form with the post method and the multipart/form-data enctype but I have problems when I recover the value of the fields in the cgi script. When the script catch the form fields, the value of the file is a MiniFieldStorage with two fields only (key and file name), and I can't recover the content of the file. As the API doc shows, this content is in value field of a StorageField but in the MiniFieldStorage this field isn't exits. ¿How can I recover a StorageField with the content of the file instead a MiniStorageField? ¿There are other method to upload a file using CGIHTTPServer? Thanks a lot A: Please provide some code example. Guessing from the text, you should look into the cgi module. Follow the examples, specially the cgi.test() function. cgi — Common Gateway Interface support Support module for Common Gateway Interface (CGI) scripts. This module defines a number of utilities for use by CGI scripts written in Python. Quoting the FieldStorage description (using the cgi module): To get at submitted form data, it’s best to use the FieldStorage class. The other classes defined in this module are provided mostly for backward compatibility. Instantiate it exactly once, without arguments. This reads the form contents from standard input or the environment (depending on the value of various environment variables set according to the CGI standard). Since it may consume standard input, it should be instantiated only once.
I can't upload a file with CGIHTTPServer
I'm using the CGIHTTPServer to implement a simple cgi server. I'm trying to upload a file by a form with the post method and the multipart/form-data enctype but I have problems when I recover the value of the fields in the cgi script. When the script catch the form fields, the value of the file is a MiniFieldStorage with two fields only (key and file name), and I can't recover the content of the file. As the API doc shows, this content is in value field of a StorageField but in the MiniFieldStorage this field isn't exits. ¿How can I recover a StorageField with the content of the file instead a MiniStorageField? ¿There are other method to upload a file using CGIHTTPServer? Thanks a lot
[ "Please provide some code example.\nGuessing from the text, you should look into the cgi module.\nFollow the examples, specially the cgi.test() function.\n\ncgi — Common Gateway Interface support\nSupport module for Common Gateway Interface (CGI) scripts.\nThis module defines a number of utilities for use by CGI sc...
[ 1 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0003695441_cgi_python.txt
Q: UnicodeEncodeError when fetching URLs I am using urlfetch to fetch a URL. When I try to send it to html2text function (strips off all HTML tags), I get the following message: UnicodeEncodeError: 'charmap' codec can't encode characters in position ... character maps to <undefined> I've been trying to process encode('UTF-8','ignore') on the string but I keep getting this error. Any ideas? Thanks, Joel Some Code: result = urlfetch.fetch(url="http://www.google.com") html2text(result.content.encode('utf-8', 'ignore')) And the error message: File "C:\Python26\lib\encodings\cp1252.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position 159-165: character maps to <undefined> A: You need to decode the data you fetched first! With which codec? Depends on the website you fetch. When you have unicode and try to encode it with some_unicode.encode('utf-8', 'ignore') i can't image how it could throw an error. Ok what you need to do: result = fetch('http://google.com') content_type = result.headers['Content-Type'] # figure out what you just fetched ctype, charset = content_type.split(';') encoding = charset[len(' charset='):] # get the encoding print encoding # ie ISO-8859-1 utext = result.content.decode(encoding) # now you have unicode text = utext.encode('utf8', 'ignore') # encode to uft8 This is not really robust but it should show you the way.
UnicodeEncodeError when fetching URLs
I am using urlfetch to fetch a URL. When I try to send it to html2text function (strips off all HTML tags), I get the following message: UnicodeEncodeError: 'charmap' codec can't encode characters in position ... character maps to <undefined> I've been trying to process encode('UTF-8','ignore') on the string but I keep getting this error. Any ideas? Thanks, Joel Some Code: result = urlfetch.fetch(url="http://www.google.com") html2text(result.content.encode('utf-8', 'ignore')) And the error message: File "C:\Python26\lib\encodings\cp1252.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position 159-165: character maps to <undefined>
[ "You need to decode the data you fetched first! With which codec? Depends on the website you fetch.\nWhen you have unicode and try to encode it with some_unicode.encode('utf-8', 'ignore') i can't image how it could throw an error.\nOk what you need to do:\nresult = fetch('http://google.com') \ncontent_type = result...
[ 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003695567_google_app_engine_python.txt
Q: Simplest way to implement user login / authentication in Python I'm developing a fairly simple Python web app and I want to allow users to log in. I know the solution will probably involve installing some sort of framework rather than doing it in straight Python and I'm OK with that, I'm just wondering, what would be the easiest, most hassle-free way to add authentication? The app is already written in straight Python so any extra code I use will only be used to for this purpose. A: Store the user's login, the salted hash of their password, and the salt in a database. (If you're going for cryptographic overkill, you can use a very expensive-to-compute hashing algorithm like bcrypt.) You can use SQLite as that's bundled with Python, but it would probably make more sense to install a database separately and use that.
Simplest way to implement user login / authentication in Python
I'm developing a fairly simple Python web app and I want to allow users to log in. I know the solution will probably involve installing some sort of framework rather than doing it in straight Python and I'm OK with that, I'm just wondering, what would be the easiest, most hassle-free way to add authentication? The app is already written in straight Python so any extra code I use will only be used to for this purpose.
[ "Store the user's login, the salted hash of their password, and the salt in a database. (If you're going for cryptographic overkill, you can use a very expensive-to-compute hashing algorithm like bcrypt.)\nYou can use SQLite as that's bundled with Python, but it would probably make more sense to install a database ...
[ 2 ]
[]
[]
[ "authentication", "frameworks", "python" ]
stackoverflow_0003695702_authentication_frameworks_python.txt
Q: django, distinct() not behaving For some reason duplicate values aren't eliminated. records = Records.objects.all() records2 = records.values_list('columna','columna').distinct() print records2 I must be doing something stupid A: My solution was to cast the values_list to a set (to remove duplicates) then back to a list
django, distinct() not behaving
For some reason duplicate values aren't eliminated. records = Records.objects.all() records2 = records.values_list('columna','columna').distinct() print records2 I must be doing something stupid
[ "My solution was to cast the values_list to a set (to remove duplicates) then back to a list\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003693405_django_python.txt
Q: python remove last character and id I have list of 34.00B 65.89B 346M I need 34. 65.89 .344 So, how do i remove last character, is if B or M, divide M's by 1000. A: I think you just want something like this: divisors = {'B': 1, 'M': 1000} def fn(number): if number[-1] in divisors: return str(float(number[:-1]) / divisors[number[-1]]) return number map(fn, ['34.00B', '65.89B', '346M']) I converted the return value back to a string since your question was a little unclear A: Not sure if I understood the question clearly, the following code removes the last character and returns a float of the value (dividing by 1000 if the last character was 'M'). lst=[ "34.00B", "65.89B", "346M" ] lst=map(lambda x: float(x[:-1]) if x[-1]=='B' else float(x[:-1])/1000, lst) print lst
python remove last character and id
I have list of 34.00B 65.89B 346M I need 34. 65.89 .344 So, how do i remove last character, is if B or M, divide M's by 1000.
[ "I think you just want something like this:\ndivisors = {'B': 1, 'M': 1000}\ndef fn(number):\n if number[-1] in divisors:\n return str(float(number[:-1]) / divisors[number[-1]])\n return number\n\nmap(fn, ['34.00B', '65.89B', '346M'])\n\nI converted the return value back to a string since your question...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003695756_python.txt
Q: django custom form validation In Django/Python, when you make a custom form, does it need to have a clean() method, or will calling .is_valid() perform a default validation? if request.method == 'POST': filter = FilterForm(request.POST) if filter.is_valid(): print 'Month is ' + filter.cleaned_data['month'] print 'Type is ' + filter.cleaned_data['type'] print 'Number is ' +filter.cleaned_data['number'] else: print 'Invalid form' print filter.errors "Invalid Form" gets printed but no errors get printed. class FilterForm(forms.Form): months = [('January','January'), ('February','February'), ('March','March'), ('April','April'), ('May','May'), ('June','June'), ('July','July'), ('August','August'), ('September','September'), ('October','October'), ('November','November'), ('December','December'),] types = [('text','Text'), ('call','Call'),] month = forms.ChoiceField(months) type = forms.ChoiceField(choices=types,widget=forms.CheckboxSelectMultiple) def __init__(self,numbers,*args, **kwargs): super(FilterForm,self).__init__(*args, **kwargs) self.fields['number'] = forms.ChoiceField(choices=numbers) def clean(self): return self.cleaned_data I've tried it with and without the clean method. A: does it need to have a clean() method No. Completely optional. There's a big list of things that Django does in a specific order when it validates forms. You can learn about the process here: http://docs.djangoproject.com/en/dev/ref/forms/validation/ As for finding your problem, if you stick a {{form.errors}} on your template, you'll see which field is blowing up. I have a feeling it could be that your choices is defined in a place that something can't get a handle on when it needs to (Move them out of the class). Edit: Almost missed this. Look at this line: def __init__(self,numbers,*args, **kwargs) And then look at this line: filter = FilterForm(request.POST) You need to pass the numbers argument in this time too. It's a completely new instance. it can't validate because it doesn't know what numbers is. A: If you have no specific clean method, Django will still validate all the fields in your form to ensure that all required fields are present, that they have the correct type where necessary, and that fields with choices have a value corresponding to one of the choices. There are a couple of issues with this form that could be causing your problem. Firstly, you have overridden __init__ so that the first parameter after self is numbers. However, when you instantiate the form you don't pass this parameter - you just pass request.POST. Secondly, it's a bad idea to add fields dynamically to self.fields as you do in __init__. Instead, declare your number field with an empty choices list and just set that in __init__: self.fields['number'].choices = numbers
django custom form validation
In Django/Python, when you make a custom form, does it need to have a clean() method, or will calling .is_valid() perform a default validation? if request.method == 'POST': filter = FilterForm(request.POST) if filter.is_valid(): print 'Month is ' + filter.cleaned_data['month'] print 'Type is ' + filter.cleaned_data['type'] print 'Number is ' +filter.cleaned_data['number'] else: print 'Invalid form' print filter.errors "Invalid Form" gets printed but no errors get printed. class FilterForm(forms.Form): months = [('January','January'), ('February','February'), ('March','March'), ('April','April'), ('May','May'), ('June','June'), ('July','July'), ('August','August'), ('September','September'), ('October','October'), ('November','November'), ('December','December'),] types = [('text','Text'), ('call','Call'),] month = forms.ChoiceField(months) type = forms.ChoiceField(choices=types,widget=forms.CheckboxSelectMultiple) def __init__(self,numbers,*args, **kwargs): super(FilterForm,self).__init__(*args, **kwargs) self.fields['number'] = forms.ChoiceField(choices=numbers) def clean(self): return self.cleaned_data I've tried it with and without the clean method.
[ "\ndoes it need to have a clean() method\n\nNo. Completely optional.\nThere's a big list of things that Django does in a specific order when it validates forms. You can learn about the process here:\nhttp://docs.djangoproject.com/en/dev/ref/forms/validation/\nAs for finding your problem, if you stick a {{form.error...
[ 3, 3 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003695794_django_django_forms_python.txt
Q: how do I create an indented block in Python? for example, how to I enter this in Python so that it is indented correctly? if 1 + 2 == 2: print "true" print "this is my second line of the block" print "this is the third line of the block" A: This is correctly indented. if 1 + 2 == 2: print "true" print "this is my second line of the block" print "this is the third line of the block" If you're using python's REPL... simply enter no spaces before the first line, and an arbitrary but consistent number of spaces for indented lines (standard is for spaces) within the block. Edit: added per request -- Since your background is in Java, you could roughly equate pythons indentation rules for blocks to Java's use of curly braces. For example, an else statement could be added like so: if thisRef is True: print 'I read the python tutorial' else print 'I may have skimmed a blog about python' You could even, if you choose, mimic a "bracist" (as pythonistas colloquialy call them) language with comments to help you visualize -- if thisRef is True: # { print 'I read the python tutorial' # } else # { print 'I may have skimmed a blog about python' # } Put simply, by changing indentation levels, you change block depth. I cannot emphasize enough the importance of reading such documents as PEP8, which is highlighted in Section 4.8, or any number of other pieces of documentation on the basic rules of indentation in python. A: Indenting in Python "Correctly" means "consistently". "Note that each line within a basic block must be indented by the same amount." Reference http://docs.python.org/tutorial/controlflow.html#intermezzo-coding-style summarizes the rest of the things you need to do to write "correct" Python as per PEP-8
how do I create an indented block in Python?
for example, how to I enter this in Python so that it is indented correctly? if 1 + 2 == 2: print "true" print "this is my second line of the block" print "this is the third line of the block"
[ "This is correctly indented.\nif 1 + 2 == 2:\n print \"true\"\n print \"this is my second line of the block\"\n print \"this is the third line of the block\"\n\nIf you're using python's REPL... simply enter no spaces before the first line, and an arbitrary but consistent number of spaces for indented lines...
[ 4, 2 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0003695837_if_statement_python.txt
Q: SVG Glyphs in Pyqt How do I render glyphs in pyqt using the svggraphicsItem? A: Recently I found that svg files generated by Cairo do not plot properly in pyqt. The error comes from the use of glyphs which seem not to be shown in pyqt (this might be wrong but I couldn't find any way of getting glyphs to render). I ended up writing a set of functions that will convert the glyphs to svg paths so the file will render normally. These could still use some improvements for rendering color and other style elements (which are locked in the functions that I wrote). These functions will need to be embedded in a class or have self removed to be used elsewhere. I just wanted people to have these so they wouldn't have to search high and low like I did to find a way to render glyphs in pyqt. Hope for the best, Kyle def convertSVG(self, file): dom = self._getsvgdom(file) print dom self._switchGlyphsForPaths(dom) self._commitSVG(file, dom) def _commitSVG(self, file, dom): f = open(file, 'w') dom.writexml(f) f.close() def _getsvgdom(self, file): print 'getting DOM model' import xml.dom import xml.dom.minidom as mini f = open(file, 'r') svg = f.read() f.close() dom = mini.parseString(svg) return dom def _getGlyphPaths(self, dom): symbols = dom.getElementsByTagName('symbol') glyphPaths = {} for s in symbols: pathNode = [p for p in s.childNodes if 'tagName' in dir(p) and p.tagName == 'path'] glyphPaths[s.getAttribute('id')] = pathNode[0].getAttribute('d') return glyphPaths def _switchGlyphsForPaths(self, dom): glyphs = self._getGlyphPaths(dom) use = self._getUseTags(dom) for glyph in glyphs.keys(): print glyph nl = self.makeNewList(glyphs[glyph].split(' ')) u = self._matchUseGlyphs(use, glyph) for u2 in u: print u2, 'brefore' self._convertUseToPath(u2, nl) print u2, 'after' def _getUseTags(self, dom): return dom.getElementsByTagName('use') def _matchUseGlyphs(self, use, glyph): matches = [] for i in use: print i.getAttribute('xlink:href') if i.getAttribute('xlink:href') == '#'+glyph: matches.append(i) print matches return matches def _convertUseToPath(self, use, strokeD): ## strokeD is a list of lists of strokes to make the glyph newD = self.nltostring(self.resetStrokeD(strokeD, use.getAttribute('x'), use.getAttribute('y'))) use.tagName = 'path' use.removeAttribute('xlink:href') use.removeAttribute('x') use.removeAttribute('y') use.setAttribute('style', 'fill: rgb(0%,0%,0%); stroke-width: 0.5; stroke-linecap: round; stroke-linejoin: round; stroke: rgb(0%,0%,0%); stroke-opacity: 1;stroke-miterlimit: 10; ') use.setAttribute('d', newD) def makeNewList(self, inList): i = 0 nt = [] while i < len(inList): start = i + self.listFind(inList[i:], ['M', 'L', 'C', 'Z']) end = start + self.listFind(inList[start+1:], ['M', 'L', 'C', 'Z', '', ' ']) nt.append(inList[start:end+1]) i = end + 1 return nt def listFind(self, x, query): for i in range(len(x)): if x[i] in query: return i return len(x) def resetStrokeD(self, strokeD, x, y): nsd = [] for i in strokeD: nsd.append(self.resetXY(i, x, y)) return nsd def resetXY(self, nl, x, y): # convert a list of strokes to xy coords nl2 = [] for i in range(len(nl)): if i == 0: nl2.append(nl[i]) elif i%2: # it's odd nl2.append(float(nl[i]) + float(x)) elif not i%2: # it's even nl2.append(float(nl[i]) + float(y)) else: print i, nl[i], 'error' return nl2 def nltostring(self, nl): # convert a colection of nl's to a string col = [] for l in nl: templ = [] for c in l: templ.append(str(c)) templ = ' '.join(templ) col.append(templ) return ' '.join(col)
SVG Glyphs in Pyqt
How do I render glyphs in pyqt using the svggraphicsItem?
[ "Recently I found that svg files generated by Cairo do not plot properly in pyqt. The error comes from the use of glyphs which seem not to be shown in pyqt (this might be wrong but I couldn't find any way of getting glyphs to render). \nI ended up writing a set of functions that will convert the glyphs to svg path...
[ 4 ]
[]
[]
[ "graphics", "pyqt", "python", "rendering", "svg" ]
stackoverflow_0003682127_graphics_pyqt_python_rendering_svg.txt
Q: How to know the directory where the python script is called? Let's say that I have a python script a.py in /A/B/a.py, and it's in the PATH environment variable. The current working directory is /X/Y/, and it's the directory where I call the /A/B/a.py. In a.py, how to detect /X/Y/? I mean, how to know in which directory the python call is made? A: You can get the current working directory with: os.getcwd() A: >> os.getcwd() /X/Y >> os.path.dirname(os.path.realpath(__file__)) # cannot be called interactively /A/B >> sys.path[0] /A/B >> os.path.abspath(sys.argv[0]) /A/B/a.py
How to know the directory where the python script is called?
Let's say that I have a python script a.py in /A/B/a.py, and it's in the PATH environment variable. The current working directory is /X/Y/, and it's the directory where I call the /A/B/a.py. In a.py, how to detect /X/Y/? I mean, how to know in which directory the python call is made?
[ "You can get the current working directory with:\nos.getcwd()\n\n", ">> os.getcwd()\n/X/Y\n>> os.path.dirname(os.path.realpath(__file__)) # cannot be called interactively\n/A/B\n>> sys.path[0]\n/A/B\n>> os.path.abspath(sys.argv[0])\n/A/B/a.py\n\n" ]
[ 33, 8 ]
[]
[]
[ "path", "python" ]
stackoverflow_0003696223_path_python.txt
Q: python doctest: stop example execution and use the resulting context in some shell i think there was some directive i could enter in the test that would allow me to run some commands interactively at the point of the directive and then continue the example, but i dont remember what it was... A: Do you mean you place a breakpoint in your test to enter the debugger? import pdb; pdb.set_trace()
python doctest: stop example execution and use the resulting context in some shell
i think there was some directive i could enter in the test that would allow me to run some commands interactively at the point of the directive and then continue the example, but i dont remember what it was...
[ "Do you mean you place a breakpoint in your test to enter the debugger?\nimport pdb; pdb.set_trace()\n\n" ]
[ 2 ]
[]
[]
[ "doctest", "python" ]
stackoverflow_0003696225_doctest_python.txt
Q: windows python script to traverse directory to remove folders, restart PC and continue the next line of the script? I want to remove a incorrectly installed program and reinstall it. I can remove the program with subprocess.Popen calling the msiexe on it and install new program the same way BUT ONLY with two independent scripts. But i also need to remove some folders in C:\Programs files and also in C:\Doc& Settings. How can i traverse through the directory structure and remove the folders?Also how can i continue the script after restart the PC from the next line to install the new program. A: In a nutshell, here's what you'll need to do. You can delete the files and folders by using the remove() and rmdir() or removedirs() methods in the os module (assuming your user/program has administrative rights). To restart your script you will first need to add some command line argument handling to it that allows it to be told whether to start from the beginning or continue from the other point. To get the script to run after restart, you'll need to set a value in the Windows registry. I believe they're stored under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceand HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOncekeys. There you can add a string value (type REG_SZ) which contains a command line to invoke your script and pass it the appropriate command line argument(s) which will tell it to continue and re-install the program.
windows python script to traverse directory to remove folders, restart PC and continue the next line of the script?
I want to remove a incorrectly installed program and reinstall it. I can remove the program with subprocess.Popen calling the msiexe on it and install new program the same way BUT ONLY with two independent scripts. But i also need to remove some folders in C:\Programs files and also in C:\Doc& Settings. How can i traverse through the directory structure and remove the folders?Also how can i continue the script after restart the PC from the next line to install the new program.
[ "In a nutshell, here's what you'll need to do.\nYou can delete the files and folders by using the remove() and rmdir() or removedirs() methods in the os module (assuming your user/program has administrative rights).\nTo restart your script you will first need to add some command line argument handling to it that al...
[ 1 ]
[]
[]
[ "directory", "python", "traversal", "windows" ]
stackoverflow_0003694051_directory_python_traversal_windows.txt
Q: Submitting Google with PyQT QWebElement The following code does not reach searchResults. I have printed out documentElement.findFirst('input[name="btnG"]') and found it to be <input name="btnG" type="submit" value="Google Search" class="lsb"> so we are good up to that point. Note that my goal is not to scrape Google but it's simpler to learn via the well known and public Google. #!/usr/bin/python from PyQt4.QtCore import QUrl, SIGNAL from PyQt4.QtGui import QApplication from PyQt4.QtWebKit import QWebPage, QWebView class Scrape(QApplication): def __init__(self): super(Scrape, self).__init__(None) self.webView = QWebView() self.webView.loadFinished.connect(self.searchForm) def load(self, url): self.webView.load(QUrl(url)) def searchForm(self): documentElement = self.webView.page().currentFrame().documentElement() inputSearch = documentElement.findFirst('input[title="Google Search"]') inputSearch.setAttribute('value', 'test') self.webView.loadFinished.disconnect(self.searchForm) self.webView.loadFinished.connect(self.searchResults) documentElement.findFirst('input[name="btnG"]').evaluateJavaScript('click()') def searchResults(self): for element in documentElement.find('li[class="g"]'): print unicode(element.toOuterXml()) self.exit() my_scrape = Scrape() my_scrape.load('http://google.com/ncr') my_scrape.exec_() A: I have finally figured it out! and submitted to http://drupal4hu.com/node/266
Submitting Google with PyQT QWebElement
The following code does not reach searchResults. I have printed out documentElement.findFirst('input[name="btnG"]') and found it to be <input name="btnG" type="submit" value="Google Search" class="lsb"> so we are good up to that point. Note that my goal is not to scrape Google but it's simpler to learn via the well known and public Google. #!/usr/bin/python from PyQt4.QtCore import QUrl, SIGNAL from PyQt4.QtGui import QApplication from PyQt4.QtWebKit import QWebPage, QWebView class Scrape(QApplication): def __init__(self): super(Scrape, self).__init__(None) self.webView = QWebView() self.webView.loadFinished.connect(self.searchForm) def load(self, url): self.webView.load(QUrl(url)) def searchForm(self): documentElement = self.webView.page().currentFrame().documentElement() inputSearch = documentElement.findFirst('input[title="Google Search"]') inputSearch.setAttribute('value', 'test') self.webView.loadFinished.disconnect(self.searchForm) self.webView.loadFinished.connect(self.searchResults) documentElement.findFirst('input[name="btnG"]').evaluateJavaScript('click()') def searchResults(self): for element in documentElement.find('li[class="g"]'): print unicode(element.toOuterXml()) self.exit() my_scrape = Scrape() my_scrape.load('http://google.com/ncr') my_scrape.exec_()
[ "I have finally figured it out! and submitted to http://drupal4hu.com/node/266\n" ]
[ 0 ]
[]
[]
[ "pyqt", "python", "qwebelement", "qwebview" ]
stackoverflow_0003695781_pyqt_python_qwebelement_qwebview.txt
Q: Django POST/GET exercise I'm trying to practice some django basics by implementing my own sortable table in Django and I've run into a couple of snags. Here's the code that I'm working with in my view: def __table_view_helper__(request): if not request.session.__contains__('filters'): filters = {'filterA':'', 'filterB':'', 'filterC':''} request.session['filters'] = filters if not request.session.__contains__('headers'): headers = {'sortA':'asc', 'sortB':'des', 'sortC':'asc', 'sortD':'asc'} request.session['headers'] = headers def table_view(request): __table_view_helper__(request) records = Record.objects.all() nums = list(set(records.values_list('fieldA','fieldA'))) nums.sort() if request.method == 'POST': filter = FilterForm(nums,request.POST) if filter.is_valid(): fieldA = filter.cleaned_data['fieldA'] fieldB = filter.cleaned_data['fieldB'] fieldC = filter.cleaned_data['fieldC'] filters = request.session['filters'] filters['fieldA'] = fieldA filters['fieldB'] = fieldB filters['fieldC'] = fieldC request.session['filters'] = filters else: filter = FilterForm(nums) filters = request.session['filters'] filter.fields['fieldA'].initial = filters['fieldA'] filter.fields['fieldB'].initial = filters['fieldB'] filter.fields['fieldC'].initial = filters['fieldC'] if filters['fieldA']: records = records.filter(fieldA=filters['fieldA']) if filters['fieldB']: records = records.filter(fieldB__in=filters['fieldB']) if filters['fieldC']: records = records.filter(fieldC=filters['fieldC']) sort = request.GET.get('sort') if sort is not None: headers = request.session['headers'] if headers[sort] == "des": records = records.order_by(sort).reverse() headers[sort] = "asc" else: records = records.order_by(sort) headers[sort] = "des" request.session['headers'] = headers return render_to_response("secure/table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records,'fform':filter}) I changed a lot of my code to use sessions now. It works fine. Is this a good way to do this you think? A: To set the initial values from the view you have to do: filter.fields['fieldA'].initial = filters['filterA'] To keep user related data persistent through different requests you shouldn't use globals, but sessions!
Django POST/GET exercise
I'm trying to practice some django basics by implementing my own sortable table in Django and I've run into a couple of snags. Here's the code that I'm working with in my view: def __table_view_helper__(request): if not request.session.__contains__('filters'): filters = {'filterA':'', 'filterB':'', 'filterC':''} request.session['filters'] = filters if not request.session.__contains__('headers'): headers = {'sortA':'asc', 'sortB':'des', 'sortC':'asc', 'sortD':'asc'} request.session['headers'] = headers def table_view(request): __table_view_helper__(request) records = Record.objects.all() nums = list(set(records.values_list('fieldA','fieldA'))) nums.sort() if request.method == 'POST': filter = FilterForm(nums,request.POST) if filter.is_valid(): fieldA = filter.cleaned_data['fieldA'] fieldB = filter.cleaned_data['fieldB'] fieldC = filter.cleaned_data['fieldC'] filters = request.session['filters'] filters['fieldA'] = fieldA filters['fieldB'] = fieldB filters['fieldC'] = fieldC request.session['filters'] = filters else: filter = FilterForm(nums) filters = request.session['filters'] filter.fields['fieldA'].initial = filters['fieldA'] filter.fields['fieldB'].initial = filters['fieldB'] filter.fields['fieldC'].initial = filters['fieldC'] if filters['fieldA']: records = records.filter(fieldA=filters['fieldA']) if filters['fieldB']: records = records.filter(fieldB__in=filters['fieldB']) if filters['fieldC']: records = records.filter(fieldC=filters['fieldC']) sort = request.GET.get('sort') if sort is not None: headers = request.session['headers'] if headers[sort] == "des": records = records.order_by(sort).reverse() headers[sort] = "asc" else: records = records.order_by(sort) headers[sort] = "des" request.session['headers'] = headers return render_to_response("secure/table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records,'fform':filter}) I changed a lot of my code to use sessions now. It works fine. Is this a good way to do this you think?
[ "To set the initial values from the view you have to do:\nfilter.fields['fieldA'].initial = filters['filterA']\n\nTo keep user related data persistent through different requests you shouldn't use globals, but sessions!\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003696502_django_django_forms_python.txt
Q: Python trim last and sort list I have list MC below: MC = [('GGP', '4.653B'), ('JPM', '157.7B'), ('AIG', '24.316B'), ('RX', 'N/A'), ('PFE', '136.6B'), ('GGP', '4.653B'), ('MNKD', '672.3M'), ('ECLP', 'N/A'), ('WYE', 'N/A')] def fn(number): divisors = {'B': 1, 'M': 1000} if number[-1] in divisors: return ((float(number[:-1]) / divisors[number[-1]]) return number map(fn, MC) How do I remove B, M with fn, and sort list mc high to low. A: def fn(tup): number = tup[1] divisors = {'B': 1, 'M': 1000} if number[-1] in divisors: return (tup[0], float(number[:-1]) / divisors[number[-1]]) else: return tup The problem is that that function was meant to run on a string representation of a number but you were passing it a tuple. So just pull the 1'st element of the tuple. Then return a tuple consisting of the 0'th element and the transformed 1'st element if the 1'st element is transformable or just return the tuple. Also, I stuck an else clause in there because I find them more readable. I don't know which is more efficient. as far as sorting goes, use sorted with a key keyword argument either: MC = sorted(map(fn, MC), key=lambda x: x[0]) to sort by ticker or MC = sorted(map(fn, MC), key=lambda x: x[1] ) to sort by price. Just pass reversed=True to the reversed if you want it high to low: MC = sorted(map(fn, MC), key=lambda x: x[1], reversed=True) you can find other nifty sorting tips here: http://wiki.python.org/moin/HowTo/Sorting/
Python trim last and sort list
I have list MC below: MC = [('GGP', '4.653B'), ('JPM', '157.7B'), ('AIG', '24.316B'), ('RX', 'N/A'), ('PFE', '136.6B'), ('GGP', '4.653B'), ('MNKD', '672.3M'), ('ECLP', 'N/A'), ('WYE', 'N/A')] def fn(number): divisors = {'B': 1, 'M': 1000} if number[-1] in divisors: return ((float(number[:-1]) / divisors[number[-1]]) return number map(fn, MC) How do I remove B, M with fn, and sort list mc high to low.
[ " def fn(tup):\n number = tup[1]\n divisors = {'B': 1, 'M': 1000}\n if number[-1] in divisors:\n return (tup[0], float(number[:-1]) / divisors[number[-1]])\n else:\n return tup\n\nThe problem is that that function was meant to run on a string representation of a nu...
[ 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003696648_python_sorting.txt
Q: python: does `for i in obj.func()` re-run `func` every iteration? let's say I have the following code: for a in object.a_really_huge_function(): print a In order to prevent a_really_huge_function from running multiple times, I am used to doing this in other languages: a_list = object.a_really_huge_function() for a in a_list: print a Is that necessary in Python? Will the part after in run on every single loop? A: The python interpreter is your friend. >>> def some_func(): ... print 'in some_func' ... return [1, 2, 3, 10] ... >>> for a in some_func(): ... print a ... in some_func 1 2 3 10 In short, no, it gets called once. A: You can also use generators to avoid returning huge results by relinquishing control after each step of the algorithm as follows: def a_really_huge_fuction(huge_number): i = 0 while i < huge_number: yield i # Relinquishes control to caller, resume execution at next line i = i + 1 In this case, the function is called once, but has its execution spread over huge_number different times. See the yield documentation for more details. A: It's not necessary. for a in object.a_really_huge_function(): calls a_really_huge_function only once. The only advantage of saving the result in a variable would be if you are calling the same function elsewhere in your code. If the function returns a list, you might do better in terms of memory usage by making object.a_really_huge_function() return an iterator, but otherwise you are fine.
python: does `for i in obj.func()` re-run `func` every iteration?
let's say I have the following code: for a in object.a_really_huge_function(): print a In order to prevent a_really_huge_function from running multiple times, I am used to doing this in other languages: a_list = object.a_really_huge_function() for a in a_list: print a Is that necessary in Python? Will the part after in run on every single loop?
[ "The python interpreter is your friend. \n>>> def some_func():\n... print 'in some_func'\n... return [1, 2, 3, 10]\n... \n>>> for a in some_func():\n... print a\n... \nin some_func\n1\n2\n3\n10\n\nIn short, no, it gets called once.\n", "You can also use generators to avoid returning huge results by r...
[ 8, 4, 1 ]
[]
[]
[ "for_loop", "loops", "optimization", "python" ]
stackoverflow_0003696992_for_loop_loops_optimization_python.txt
Q: which one of those python implementations is better which one of the following is considered better a design and why ?. i have 2 classes , one for the gui components and the other is for it's events. please put in mind that the eventClass will be implemented so many times, (sometimes to get data from an oracle databases and sometimes mysql databases ) class MainWindow: def __init__(self): self.myEvents = eventClass() # the class that has all the events self.button = button # consider it a button from any gui library self.menu = menu # menu box def bottonEvent(self): data = self.myEvents.buttonEvent() self.menu.populate(data) class eventClass: def __init__(self): pass def getData(self): return data # return data to puplate in the list OR class MainWindow: def __init__(self): self.myEvents = eventClass(self) # the class that has all the events self.button = button # consider it a button from any gui library self.menu = menu # menu box def bottonEvent(self): self.myEvents.ButtonEvent() class eventClass: def __init__(self,window): pass def ButtonEvent(self): window.menu.populateData() please inform me if anything was unclear please help , thanks in advance A: The first choice is better "decoupled": the event class needs and has no knowledge whatsoever about the window object or its menu attribute -- an excellent approach that makes the event class especially easy to unit-test in isolation without any overhead. This is especially nice if many implementations of the same interface need to exist, as you mention they do in your case. The second choice introduces a mutual dependency -- an event object can't work without a window object, and a window object builds an event object. That may be an acceptable complication in more abstruse cases where it buys you something, but for this specific use it sounds more like an arbitrary extra difficulty without any real plus. So, I would recommend the first form.
which one of those python implementations is better
which one of the following is considered better a design and why ?. i have 2 classes , one for the gui components and the other is for it's events. please put in mind that the eventClass will be implemented so many times, (sometimes to get data from an oracle databases and sometimes mysql databases ) class MainWindow: def __init__(self): self.myEvents = eventClass() # the class that has all the events self.button = button # consider it a button from any gui library self.menu = menu # menu box def bottonEvent(self): data = self.myEvents.buttonEvent() self.menu.populate(data) class eventClass: def __init__(self): pass def getData(self): return data # return data to puplate in the list OR class MainWindow: def __init__(self): self.myEvents = eventClass(self) # the class that has all the events self.button = button # consider it a button from any gui library self.menu = menu # menu box def bottonEvent(self): self.myEvents.ButtonEvent() class eventClass: def __init__(self,window): pass def ButtonEvent(self): window.menu.populateData() please inform me if anything was unclear please help , thanks in advance
[ "The first choice is better \"decoupled\": the event class needs and has no knowledge whatsoever about the window object or its menu attribute -- an excellent approach that makes the event class especially easy to unit-test in isolation without any overhead. This is especially nice if many implementations of the s...
[ 5 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003697066_oop_python.txt
Q: Possible to sandbox Python configuration file? I'm thinking of implementing a configuration file written in Python syntax, not unlike what Django does. While I've seen one or two SO questions about the merits of using executable code in configuration files, I'm curious whether there is a way to execute the config file code in a "sandbox" to prevent mistakes in the code from locking up the host application. Because the host application is a programmer's tool, I'm not concerned about teaching Python syntax or introducing security holes as mentioned in at least one other SO question. But I am worried about the configuration code branching to Fishkill and wedging the host app. I'd much rather that the host app trap those problems and display diagnostic error information. Has anyone tried this sort of sandboxing for a Python configuration file? And, if so, what techniques proved useful, and what pitfalls cropped up that I should be aware of? A: We do this for some of our internal tools What we do protects us from exception issues and discourages any attempts by the users to get overly creative in the config scripts. However it doesn't protect us from infinite loops or actively malicious third parties. The core of the approach here is to run the script in a locked down exec. First we go through the __ builtin __ module and del everything we don't want them to be able to touch, especially __ import __. We actually do this in a context manager which backs the original values up and dels them on the way in and then restores the original values on the way back out. Next we create an empty dictionary to be the config scripts namespace. Then we exec the config with the namespace. The exec is of course wrapped in a try except that will catch anything. And finally we inspect the namespace to extract the variables we are interested in. Points to note here: It might be tempting to prepopulate the namespace with stuff that might be useful to the config script, but you want to be very careful doing that you quickly open up hooks back into the host program. The config scripts can still create functions and classes so you might get back something that looks like a string for example, but is actually an arbitrary blob of executable code. Because of these we impose the restriction that our config scripts are expected to produce pure primitive data structures (generally just ints, strings, lists, tuples and None) that we then separately verify. A: Unfortunately there isn't a lot you can do about this issue with standard Python. When the Python interpreter is running the "configuration code" that code can do whatever it likes including accessing the host program or not returning control. Running the configuration code in a separate process might help but also limits the interaction between the host and config code. Your best bet would be to check out the PyPy project's sandbox feature. This might be what you need but may also involve quite a bit of work on your part to integrate. Is there an alternative to rexec for Python sandboxing? also discusses this topic. You should probably also ask yourself how important this problem actually is to you. I guess that depends on your use case and who's going to be writing the configuration code.
Possible to sandbox Python configuration file?
I'm thinking of implementing a configuration file written in Python syntax, not unlike what Django does. While I've seen one or two SO questions about the merits of using executable code in configuration files, I'm curious whether there is a way to execute the config file code in a "sandbox" to prevent mistakes in the code from locking up the host application. Because the host application is a programmer's tool, I'm not concerned about teaching Python syntax or introducing security holes as mentioned in at least one other SO question. But I am worried about the configuration code branching to Fishkill and wedging the host app. I'd much rather that the host app trap those problems and display diagnostic error information. Has anyone tried this sort of sandboxing for a Python configuration file? And, if so, what techniques proved useful, and what pitfalls cropped up that I should be aware of?
[ "We do this for some of our internal tools\nWhat we do protects us from exception issues and discourages any attempts by the users to get overly creative in the config scripts. However it doesn't protect us from infinite loops or actively malicious third parties.\nThe core of the approach here is to run the script ...
[ 3, 2 ]
[]
[]
[ "configuration", "python", "sandbox" ]
stackoverflow_0001757381_configuration_python_sandbox.txt
Q: Help writing the output to another file: Hi here is the program I have: with open('C://avy.txt', "rtU") as f: columns = f.readline().strip().split(" ") numRows = 0 sums = [0] * len(columns) for line in f: # Skip empty lines if not line.strip(): continue values = line.split(" ") for i in xrange(len(values)): sums[i] += int(values[i]) numRows += 1 for index, summedRowValue in enumerate(sums): print columns[index], 1.0 * summedRowValue / numRows I'd like to modify it so that it writes the output to a file called Finished. I keep getting errors when I rewrite. Can someone help please? Thanks A: Change the snippet which now reads: for index, summedRowValue in enumerate(sums): print columns[index], 1.0 * summedRowValue / numRows to make it, instead: with open('Finished', 'w') as ouf: for index, summedRowValue in enumerate(sums): print>>ouf, columns[index], 1.0 * summedRowValue / numRows As you see, it's very easy: you just need to nest the loop in another with statement (to insure proper opening and closing of the output file), and change the bare print to print>>ouf, to instruct print to use open file object ouf instead of standard-output. A: out = open('Finished', 'w') for index, summedRowValue in enumerate(sums): out.write('%s %f\n' % (columns[index], 1.0 * summedRowValue / numRows))
Help writing the output to another file:
Hi here is the program I have: with open('C://avy.txt', "rtU") as f: columns = f.readline().strip().split(" ") numRows = 0 sums = [0] * len(columns) for line in f: # Skip empty lines if not line.strip(): continue values = line.split(" ") for i in xrange(len(values)): sums[i] += int(values[i]) numRows += 1 for index, summedRowValue in enumerate(sums): print columns[index], 1.0 * summedRowValue / numRows I'd like to modify it so that it writes the output to a file called Finished. I keep getting errors when I rewrite. Can someone help please? Thanks
[ "Change the snippet which now reads:\n for index, summedRowValue in enumerate(sums):\n print columns[index], 1.0 * summedRowValue / numRows\n\nto make it, instead:\n with open('Finished', 'w') as ouf:\n for index, summedRowValue in enumerate(sums):\n print>>ouf, columns[index], 1.0 * summedRowVal...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003697163_python.txt
Q: How can I get the base URI in AppEngine? How can I get the base URI in a Google AppEngine app written in Python? I'm using the webapp framework. e.g. http://example.appspot.com/ A: The proper way to parse self.request.url is not with a regular expression, but with Python standard library's urlparse module: import urlparse ... o = urlparse.urlparse(self.request.url) Object o will be an instance of the ParseResult class with string-valued fields such as o.scheme (probably http;-) and o.netloc ('example.appspot.com' in your case). You can put some of the strings back together again with the urlparse.urlunparse function from the same module, e.g. s = urlparse.urlunparse((o.scheme, o.netloc, '', '', '', '')) which would give you in s the string 'http://example.appspot.com' in this case. A: If you just want to find your app ID, you can get that from the environment without having to parse the current URL. The environment variable is APPLICATION_ID You can also use this to find the current version (CURRENT_VERSION_ID), auth domain (which will let you know whether you're running on appspot.com, AUTH_DOMAIN) and whether you're running on the local development server or in production (SERVER_SOFTWARE). So to get the full base URL, try something like this: import os def get_base_url(): if os.environ[AUTH_DOMAIN] == "gmail.com": app_id = os.environ[APPLICATION_ID] return "http://" + app_id + ".appspot.com" else: return "http://" + os.environ[AUTH_DOMAIN] edit: AUTH_DOMAIN contains the custom domain, no need to include the app ID. This will return the current version's base URL even if you're not accessing the current version, or if you visit the current version using a URL like http://current-version.latest.app_id.appspot.com (unlike URL-parsing methods)
How can I get the base URI in AppEngine?
How can I get the base URI in a Google AppEngine app written in Python? I'm using the webapp framework. e.g. http://example.appspot.com/
[ "The proper way to parse self.request.url is not with a regular expression, but with Python standard library's urlparse module:\nimport urlparse\n\n...\n\no = urlparse.urlparse(self.request.url)\n\nObject o will be an instance of the ParseResult class with string-valued fields such as o.scheme (probably http;-) and...
[ 5, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003697033_google_app_engine_python.txt
Q: Why isn't my route working? The index route works when I go to /home/index But it doesn't work why I type /home/test What is wrong here, very confused! import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect from helloworld.lib.base import BaseController, render log = logging.getLogger(name) class HelloController(BaseController): def index(self): # Return a rendered template #return render('/hello.mako') # or, return a string return 'Hello World from index() action!' def test(self): return 'blah' I get this error: WebError Traceback: ⇝ NotImplementedError: Action u'test' is not implemented View as: Interactive | Text | XML (full) URL: http://127.0.0.1:5000/hello/test Module weberror.evalexception:431 in respond view >> app_iter = self.application(environ, detect_start_response) Module beaker.middleware:152 in __call__ view >> return self.wrap_app(environ, session_start_response) Module routes.middleware:131 in __call__ view >> response = self.app(environ, start_response) Module pylons.wsgiapp:107 in __call__ view >> response = self.dispatch(controller, environ, start_response) Module pylons.wsgiapp:312 in dispatch view >> return controller(environ, start_response) Module helloworld.lib.base:15 in __call__ view >> return WSGIController.__call__(self, environ, start_response) Module pylons.controllers.core:211 in __call__ view >> response = self._dispatch_call() Module pylons.controllers.core:168 in _dispatch_call view >> action) NotImplementedError: Action u'test' is not implemented A: Double check your indentation. If def test(self) is on the same indentation level as the class, you won't get an indentation error. This throws an indentation error: class HelloController(BaseController): def index(self): return "hello from index()" def test(self): return "blah" This doesn't: class HelloController(BaseController): def index(self): return "hello from index()" def test(self): return "blah"
Why isn't my route working?
The index route works when I go to /home/index But it doesn't work why I type /home/test What is wrong here, very confused! import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect from helloworld.lib.base import BaseController, render log = logging.getLogger(name) class HelloController(BaseController): def index(self): # Return a rendered template #return render('/hello.mako') # or, return a string return 'Hello World from index() action!' def test(self): return 'blah' I get this error: WebError Traceback: ⇝ NotImplementedError: Action u'test' is not implemented View as: Interactive | Text | XML (full) URL: http://127.0.0.1:5000/hello/test Module weberror.evalexception:431 in respond view >> app_iter = self.application(environ, detect_start_response) Module beaker.middleware:152 in __call__ view >> return self.wrap_app(environ, session_start_response) Module routes.middleware:131 in __call__ view >> response = self.app(environ, start_response) Module pylons.wsgiapp:107 in __call__ view >> response = self.dispatch(controller, environ, start_response) Module pylons.wsgiapp:312 in dispatch view >> return controller(environ, start_response) Module helloworld.lib.base:15 in __call__ view >> return WSGIController.__call__(self, environ, start_response) Module pylons.controllers.core:211 in __call__ view >> response = self._dispatch_call() Module pylons.controllers.core:168 in _dispatch_call view >> action) NotImplementedError: Action u'test' is not implemented
[ "Double check your indentation. If def test(self) is on the same indentation level as the class, you won't get an indentation error.\nThis throws an indentation error:\nclass HelloController(BaseController):\n def index(self):\n return \"hello from index()\"\n\n def test(self):\n return \"blah\"\n...
[ 2 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003695670_pylons_python.txt
Q: SQLAlchemy Select statement - SQL Syntax Error I have created a table (MySQL 5.1) from sqlalchemy import * def get(): db = create_engine('mysql://user:password@localhost/database') db.echo = True metadata = MetaData(db) feeds = Table('feeds', metadata, Column('id', Integer, primary_key=True), Column('title', String(100)), Column('link', String(255)), Column('description', String(255)), ) entries = Table('entries', metadata, Column('id', Integer, primary_key=True), Column('fid', Integer), Column('url', String(255)), Column('title', String(255)), Column('content', String(5000)), Column('date', DateTime), ) feeds.create() entries.create() But when I try to query it: from sqlalchemy import * db = create_engine('mysql://user:password@localhost/database') metadata = MetaData(db) feeds = Table('feeds', metadata) s = feeds.select() result = db.execute(s) I get an error on the result = db.execute(s) line indicating the following: sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM feeds' at line 2") 'SELECT \nFROM feeds' () I'm obviously new to SQLAlchemy, and I have no idea what I'm doing wrong, despite having googled every tutorial on the web and changed this a million times. Any help? A: I suspect Table.select() is only for selecting specific columns. For SELECT *, the expression language tutorial uses this syntax instead: from sqlalchemy.sql import select s = select([feeds]) result = db.execute(s) A: there's something missing probably from your feeds.select() call, I'd have another look at the API documentation for this function.
SQLAlchemy Select statement - SQL Syntax Error
I have created a table (MySQL 5.1) from sqlalchemy import * def get(): db = create_engine('mysql://user:password@localhost/database') db.echo = True metadata = MetaData(db) feeds = Table('feeds', metadata, Column('id', Integer, primary_key=True), Column('title', String(100)), Column('link', String(255)), Column('description', String(255)), ) entries = Table('entries', metadata, Column('id', Integer, primary_key=True), Column('fid', Integer), Column('url', String(255)), Column('title', String(255)), Column('content', String(5000)), Column('date', DateTime), ) feeds.create() entries.create() But when I try to query it: from sqlalchemy import * db = create_engine('mysql://user:password@localhost/database') metadata = MetaData(db) feeds = Table('feeds', metadata) s = feeds.select() result = db.execute(s) I get an error on the result = db.execute(s) line indicating the following: sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM feeds' at line 2") 'SELECT \nFROM feeds' () I'm obviously new to SQLAlchemy, and I have no idea what I'm doing wrong, despite having googled every tutorial on the web and changed this a million times. Any help?
[ "I suspect Table.select() is only for selecting specific columns. For SELECT *, the expression language tutorial uses this syntax instead:\nfrom sqlalchemy.sql import select\ns = select([feeds])\nresult = db.execute(s)\n\n", "there's something missing probably from your feeds.select() call, I'd have another look ...
[ 1, 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0003697350_python_sql_sqlalchemy.txt
Q: In textmate, how do I reverse indent a block of selected code? I have a block of code selected, I want to un-indent this selected code. On a pc, I would do a shift-tab and it would un-indent. A: Option+Shift+Tab (or Cmd+]). Omitting shift (or changing ] to [) will indent instead of reverse-indent. A: The following is from TextMate Power Editing for the Mac by James Edward Gray II. ⌘+[ or ⌥+⇧+⇥ Decrease selection indent (works on current line when nothing is selected) ⌘+] or ⌥+⇥ Increase selection indent (works on current line when nothing is selected) ⌥+⌘+[ Reindent selection based on current language grammar rules (works on current line when nothing is selected)
In textmate, how do I reverse indent a block of selected code?
I have a block of code selected, I want to un-indent this selected code. On a pc, I would do a shift-tab and it would un-indent.
[ "Option+Shift+Tab (or Cmd+]).\nOmitting shift (or changing ] to [) will indent instead of reverse-indent.\n", "The following is from TextMate Power Editing for the Mac by James Edward Gray II.\n\n⌘+[ or ⌥+⇧+⇥ \nDecrease selection indent (works on current line when nothing is selected)\n\n⌘+] or ⌥+⇥\nIncrease sele...
[ 7, 4 ]
[]
[]
[ "python", "textmate" ]
stackoverflow_0003697628_python_textmate.txt
Q: Replacing some part of string with Python I have a SQL string, for example SELECT * FROM benchmark WHERE xversion = 1.0 And actually, xversion is aliased variable, and self.alias has all the alias info something like {'CompilationParameters_Family': 'chip_name', 'xversion': 'CompilationParameters_XilinxVersion', 'opt_param': .... 'chip_name': 'CompilationParameters_Family', 'CompilationParameters_Device': 'device'} Using this alias, I should change the string into as follows. SELECT * FROM benchmark WHERE CompilationParameters_XilinxVersion = 1.0 For this change, I came up with the following. def processAliasString(self, sqlString): components = sqlString.split(' ') resList = [] for comp in components: if comp in self.alias: resList.append(self.alias[comp]) else: resList.append(comp) resString = " ".join(resList) return resString But, I expect better code not using for loop. What do you think? A: This should do it: def processAliasString(self, sqlString): return ' '.join(self.alias.get(comp, comp) for comp in sqlString.split(' ')) A: If you could change your input string's format to make the replacements more clearly visible, e.g. s = 'SELECT * FROM benchmark WHERE %(xversion)s = 1.0' then s % self.alias would suffice (there are some other alternatives available depending on your favorite formatting syntax and Python level). If the input string format is "nailed down", re can help because of the ease it offers to identify word boundaries (so you won't e.g. unexpectedly miss a replacement if an otherwise insignificant space is missing, for example after xversion). Consider (with s having its original form, with substitutables mixed in haphazardly with non-substitutables): import re sre = re.compile('|'.join(r'\b%s\b' % re.escape(s) for s in self.alias)) def repl(mo): return self.alias[mo.group()] news = sre.sub(repl, s) These approaches are fast, since %-formatting and res' sub are really well optimized for such tasks.
Replacing some part of string with Python
I have a SQL string, for example SELECT * FROM benchmark WHERE xversion = 1.0 And actually, xversion is aliased variable, and self.alias has all the alias info something like {'CompilationParameters_Family': 'chip_name', 'xversion': 'CompilationParameters_XilinxVersion', 'opt_param': .... 'chip_name': 'CompilationParameters_Family', 'CompilationParameters_Device': 'device'} Using this alias, I should change the string into as follows. SELECT * FROM benchmark WHERE CompilationParameters_XilinxVersion = 1.0 For this change, I came up with the following. def processAliasString(self, sqlString): components = sqlString.split(' ') resList = [] for comp in components: if comp in self.alias: resList.append(self.alias[comp]) else: resList.append(comp) resString = " ".join(resList) return resString But, I expect better code not using for loop. What do you think?
[ "This should do it:\ndef processAliasString(self, sqlString):\n return ' '.join(self.alias.get(comp, comp) for comp in sqlString.split(' '))\n\n", "If you could change your input string's format to make the replacements more clearly visible, e.g.\ns = 'SELECT * FROM benchmark WHERE %(xversion)s = 1.0'\n\nthen ...
[ 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003697589_python_string.txt
Q: How to test the login func in flask? I write this according to flaskr sample, I can login with browser,but test fails. Thanks for your help! @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': username = request.form['username'] password = request.form['password'] if lib.authenticate_user(username, password): session['logged_in'] = True flash('You were logged in') return render_template('www.html') return render_template('login.html', error=error) tests.py def login(self, username, password): #print username, password return self.app.post('/Login', data=dict( username=username, password=password ), follow_redirects=True) # testing functions def test_login_logout(self): """Make sure login and logout works""" rv = self.login('c1','123') assert 'You were logged in' in rv.data A: I needed to change this part in tests.py: return self.app.post('/Login', data=dict( to this one: return self.app.post('/login', data=dict( Capitalisation matters!
How to test the login func in flask?
I write this according to flaskr sample, I can login with browser,but test fails. Thanks for your help! @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': username = request.form['username'] password = request.form['password'] if lib.authenticate_user(username, password): session['logged_in'] = True flash('You were logged in') return render_template('www.html') return render_template('login.html', error=error) tests.py def login(self, username, password): #print username, password return self.app.post('/Login', data=dict( username=username, password=password ), follow_redirects=True) # testing functions def test_login_logout(self): """Make sure login and logout works""" rv = self.login('c1','123') assert 'You were logged in' in rv.data
[ "I needed to change this part in tests.py:\nreturn self.app.post('/Login', data=dict(\n\nto this one:\nreturn self.app.post('/login', data=dict(\n\nCapitalisation matters!\n" ]
[ 7 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0003697648_flask_python.txt
Q: Python: intersection of lists/sets def boolean_search_and(self, text): results = [] and_tokens = self.tokenize(text) tokencount = len(and_tokens) term1 = and_tokens[0] print ' term 1:', term1 term2 = and_tokens[1] print ' term 2:', term2 #for term in and_tokens: if term1 in self._inverted_index.keys(): resultlist1 = self._inverted_index[term1] print resultlist1 if term2 in self._inverted_index.keys(): resultlist2 = self._inverted_index[term2] print resultlist2 #intersection of two sets casted into a list results = list(set(resultlist1) & set(resultlist2)) print 'results:', results return str(results) This code works great for two tokens, ex: text= "Hello World" and so, tokens = ['hello', 'world']. I want to generalize it for multiple tokens, so the text can be a sentence, or an entire text file. self._inverted_index is a dictionary that saves the tokens as keys and the values are the DocIDs in which the keys/tokens occur. hello -> [1,2,5,6] world -> [1,3,5,7,8] result: hello AND world -> [1,5] I want to achieve result for: say, (((hello AND computer) AND science) AND world) I am working on making this work for multiple words, not just two. I started working in python this mornin', so I'm unaware of a lot of features it has to offer. Any ideas? A: I want to generalize it for multiple tokens def boolean_search_and_multi(self, text): and_tokens = self.tokenize(text) results = set(self._inverted_index[and_tokens[0]]) for tok in and_tokens[1:]: results.intersection_update(self._inverted_index[tok]) return list(results) A: Would the built-in set type work for you? $ python Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) [GCC 4.3.4 20090804 (release) 1] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> hello = set([1,2,5,6]) >>> world = set([1,3,5,7,8]) >>> hello & world set([1, 5])
Python: intersection of lists/sets
def boolean_search_and(self, text): results = [] and_tokens = self.tokenize(text) tokencount = len(and_tokens) term1 = and_tokens[0] print ' term 1:', term1 term2 = and_tokens[1] print ' term 2:', term2 #for term in and_tokens: if term1 in self._inverted_index.keys(): resultlist1 = self._inverted_index[term1] print resultlist1 if term2 in self._inverted_index.keys(): resultlist2 = self._inverted_index[term2] print resultlist2 #intersection of two sets casted into a list results = list(set(resultlist1) & set(resultlist2)) print 'results:', results return str(results) This code works great for two tokens, ex: text= "Hello World" and so, tokens = ['hello', 'world']. I want to generalize it for multiple tokens, so the text can be a sentence, or an entire text file. self._inverted_index is a dictionary that saves the tokens as keys and the values are the DocIDs in which the keys/tokens occur. hello -> [1,2,5,6] world -> [1,3,5,7,8] result: hello AND world -> [1,5] I want to achieve result for: say, (((hello AND computer) AND science) AND world) I am working on making this work for multiple words, not just two. I started working in python this mornin', so I'm unaware of a lot of features it has to offer. Any ideas?
[ "\nI want to generalize it for multiple\n tokens\n\ndef boolean_search_and_multi(self, text):\n and_tokens = self.tokenize(text)\n results = set(self._inverted_index[and_tokens[0]])\n for tok in and_tokens[1:]:\n results.intersection_update(self._inverted_index[tok])\n return list(results)\n\n",...
[ 1, 0 ]
[]
[]
[ "information_retrieval", "python" ]
stackoverflow_0003697772_information_retrieval_python.txt
Q: How can I get better error information with try/except in Python Consider this try/except block I use for checking error message stored in e. Try/Catch to get the e queryString = "SELECT * FROM benchmark WHERE NOC = 2" try: res = db.query(queryString) except SQLiteError, e: # `e` has the error info print `e` The e object here contains nothing more than the above string. When python reports an unhandled error, however, it shows a pretty detailed info as below: Traceback (most recent call last): File "fool.py", line 1, in open("abc.zyz", "r") IOError: [Errno 2] No such file or directory: 'abc.zyz' My question is, how can I get the information such as above (the file and the line number etc.)? Or, if e contains this info, how is it stored inside it? A: This will show the trace to the error. import traceback try: res = db.query(queryString) except SQLiteError, e: # `e` has the error info print `e` for tb in traceback.format_tb(sys.exc_info()[2]): print tb A: Like the first 2 answers, use traceback. Here is a more complete example. import traceback def foo(): raise RuntimeError('we have a problem') try: foo() except: traceback.print_exc() When you run it, you'll see Traceback (most recent call last): File "C:\0\tmp\x.py", line 6, in <module> foo() File "C:\0\tmp\x.py", line 3, in foo raise RuntimeError('we have a problem') RuntimeError: we have a problem A: See the traceback library. If you want to just pass errors up the chain instead of modifying them, you can just use raise within an except block, which will then act like the except block isn't there (aside from any conditional logic/side effects you may have done before the raise).
How can I get better error information with try/except in Python
Consider this try/except block I use for checking error message stored in e. Try/Catch to get the e queryString = "SELECT * FROM benchmark WHERE NOC = 2" try: res = db.query(queryString) except SQLiteError, e: # `e` has the error info print `e` The e object here contains nothing more than the above string. When python reports an unhandled error, however, it shows a pretty detailed info as below: Traceback (most recent call last): File "fool.py", line 1, in open("abc.zyz", "r") IOError: [Errno 2] No such file or directory: 'abc.zyz' My question is, how can I get the information such as above (the file and the line number etc.)? Or, if e contains this info, how is it stored inside it?
[ "This will show the trace to the error.\nimport traceback\n\ntry:\n res = db.query(queryString) \nexcept SQLiteError, e:\n # `e` has the error info \n print `e`\n for tb in traceback.format_tb(sys.exc_info()[2]):\n print tb\n\n", "Like the first 2 answers, use traceback. Here is a more complete...
[ 10, 3, 2 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0003697452_error_handling_python.txt
Q: Why is the Python script unreliable when run from rc.local on first boot? The script below works great when logged in as root and run from the command line, but when run at first boot using /etc/rc.local in Ubuntu 10.04, it fails about 25% of the time- the system root, mysql root and some mysql user passwords are set correctly, but one will fail with console log reporting standard mysql login error: "ERROR 1045 (28000): Access denied for user 'root' @ 'localhost' (using password: YES)" Is there something about running python scripts from init jobs that I should account for, such as an environment variable? #!/usr/bin/env python # Randomizes and outputs to files the system root and mysql user passwords files = ['/home/ubuntu/passwords','/opt/data1/alfresco/extensions/ extension/alfresco-global.properties','/opt/data/etc/mysql/ debian.cnf','/home/ubuntu/duncil'] userpasswords = {'root':'ROOTPASSWORD'} mysqlpasswords = {'root':'MYSQLPASSWORD','alfresco':'alfrescoPASSWORD','debian-sys- maint':'debian-sys-maintPASSWORD'} otherpasswords = ['OTHERPASSWORD'] log = '/var/log/firstrun' import random, string import crypt import re from subprocess import PIPE, Popen def getsalt(chars = string.letters + string.digits): # generate a random 2-character 'salt' return random.choice(chars) + random.choice(chars) def getpwd(chars = string.letters + string.digits, len = 12): retval = ""; for i in range(0, len): # generate 12 character alphanumeric password retval += random.choice(chars) return retval def replace_pass(filename): handle = open(filename, 'r') hbuf = handle.read() handle.close() for placeholder, password in pdict.iteritems(): hbuf = re.sub(placeholder, password, hbuf) try: # Output file handle = open(filename, 'w') handle.write(hbuf) handle.close() except: pass #logh.write('failed to update ' + filename + "\n") #logh.write('maybe you don\'t have permision to write to it?\n') logh = open(log, "a") logh.write("Starting...\n") # Generate passwords pdict = {} for user, placeholder in userpasswords.iteritems(): syspass = getpwd() Popen(['usermod', '--password', crypt.crypt(syspass, getsalt()), user]) logh.write(placeholder + ": User " + user + " --> " + syspass + "\n") pdict[placeholder] = syspass # Whats the MySQL Root password placeholder? mplace = mysqlpasswords['root'] for user, placeholder in mysqlpasswords.iteritems(): mpass = getpwd() if (("root" in mysqlpasswords) and (mysqlpasswords['root'] in pdict)): mrootpass = pdict[mysqlpasswords['root']] else: mrootpass = "" Popen(['mysql', '-uroot', "--password=" + mrootpass, "-e", "UPDATE user SET Password = PASSWORD('" + mpass + "') WHERE User = '" + user + "';FLUSH PRIVILEGES;","mysql"]) logh.write(placeholder + ": MySQL " + user + " --> " + mpass + "\n") pdict[placeholder] = mpass for placeholder in otherpasswords: opass = getpwd() logh.write(placeholder + ": " + opass + "\n") pdict[placeholder] = opass # Update passwords for file in files: logh.write("Replacing placeholders in " + file + "\n") replace_pass(file) logh.write("Finished\n") logh.close A: Doesn't Popen execute asynchronously? It seems that during boot, the load is high and you are getting a race condition between setting the root password and using it to set the next password (next command). Try p = Popen(['mysql', '-uroot', "--password=" + mrootpass, "-e", "UPDATE user SET Password = PASSWORD('" + mpass + "') WHERE User = '" + user + "';FLUSH PRIVILEGES;","mysql"]) p.wait() and see if that does it.
Why is the Python script unreliable when run from rc.local on first boot?
The script below works great when logged in as root and run from the command line, but when run at first boot using /etc/rc.local in Ubuntu 10.04, it fails about 25% of the time- the system root, mysql root and some mysql user passwords are set correctly, but one will fail with console log reporting standard mysql login error: "ERROR 1045 (28000): Access denied for user 'root' @ 'localhost' (using password: YES)" Is there something about running python scripts from init jobs that I should account for, such as an environment variable? #!/usr/bin/env python # Randomizes and outputs to files the system root and mysql user passwords files = ['/home/ubuntu/passwords','/opt/data1/alfresco/extensions/ extension/alfresco-global.properties','/opt/data/etc/mysql/ debian.cnf','/home/ubuntu/duncil'] userpasswords = {'root':'ROOTPASSWORD'} mysqlpasswords = {'root':'MYSQLPASSWORD','alfresco':'alfrescoPASSWORD','debian-sys- maint':'debian-sys-maintPASSWORD'} otherpasswords = ['OTHERPASSWORD'] log = '/var/log/firstrun' import random, string import crypt import re from subprocess import PIPE, Popen def getsalt(chars = string.letters + string.digits): # generate a random 2-character 'salt' return random.choice(chars) + random.choice(chars) def getpwd(chars = string.letters + string.digits, len = 12): retval = ""; for i in range(0, len): # generate 12 character alphanumeric password retval += random.choice(chars) return retval def replace_pass(filename): handle = open(filename, 'r') hbuf = handle.read() handle.close() for placeholder, password in pdict.iteritems(): hbuf = re.sub(placeholder, password, hbuf) try: # Output file handle = open(filename, 'w') handle.write(hbuf) handle.close() except: pass #logh.write('failed to update ' + filename + "\n") #logh.write('maybe you don\'t have permision to write to it?\n') logh = open(log, "a") logh.write("Starting...\n") # Generate passwords pdict = {} for user, placeholder in userpasswords.iteritems(): syspass = getpwd() Popen(['usermod', '--password', crypt.crypt(syspass, getsalt()), user]) logh.write(placeholder + ": User " + user + " --> " + syspass + "\n") pdict[placeholder] = syspass # Whats the MySQL Root password placeholder? mplace = mysqlpasswords['root'] for user, placeholder in mysqlpasswords.iteritems(): mpass = getpwd() if (("root" in mysqlpasswords) and (mysqlpasswords['root'] in pdict)): mrootpass = pdict[mysqlpasswords['root']] else: mrootpass = "" Popen(['mysql', '-uroot', "--password=" + mrootpass, "-e", "UPDATE user SET Password = PASSWORD('" + mpass + "') WHERE User = '" + user + "';FLUSH PRIVILEGES;","mysql"]) logh.write(placeholder + ": MySQL " + user + " --> " + mpass + "\n") pdict[placeholder] = mpass for placeholder in otherpasswords: opass = getpwd() logh.write(placeholder + ": " + opass + "\n") pdict[placeholder] = opass # Update passwords for file in files: logh.write("Replacing placeholders in " + file + "\n") replace_pass(file) logh.write("Finished\n") logh.close
[ "Doesn't Popen execute asynchronously?\nIt seems that during boot, the load is high and you are getting a race condition between setting the root password and using it to set the next password (next command).\nTry\np = Popen(['mysql', '-uroot', \"--password=\" + mrootpass, \"-e\", \"UPDATE user SET Password = PASSW...
[ 2 ]
[]
[]
[ "boot", "python" ]
stackoverflow_0003698010_boot_python.txt
Q: Using webpy's web.template.render() with a relative path when deployed on Apache Using webpy, what's the proper way to reference the templates directory for web.template.render() so that it works on both the webpy development web server and on Apache? The following code works using the development server but not when running on my Apache server. import web urls = ( '/', 'index', ) class index: def GET(self): render = web.template.render('templates/') return render.index(self) I know the problem is that web.template.render('templates/') is the problem, because the relative path is no longer valid when Apache runs from C:\Program Files\Apache Software Foundation\Apache2.2. My templates directory is within my project folder. What I don't want to do is use an absolute path, because I'd like to be able to move my project files around without having to tinker with the code to keep it working. A: If you're using mod_wsgi, the easiest solution is to set the home= option appropriately, Alternatively, you can get the module's path and combine that with the template, i.e. os.path.join(os.path.dirname(__file__), 'templates/') Put it in a function if you need it often. Be aware that if you put it in a separate module, this module needs to be in the same folder as the templates directory or you'll end up with the wrong directory again. In case you want to put it in a system wide package, you can find out the callers directory easily: def abspath(path): frame = sys._getframe(1) base = os.path.dirname(frame.f_globals['__file__']) return os.path.join(base, path)
Using webpy's web.template.render() with a relative path when deployed on Apache
Using webpy, what's the proper way to reference the templates directory for web.template.render() so that it works on both the webpy development web server and on Apache? The following code works using the development server but not when running on my Apache server. import web urls = ( '/', 'index', ) class index: def GET(self): render = web.template.render('templates/') return render.index(self) I know the problem is that web.template.render('templates/') is the problem, because the relative path is no longer valid when Apache runs from C:\Program Files\Apache Software Foundation\Apache2.2. My templates directory is within my project folder. What I don't want to do is use an absolute path, because I'd like to be able to move my project files around without having to tinker with the code to keep it working.
[ "If you're using mod_wsgi, the easiest solution is to set the home= option appropriately,\nAlternatively, you can get the module's path and combine that with the template, i.e.\nos.path.join(os.path.dirname(__file__), 'templates/')\n\nPut it in a function if you need it often. Be aware that if you put it in a separ...
[ 6 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0003697704_python_web.py.txt
Q: problems using observer pattern in django I'm working on a website where I sell products (one class Sale, one class Product). Whenever I sell a product, I want to save that action in a History table and I have decided to use the observer pattern to do this. That is: my class Sales is the subject and the History class is the observer, whenever I call the save_sale() method of the Sales class I will notify the observers. (I've decided to use this pattern because later I'll also send an email, notify the admin, etc.) This is my subject class (the Sales class extends from this) class Subject: _observers = [] def attach(self, observer): if not observer in self._observers: self._observers.append(observer) def detach(self, observer): try: self._observers.remove(observer) except ValueError: pass def notify(self,**kargs): for observer in self._observers: observer.update(self,**kargs) on the view I do something like this sale = Sale() sale.user = request.user sale.product = product h = History() #here I create the observer sale.attach(h) #here I add the observer to the subject class sale.save_sale() #inside this class I will call the notify() method This is the update method on History def update(self,subject,**kargs): self.action = "sale" self.username = subject.user.username self.total = subject.product.total self.save(force_insert=True) It works fine the first time, but when I try to make another sale, I get an error saying I can't insert into History because of a primary key constraint. My guess is that when I call the view the second time, the first observer is still in the Subject class, and now I have two history observers listening to the Sales, but I'm not sure if that's the problem (gosh I miss the print_r from php). What am I doing wrong? When do I have to "attach" the observer? Or is there a better way of doing this? BTW: I'm using Django 1.1 and I don't have access to install any plugins. A: This may not be an acceptable answer since it's more architecture related, but have you considered using signals to notify the system of the change? It seems that you are trying to do exactly what signals were designed to do. Django signals have the same end-result functionality as Observer patterns. http://docs.djangoproject.com/en/1.1/topics/signals/ A: I think this is because _observers = [] acts like static shared field. So every instance of Subject changes the _observers instance and it has unwanted side effect. Initialize this variable in constructor: class Subject: def __init__(self): self._observers = [] A: @Andrew Sledge's answer indicates a good way of tackling this problem. I would like to suggest an alternate approach. I had a similar problem and started out using signals. They worked well but I found that my unit tests had become slower as the signals were called each time I loaded an instance of the associated class using a fixture. This added tens of seconds to the test run. There is a work around but I found it clumsy. I defined a custom test runner and disconnected my functions from the signals before loading fixtures. I reconnected them afterwards. Finally I decided to ditch signals altogether and overrode the appropriate save() methods of models instead. In my case whenever an Order is changed a row is automatically created in and OrderHistory table, among other things. In order to do this I added a function to create an instance of OrderHistory and called it from within the Order.save() method. this also made it possible to test the save() and the function separately. Take a look at this SO question. It has a discussion about when to override save() versus when to use signals. A: Thank you all for your answers, reading about signals gave me another perspective but i dont want to use them because of learning purposes (i wanted to use the observer pattern in web development :P) In the end, i solved doing something like this: class Sales(models.Model,Subject): ... def __init__(self): self._observers = [] #reset observers self.attach(History()) #attach a History Observer ... def save(self): super(Sales,self).save() self.notify() # notify all observers now every time i call the save(), the observers will be notified and if i need it, i could add or delete an observer what do you think? is this a good way to solve it?
problems using observer pattern in django
I'm working on a website where I sell products (one class Sale, one class Product). Whenever I sell a product, I want to save that action in a History table and I have decided to use the observer pattern to do this. That is: my class Sales is the subject and the History class is the observer, whenever I call the save_sale() method of the Sales class I will notify the observers. (I've decided to use this pattern because later I'll also send an email, notify the admin, etc.) This is my subject class (the Sales class extends from this) class Subject: _observers = [] def attach(self, observer): if not observer in self._observers: self._observers.append(observer) def detach(self, observer): try: self._observers.remove(observer) except ValueError: pass def notify(self,**kargs): for observer in self._observers: observer.update(self,**kargs) on the view I do something like this sale = Sale() sale.user = request.user sale.product = product h = History() #here I create the observer sale.attach(h) #here I add the observer to the subject class sale.save_sale() #inside this class I will call the notify() method This is the update method on History def update(self,subject,**kargs): self.action = "sale" self.username = subject.user.username self.total = subject.product.total self.save(force_insert=True) It works fine the first time, but when I try to make another sale, I get an error saying I can't insert into History because of a primary key constraint. My guess is that when I call the view the second time, the first observer is still in the Subject class, and now I have two history observers listening to the Sales, but I'm not sure if that's the problem (gosh I miss the print_r from php). What am I doing wrong? When do I have to "attach" the observer? Or is there a better way of doing this? BTW: I'm using Django 1.1 and I don't have access to install any plugins.
[ "This may not be an acceptable answer since it's more architecture related, but have you considered using signals to notify the system of the change? It seems that you are trying to do exactly what signals were designed to do. Django signals have the same end-result functionality as Observer patterns.\nhttp://doc...
[ 9, 4, 1, 1 ]
[]
[]
[ "design_patterns", "django", "observer_pattern", "python" ]
stackoverflow_0003676517_design_patterns_django_observer_pattern_python.txt
Q: Python multiprocessing handling sessions I have a script receiveing data from a socket, each data contains a sessionid that a have to keep track of, foreach incomming message, i'm opening a new process with the multiprocessing module, i having trouble to figure out a way to keep track of the new incoming messages having the same sessionid. For example: 100100|Hello -- (open a new process) 100100|Hello back at you (proccess replies) 100101|Hello (open a new process) 100101|Hello back at you (new proccess replies) 100100|wasap? -- (open a new process) when a new message from sessionid 100100 comes... how could i sent it to the process that is handling those particular messages? until know the main process is opening a new process for each incomming message another process is writing data on the socket, but is giving me real trouble finding out a way to handle each session process and sending data to them... I need some guidance cause a never work with multiprocessing before... Thanks... A: To communicate with processes created suing multiprocessing you can use the classes Queue and Pipe (also from the multiprocessing module). Here is a short example of using a Queue to send a message to a process: from multiprocessing import Process, Queue def f(q): print 'f(), waiting...' print q.get() if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() q.put('Hello from main!') p.join() More informatin can be found in the Python docs. A: How about storing the processes in a dictionary? E.g. in pseudo code: def __init__(self): self.sessions = {} def handle(self, sessionid, data): proc = self.sessions.get(sessionid) if prod is None: proc = self.create_process() self.sessions[sessionid] = proc proc.handle(data) A: I am not sure about the requirement to open a separate process for every message received from the sockets. I guess, you have a reason for doing all that you have mentioned. My understanding is, you have written a server side socket that listens for client connection, accepts the client connection, receives the data and dispatch these data to various processes you have created to handle these messages. I am assuming that session id remains same for a client connection. Each client sends data tagged with it's session id. If this is the case, then you can solve easily by the fact that in unix - forks duplicate file / socket descriptors. when you launch a multiprocessing.Process(), you can pass it the socket descriptor. Ensure that you close the socket in parent process or the process in which you listen for client connections. This way each process will handle the connection and will receive only messages for the single client tagged with the same session id. I hope this answers your need.
Python multiprocessing handling sessions
I have a script receiveing data from a socket, each data contains a sessionid that a have to keep track of, foreach incomming message, i'm opening a new process with the multiprocessing module, i having trouble to figure out a way to keep track of the new incoming messages having the same sessionid. For example: 100100|Hello -- (open a new process) 100100|Hello back at you (proccess replies) 100101|Hello (open a new process) 100101|Hello back at you (new proccess replies) 100100|wasap? -- (open a new process) when a new message from sessionid 100100 comes... how could i sent it to the process that is handling those particular messages? until know the main process is opening a new process for each incomming message another process is writing data on the socket, but is giving me real trouble finding out a way to handle each session process and sending data to them... I need some guidance cause a never work with multiprocessing before... Thanks...
[ "To communicate with processes created suing multiprocessing you can use the classes Queue and Pipe (also from the multiprocessing module). Here is a short example of using a Queue to send a message to a process:\nfrom multiprocessing import Process, Queue\n\ndef f(q):\n print 'f(), waiting...'\n print q.get(...
[ 1, 0, 0 ]
[]
[]
[ "multiprocessing", "python", "queue", "session" ]
stackoverflow_0003698051_multiprocessing_python_queue_session.txt
Q: prefer windows or unix line ending for code? I writing code that should compiled and run on both Windows and unix like Linux. I know about difference between line endings, but question is which to prefer for my code? Does it matter? I want it to be consistent - say all my code uses LF only, or is it better CRLF only? Are there critaria for comparing? If it matters mostly I care for C++ and Python codes A: Use a version control system that's smart enough to ignore line-endings on check-in, and use the correct value for the platform on check-out. A: For the code itself, it does not matter. All reasonably modern editors and compilers handle both just as well (I presume you are not using notepad :-) ). Just use the line ending of the main development platform. A: IME the easiest is to use *NIX line endings. Windows' compilers and IDEs can deal with it fine and it is native for *NIX tools. Using DOS line endings creates, if not problems, inconveniences with some (even the more popular) text editors on *NIX. You often get ugly '^M' at the end of the line then and you have to explicitly convert or tell your editor it has DOS line endings.
prefer windows or unix line ending for code?
I writing code that should compiled and run on both Windows and unix like Linux. I know about difference between line endings, but question is which to prefer for my code? Does it matter? I want it to be consistent - say all my code uses LF only, or is it better CRLF only? Are there critaria for comparing? If it matters mostly I care for C++ and Python codes
[ "Use a version control system that's smart enough to ignore line-endings on check-in, and use the correct value for the platform on check-out.\n", "For the code itself, it does not matter. All reasonably modern editors and compilers handle both just as well (I presume you are not using notepad :-) ). Just use the...
[ 9, 2, 2 ]
[]
[]
[ "c++", "line_endings", "multiplatform", "python" ]
stackoverflow_0003698084_c++_line_endings_multiplatform_python.txt
Q: Python, Django, how to use getattr (or other method) to call object that has multiple attributes? After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use getattr to call functions such as the one below in a generic manner: the way I do it that works (non-generic manner): from django.db.models import get_model mymodel = get_model('appname', 'modelname') dbobject = mymodel.objects.all() one of my attempts create this in a generic manner, still not working, it does return something back but its not the proper object type so that i can get the data from it (its a database call for django) ret = getattr(mymodel,'objects') dbobject = getattr(ret,'all') A: You forgot to call the result. dbobject = mymodel.objects.all() Accesses the method mymodel.objects.all and then calls it. ret = getattr(mymodel,'objects') self.dbobject = getattr(ret,'all') accesses the method mymodel.objects.all but does not call it. All you need is to change the last line to: self.dbobject = getattr(ret,'all')() A: You will need to call the attribute if it's a function, e.g. ret = getattr(mymodel,'objects') all = getattr(ret,'all') self.dbobject = all()
Python, Django, how to use getattr (or other method) to call object that has multiple attributes?
After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use getattr to call functions such as the one below in a generic manner: the way I do it that works (non-generic manner): from django.db.models import get_model mymodel = get_model('appname', 'modelname') dbobject = mymodel.objects.all() one of my attempts create this in a generic manner, still not working, it does return something back but its not the proper object type so that i can get the data from it (its a database call for django) ret = getattr(mymodel,'objects') dbobject = getattr(ret,'all')
[ "You forgot to call the result.\ndbobject = mymodel.objects.all()\n\nAccesses the method mymodel.objects.all and then calls it.\nret = getattr(mymodel,'objects')\nself.dbobject = getattr(ret,'all')\n\naccesses the method mymodel.objects.all but does not call it.\nAll you need is to change the last line to:\nself.db...
[ 14, 2 ]
[]
[]
[ "code_reuse", "django", "getattr", "object", "python" ]
stackoverflow_0003698845_code_reuse_django_getattr_object_python.txt
Q: Handling unicode data in XMLRPC I have to migrate data to OpenERP through XMLRPC by using TerminatOOOR. I send a name with value "Rotule right Aurélia". In Python the name with be encoded with value : 'Rotule right Aur\xc3\xa9lia ' But in TerminatOOOR (xmlrpc client) the data is encoded with value 'Rotule middle Aur\357\277\275lia' So in the server side, the data value is not decoded correctly and I get bad data. The terminateOOOR is a ruby plugin for Kettle ( Java product) and I guess it should encode data by utf-8. I just don't know why it happens like this. Any help? A: This issue comes from Kettle. My program is using Kettle to get an Excel file, get the active sheet and transfer the data in that sheet to TerminateOOOR for further handling. At the phase of reading data from Excel file, Kettle can not recognize the encoding then it gives bad data to TerminateOOOR. My work around solution is manually exporting excel to csv before giving data to TerminateOOOR. By doing this, I don't use the feature to mapping excel column name a variable name (used by kettle). A: first off, whenever you deal with text (and all text is bound to contain some non-US-ASCII character sooner or later), you'll be much happier doing that in Python 3.x instead of in the 2.x series. if Py3 is not an option, try to always use from __future__ import unicode_literals (available in Python 2.6 and 2.7). basically, when you send text or any other data over the wire, that will only happen in the form of bytes (octets of bits), so it will have to be encoded at some point. try to find out exactly where that encoding takes place in your tool chain; if necessary, use a debugging tool (or deploy print( repr( x ) ) statements) to look into relevant variables. the other software you mention is presumably written in PHP, a language which is known to have issues with unicode. you say that 'it should encode the data by utf-8', but on the other hand, when the receiving end sees the data of an incoming RPC request, that data should already be in utf-8. it would have to be decoded to obtain unicode again.
Handling unicode data in XMLRPC
I have to migrate data to OpenERP through XMLRPC by using TerminatOOOR. I send a name with value "Rotule right Aurélia". In Python the name with be encoded with value : 'Rotule right Aur\xc3\xa9lia ' But in TerminatOOOR (xmlrpc client) the data is encoded with value 'Rotule middle Aur\357\277\275lia' So in the server side, the data value is not decoded correctly and I get bad data. The terminateOOOR is a ruby plugin for Kettle ( Java product) and I guess it should encode data by utf-8. I just don't know why it happens like this. Any help?
[ "This issue comes from Kettle.\nMy program is using Kettle to get an Excel file, get the active sheet and transfer the data in that sheet to TerminateOOOR for further handling.\nAt the phase of reading data from Excel file, Kettle can not recognize the encoding then it gives bad data to TerminateOOOR. \nMy work ar...
[ 1, 0 ]
[]
[]
[ "python", "ruby", "unicode", "xml_rpc" ]
stackoverflow_0003651031_python_ruby_unicode_xml_rpc.txt
Q: google code + temp server? We are starting a new project to develop a website using django. We have created a project on google code. We would like to be able to occasionally show the progress of the site to some people, without having to purchase a real server. We are all modifying the project through eclipse and SVN. What's the best way to create a runserver type thing but allow othes to access over the internet temporarily? thanks A: One way is to run Django development server to bind on multiple interfaces: python manage.py runserver 0.0.0.0:8000 Or specify a IP of the interface to bind to, for example this would only listen on the interface who's IP is 192.168.1.100: python manage.py runserver 192.168.1.100:8000 But Django development server is single threaded and thus will not work good with concurrent requests. I would advise setting up a development preview on shared hosting or something, or even locally, with a proper web server (such as Apache or ngnix). If you do it locally just portforward your traffic from router to your local installation, if you don't have static IP you can use a service such as DynDns or No-ip. This subject has been covered several times on Stackoverflow, feel free to search for other ideas.
google code + temp server?
We are starting a new project to develop a website using django. We have created a project on google code. We would like to be able to occasionally show the progress of the site to some people, without having to purchase a real server. We are all modifying the project through eclipse and SVN. What's the best way to create a runserver type thing but allow othes to access over the internet temporarily? thanks
[ "One way is to run Django development server to bind on multiple interfaces:\npython manage.py runserver 0.0.0.0:8000 \n\nOr specify a IP of the interface to bind to, for example this would only listen on the interface who's IP is 192.168.1.100:\npython manage.py runserver 192.168.1.100:8000 \n\nBut Django developm...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003698964_django_python.txt
Q: Retrieving netmask for interfaces with multiple IP addresses using Python? I need to list the available network interfaces and their IP addresses and corresponding netmasks using Python in a Linux environment. I can get the interfaces and the IP addresses of each interface using ioctl and SIOCGIFCONF as outlined here, but I'm at loss when it comes to determining the netmask when there are multiple IP address on an interface. I can get the netmask of the primary IP address of an interface as suggested in Retrieving network mask in Python: import socket import fcntl import struct SIOCGIFNETMASK = 0x891b def get_network_mask(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) netmask = fcntl.ioctl(s, SIOCGIFNETMASK, struct.pack('256s', ifname))[20:24] return socket.inet_ntoa(netmask) >>> get_network_mask('eth0') '255.255.255.0' However, this won't work if I have multiple IP addresses with different netmasks on the same interface, as follows: $ ip addr show eth0 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000 inet 192.168.1.1/16 brd 192.168.255.255 scope global eth0 inet 172.16.0.123/24 scope global eth0 In this case I'll only be able to retrieve one of the netmasks using the above function. Is there a way to retrieve the netmasks for all addresses, except by parsing the output from ip addr show or ifconfig? A: Technically what "ip addr sh" does is use the netlink library to interrogate (and optionally monitor) the kernel network interfaces / routing tables. You might be able to do this in python, but I strongly recommend parsing the output of "/sbin/ip addr sh" This is because Using the rtnetlink library is complicated You don't care about performance - network interfaces don't change often enough that you care (and in any case you can monitor them using "ip monitor")
Retrieving netmask for interfaces with multiple IP addresses using Python?
I need to list the available network interfaces and their IP addresses and corresponding netmasks using Python in a Linux environment. I can get the interfaces and the IP addresses of each interface using ioctl and SIOCGIFCONF as outlined here, but I'm at loss when it comes to determining the netmask when there are multiple IP address on an interface. I can get the netmask of the primary IP address of an interface as suggested in Retrieving network mask in Python: import socket import fcntl import struct SIOCGIFNETMASK = 0x891b def get_network_mask(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) netmask = fcntl.ioctl(s, SIOCGIFNETMASK, struct.pack('256s', ifname))[20:24] return socket.inet_ntoa(netmask) >>> get_network_mask('eth0') '255.255.255.0' However, this won't work if I have multiple IP addresses with different netmasks on the same interface, as follows: $ ip addr show eth0 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000 inet 192.168.1.1/16 brd 192.168.255.255 scope global eth0 inet 172.16.0.123/24 scope global eth0 In this case I'll only be able to retrieve one of the netmasks using the above function. Is there a way to retrieve the netmasks for all addresses, except by parsing the output from ip addr show or ifconfig?
[ "Technically what \"ip addr sh\" does is use the netlink library to interrogate (and optionally monitor) the kernel network interfaces / routing tables.\nYou might be able to do this in python, but I strongly recommend parsing the output of \"/sbin/ip addr sh\"\nThis is because\n\nUsing the rtnetlink library is com...
[ 2 ]
[]
[]
[ "linux", "networking", "python" ]
stackoverflow_0003698901_linux_networking_python.txt
Q: Django Celery implementation - OSError : [Errno 38] Function not implemented I installed django-celery and I tried to start up the worker server but I get an OSError that a function isn't implemented. I'm running CentOS release 5.4 (Final) on a VPS: . broker -> amqp://guest@localhost:5672/ . queues -> . celery -> exchange:celery (direct) binding:celery . concurrency -> 4 . loader -> djcelery.loaders.DjangoLoader . logfile -> [stderr]@WARNING . events -> OFF . beat -> OFF [2010-07-22 17:10:01,364: WARNING/MainProcess] Traceback (most recent call last): [2010-07-22 17:10:01,364: WARNING/MainProcess] File "manage.py", line 11, in <module> [2010-07-22 17:10:01,364: WARNING/MainProcess] execute_manager(settings) [2010-07-22 17:10:01,364: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager [2010-07-22 17:10:01,364: WARNING/MainProcess] utility.execute() [2010-07-22 17:10:01,364: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute [2010-07-22 17:10:01,365: WARNING/MainProcess] self.fetch_command(subcommand).run_from_argv(self.argv) [2010-07-22 17:10:01,365: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 191, in run_from_argv [2010-07-22 17:10:01,365: WARNING/MainProcess] self.execute(*args, **options.__dict__) [2010-07-22 17:10:01,365: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 218, in execute [2010-07-22 17:10:01,365: WARNING/MainProcess] output = self.handle(*args, **options) [2010-07-22 17:10:01,365: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django_celery-2.0.0-py2.6.egg/djcelery/management/commands/celeryd.py", line 22, in handle [2010-07-22 17:10:01,366: WARNING/MainProcess] run_worker(**options) [2010-07-22 17:10:01,366: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/bin/celeryd.py", line 385, in run_worker [2010-07-22 17:10:01,366: WARNING/MainProcess] return Worker(**options).run() [2010-07-22 17:10:01,366: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/bin/celeryd.py", line 218, in run [2010-07-22 17:10:01,366: WARNING/MainProcess] self.run_worker() [2010-07-22 17:10:01,366: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/bin/celeryd.py", line 312, in run_worker [2010-07-22 17:10:01,367: WARNING/MainProcess] worker.start() [2010-07-22 17:10:01,367: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/worker/__init__.py", line 206, in start [2010-07-22 17:10:01,367: WARNING/MainProcess] component.start() [2010-07-22 17:10:01,367: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/concurrency/processes/__init__.py", line 54, in start [2010-07-22 17:10:01,367: WARNING/MainProcess] maxtasksperchild=self.maxtasksperchild) [2010-07-22 17:10:01,367: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/concurrency/processes/pool.py", line 448, in __init__ [2010-07-22 17:10:01,368: WARNING/MainProcess] self._setup_queues() [2010-07-22 17:10:01,368: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/concurrency/processes/pool.py", line 564, in _setup_queues [2010-07-22 17:10:01,368: WARNING/MainProcess] self._inqueue = SimpleQueue() [2010-07-22 17:10:01,368: WARNING/MainProcess] File "/usr/local/lib/python2.6/multiprocessing/queues.py", line 315, in __init__ [2010-07-22 17:10:01,368: WARNING/MainProcess] self._rlock = Lock() [2010-07-22 17:10:01,368: WARNING/MainProcess] File "/usr/local/lib/python2.6/multiprocessing/synchronize.py", line 117, in __init__ [2010-07-22 17:10:01,369: WARNING/MainProcess] SemLock.__init__(self, SEMAPHORE, 1, 1) [2010-07-22 17:10:01,369: WARNING/MainProcess] File "/usr/local/lib/python2.6/multiprocessing/synchronize.py", line 49, in __init__ [2010-07-22 17:10:01,369: WARNING/MainProcess] sl = self._semlock = _multiprocessing.SemLock(kind, value, maxvalue) [2010-07-22 17:10:01,369: WARNING/MainProcess] OSError [2010-07-22 17:10:01,369: WARNING/MainProcess] : [2010-07-22 17:10:01,369: WARNING/MainProcess] [Errno 38] Function not implemented Am I just totally screwed or is there an easy way to resolve this? A: same issue on ubuntu 10, even after full rights on shmem are given - problem still here... UP- finally done, /dev/shm was not mounted. so add shm to fstab mount shm set full 777 permissions on /dev/shm
Django Celery implementation - OSError : [Errno 38] Function not implemented
I installed django-celery and I tried to start up the worker server but I get an OSError that a function isn't implemented. I'm running CentOS release 5.4 (Final) on a VPS: . broker -> amqp://guest@localhost:5672/ . queues -> . celery -> exchange:celery (direct) binding:celery . concurrency -> 4 . loader -> djcelery.loaders.DjangoLoader . logfile -> [stderr]@WARNING . events -> OFF . beat -> OFF [2010-07-22 17:10:01,364: WARNING/MainProcess] Traceback (most recent call last): [2010-07-22 17:10:01,364: WARNING/MainProcess] File "manage.py", line 11, in <module> [2010-07-22 17:10:01,364: WARNING/MainProcess] execute_manager(settings) [2010-07-22 17:10:01,364: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager [2010-07-22 17:10:01,364: WARNING/MainProcess] utility.execute() [2010-07-22 17:10:01,364: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute [2010-07-22 17:10:01,365: WARNING/MainProcess] self.fetch_command(subcommand).run_from_argv(self.argv) [2010-07-22 17:10:01,365: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 191, in run_from_argv [2010-07-22 17:10:01,365: WARNING/MainProcess] self.execute(*args, **options.__dict__) [2010-07-22 17:10:01,365: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 218, in execute [2010-07-22 17:10:01,365: WARNING/MainProcess] output = self.handle(*args, **options) [2010-07-22 17:10:01,365: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/django_celery-2.0.0-py2.6.egg/djcelery/management/commands/celeryd.py", line 22, in handle [2010-07-22 17:10:01,366: WARNING/MainProcess] run_worker(**options) [2010-07-22 17:10:01,366: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/bin/celeryd.py", line 385, in run_worker [2010-07-22 17:10:01,366: WARNING/MainProcess] return Worker(**options).run() [2010-07-22 17:10:01,366: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/bin/celeryd.py", line 218, in run [2010-07-22 17:10:01,366: WARNING/MainProcess] self.run_worker() [2010-07-22 17:10:01,366: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/bin/celeryd.py", line 312, in run_worker [2010-07-22 17:10:01,367: WARNING/MainProcess] worker.start() [2010-07-22 17:10:01,367: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/worker/__init__.py", line 206, in start [2010-07-22 17:10:01,367: WARNING/MainProcess] component.start() [2010-07-22 17:10:01,367: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/concurrency/processes/__init__.py", line 54, in start [2010-07-22 17:10:01,367: WARNING/MainProcess] maxtasksperchild=self.maxtasksperchild) [2010-07-22 17:10:01,367: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/concurrency/processes/pool.py", line 448, in __init__ [2010-07-22 17:10:01,368: WARNING/MainProcess] self._setup_queues() [2010-07-22 17:10:01,368: WARNING/MainProcess] File "/usr/local/lib/python2.6/site-packages/celery-2.0.1-py2.6.egg/celery/concurrency/processes/pool.py", line 564, in _setup_queues [2010-07-22 17:10:01,368: WARNING/MainProcess] self._inqueue = SimpleQueue() [2010-07-22 17:10:01,368: WARNING/MainProcess] File "/usr/local/lib/python2.6/multiprocessing/queues.py", line 315, in __init__ [2010-07-22 17:10:01,368: WARNING/MainProcess] self._rlock = Lock() [2010-07-22 17:10:01,368: WARNING/MainProcess] File "/usr/local/lib/python2.6/multiprocessing/synchronize.py", line 117, in __init__ [2010-07-22 17:10:01,369: WARNING/MainProcess] SemLock.__init__(self, SEMAPHORE, 1, 1) [2010-07-22 17:10:01,369: WARNING/MainProcess] File "/usr/local/lib/python2.6/multiprocessing/synchronize.py", line 49, in __init__ [2010-07-22 17:10:01,369: WARNING/MainProcess] sl = self._semlock = _multiprocessing.SemLock(kind, value, maxvalue) [2010-07-22 17:10:01,369: WARNING/MainProcess] OSError [2010-07-22 17:10:01,369: WARNING/MainProcess] : [2010-07-22 17:10:01,369: WARNING/MainProcess] [Errno 38] Function not implemented Am I just totally screwed or is there an easy way to resolve this?
[ "same issue on ubuntu 10, even after full rights on shmem are given - problem still here...\nUP- finally done, /dev/shm was not mounted. so \nadd shm to fstab\nmount shm\nset full 777 permissions on /dev/shm\n" ]
[ 13 ]
[]
[]
[ "celery", "celery_task", "django", "python" ]
stackoverflow_0003314031_celery_celery_task_django_python.txt
Q: pretty printer with Python? I have a list of labels, and data as follows. ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort'] [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High'] I need to print them into console. And for this, I'm iterating over the list, and print out each element with a tab ('\t'). But, unfortunately, the result is not so pretty. number of data 1 and number of column 7 id Version chip_name xversion device opt_param place_effort 1 1.0 virtex2 xilinx11.5 xc5vlx50 Speed High The string length of label and data is quite variable, and it's not aligned well. Is there any solution to this problem with Python? ADDED Hepled by Mike DeSimone's answer, I could make the pretty printer that I can use for my purposes. The valueResults are a list of duple. labels = queryResult.names valueResults = queryResult.result # get the maximum width allData = valueResults allData.insert(0,labels) transpose = zip(*valueResults) # remove the sequence as a parameter #print transpose for value in transpose: # value is integer/float/unicode/str, so make it length of str newValue = [len(str(i)) for i in value] columnWidth = max(newValue) columnWidths.append(columnWidth) dividers.append('-' * columnWidth) dblDividers.append('=' * columnWidth) label = value[0] paddedLabels.append(label.center(columnWidth)) paddedString = "" for values in valueResults[1:]: paddedValue = [] for i, value in enumerate(values): svalue = str(value) columnWidth = columnWidths[i] paddedValue.append(svalue.center(columnWidth)) paddedString += '| ' + ' | '.join(paddedValue) + ' |' + '\n' string += '+-' + '-+-'.join(dividers) + '-+' + '\n' string += '| ' + ' | '.join(paddedLabels) + ' |' + '\n' string += '+=' + '=+='.join(dblDividers) + '=+' + '\n' string += paddedString string += '+-' + '-+-'.join(dividers) + '-+' + '\n' And this is the result. +----+---------+-----------+------------+----------+-----------+--------------+ | id | Version | chip_name | xversion | device | opt_param | place_effort | +====+=========+===========+============+==========+===========+==============+ | 1 | 1.0 | virtex2 | xilinx11.5 | xc5vlx50 | Speed | High | | 2 | 1.0 | virtex2 | xilinx11.5 | xc5vlx50 | Speed | High | +----+---------+-----------+------------+----------+-----------+--------------+ Thanks for the help. A: Use ljust to stuff the contents before they are printed out. import sys def maxwidth(table, index): """Get the maximum width of the given column index""" return max([len(str(row[index])) for row in table]) def pprint_table(table): colpad = [] for i in range(len(table[0])): colpad.append(maxwidth(table, i)) for row in table: print str(row[0]).ljust(colpad[0] + 1), for i in range(1, len(row)): col = str(row[i]).rjust(colpad[i] + 2) print "", col, print "" a = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort'] b = [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High'] # Put it in the table c = [a, b] pprint_table(c) output: id Version chip_name xversion device opt_param place_effort 1 1.0 virtex2 xilinx11.5 xc5vlx50 Speed High A: Something like this: labels = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort'] values = [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High'] paddedLabels = [] paddedValues = [] for label, value in zip(labels, values): value = str(value) columnWidth = max(len(label), len(value)) paddedLabels.append(label.center(columnWidth)) paddedValues.append(value.center(columnWidth)) print ' '.join(paddedLabels) print ' '.join(paddedValues) Output: id Version chip_name xversion device opt_param place_effort 1 1.0 virtex2 xilinx11.5 xc5vlx50 Speed High If you want to get fancy, make it reStructuredText-ready: labels = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort'] values = [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High'] paddedLabels = [] paddedValues = [] dividers = [] dblDividers = [] for label, value in zip(labels, values): value = str(value) columnWidth = max(len(label), len(value)) paddedLabels.append(label.center(columnWidth)) paddedValues.append(value.center(columnWidth)) dividers.append('-' * columnWidth) dblDividers.append('=' * columnWidth) print '+-' + '-+-'.join(dividers) + '-+' print '| ' + ' | '.join(paddedLabels) + ' |' print '+=' + '=+='.join(dblDividers) + '=+' print '| ' + ' | '.join(paddedValues) + ' |' print '+-' + '-+-'.join(dividers) + '-+' Output: +----+---------+-----------+------------+----------+-----------+--------------+ | id | Version | chip_name | xversion | device | opt_param | place_effort | +====+=========+===========+============+==========+===========+==============+ | 1 | 1.0 | virtex2 | xilinx11.5 | xc5vlx50 | Speed | High | +----+---------+-----------+------------+----------+-----------+--------------+ A: you could try this >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print '{0:10} ==> {1:10d}'.format(name, phone) ... Jack ==> 4098 Dcab ==> 7678 Sjoerd ==> 4127 from http://docs.python.org/tutorial/inputoutput.html The integer after the : is the padding. or better yet >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' ... 'Dcab: {0[Dcab]:d}'.format(table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 A: You can use ready solution: : prettytable A simple Python library for easily displaying tabular data in a visually appealing ASCII table format Other solutions, see my similar questions other answers: How to extend pretty print module to tables? A: Another solution is not to use tab at all, and uses spaces to adjust column width, also no need of manually padding, as '%Ns' string formatting comes handy e.g. header = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort'] rows = [[1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']] def print_row(row): column_width=12 format_str = ("%-"+str(column_width)+"s")*len(row) print format_str%tuple(row) print_row(header) for row in rows: print_row(row) Output: id Version chip_name xversion device opt_param place_effort 1 1.0 virtex2 xilinx11.5 xc5vlx50 Speed High A: For a quick solution, If ln is the list containing all these lists, for l in ln: print "\t".join([str(x).ljust(10) for x in l]) will print columns seperated by tab and left-justified. Increase the value inside ljust if it isn't pretty yet.
pretty printer with Python?
I have a list of labels, and data as follows. ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort'] [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High'] I need to print them into console. And for this, I'm iterating over the list, and print out each element with a tab ('\t'). But, unfortunately, the result is not so pretty. number of data 1 and number of column 7 id Version chip_name xversion device opt_param place_effort 1 1.0 virtex2 xilinx11.5 xc5vlx50 Speed High The string length of label and data is quite variable, and it's not aligned well. Is there any solution to this problem with Python? ADDED Hepled by Mike DeSimone's answer, I could make the pretty printer that I can use for my purposes. The valueResults are a list of duple. labels = queryResult.names valueResults = queryResult.result # get the maximum width allData = valueResults allData.insert(0,labels) transpose = zip(*valueResults) # remove the sequence as a parameter #print transpose for value in transpose: # value is integer/float/unicode/str, so make it length of str newValue = [len(str(i)) for i in value] columnWidth = max(newValue) columnWidths.append(columnWidth) dividers.append('-' * columnWidth) dblDividers.append('=' * columnWidth) label = value[0] paddedLabels.append(label.center(columnWidth)) paddedString = "" for values in valueResults[1:]: paddedValue = [] for i, value in enumerate(values): svalue = str(value) columnWidth = columnWidths[i] paddedValue.append(svalue.center(columnWidth)) paddedString += '| ' + ' | '.join(paddedValue) + ' |' + '\n' string += '+-' + '-+-'.join(dividers) + '-+' + '\n' string += '| ' + ' | '.join(paddedLabels) + ' |' + '\n' string += '+=' + '=+='.join(dblDividers) + '=+' + '\n' string += paddedString string += '+-' + '-+-'.join(dividers) + '-+' + '\n' And this is the result. +----+---------+-----------+------------+----------+-----------+--------------+ | id | Version | chip_name | xversion | device | opt_param | place_effort | +====+=========+===========+============+==========+===========+==============+ | 1 | 1.0 | virtex2 | xilinx11.5 | xc5vlx50 | Speed | High | | 2 | 1.0 | virtex2 | xilinx11.5 | xc5vlx50 | Speed | High | +----+---------+-----------+------------+----------+-----------+--------------+ Thanks for the help.
[ "Use ljust to stuff the contents before they are printed out.\nimport sys\n\ndef maxwidth(table, index):\n \"\"\"Get the maximum width of the given column index\"\"\"\n return max([len(str(row[index])) for row in table])\n\ndef pprint_table(table):\n colpad = []\n\n for i in range(len(table[0])):\n ...
[ 4, 3, 3, 2, 1, 0 ]
[]
[]
[ "pretty_print", "python" ]
stackoverflow_0003697763_pretty_print_python.txt
Q: Python bizarre class problem I have the following piece of code where I try to override a method: import Queue class PriorityQueue(Queue.PriorityQueue): def put(self, item): super(PriorityQueue, self).put((item.priority, item)) However, when I run it I get TypeError exception: super() argument 1 must be type, not classobj What is the problem? A: Queue.PriorityQueue is not a new-style class, and super only works with new-style classes. You must use import Queue class PriorityQueue(Queue.PriorityQueue): def put(self, item): Queue.PriorityQueue.put(self,(item.priority, item)) instead.
Python bizarre class problem
I have the following piece of code where I try to override a method: import Queue class PriorityQueue(Queue.PriorityQueue): def put(self, item): super(PriorityQueue, self).put((item.priority, item)) However, when I run it I get TypeError exception: super() argument 1 must be type, not classobj What is the problem?
[ "Queue.PriorityQueue is not a new-style class, and super only works with new-style classes. You must use\nimport Queue\nclass PriorityQueue(Queue.PriorityQueue):\n def put(self, item):\n Queue.PriorityQueue.put(self,(item.priority, item))\n\ninstead.\n" ]
[ 7 ]
[]
[]
[ "overriding", "python" ]
stackoverflow_0003699440_overriding_python.txt
Q: How can we call the CLI executables commands using Python How can we call the CLI executables commands using Python For example i have 3 linux servers which are at the remote location and i want to execute some commands on those servers like finding the version of the operating system or executing any other commands. So how can we do this in Python. I know this is done through some sort of web service (SOAP or REST) or API but i am not sure....... So could you all please guide me. A: Depends on how you want to design your software. You could do stand-alone scripts as servers listening for requests on specific ports, or you could use a webserver which runs python scripts so you just have to access a URL. REST is one option to implement the latter. You should then look for frameworks for REST development with python, or if it’s simple logic with not so many possible requests can do it on your own as a web-script. A: Maybe you should take a look at Pushy, which allows to connect to remote machines through SSH and make them execute various Python functions. I like using it because there are no server-side dependencies except the SSH server and a Python interpreter, and is therefore really easy to deploy. Edit: But if you wish to code this by yourself, i think SOAP is a nice solution, the SOAPpy module is great and very easy to use. A: You can use Twisted, It is easy create ssh clients or servers. Examples: http://twistedmatrix.com/documents/current/conch/examples/
How can we call the CLI executables commands using Python
How can we call the CLI executables commands using Python For example i have 3 linux servers which are at the remote location and i want to execute some commands on those servers like finding the version of the operating system or executing any other commands. So how can we do this in Python. I know this is done through some sort of web service (SOAP or REST) or API but i am not sure....... So could you all please guide me.
[ "Depends on how you want to design your software.\nYou could do stand-alone scripts as servers listening for requests on specific ports,\nor you could use a webserver which runs python scripts so you just have to access a URL.\nREST is one option to implement the latter.\nYou should then look for frameworks for RES...
[ 0, 0, 0 ]
[]
[]
[ "api", "django", "python", "soap", "web_services" ]
stackoverflow_0003699268_api_django_python_soap_web_services.txt
Q: How to shallow copy app engine model instance to create new instance? I want to implement a simple VersionedModel base model class for my app engine app. I'm looking for a pattern that does not involve explicitly choosing fields to copy. I am trying out something like this, but it is to hacky for my taste and did not test it in the production environment yet. class VersionedModel(BaseModel): is_history_copy = db.BooleanProperty(default=False) version = db.IntegerProperty() created = db.DateTimeProperty(auto_now_add=True) edited = db.DateTimeProperty() user = db.UserProperty(auto_current_user=True) def put(self, **kwargs): if self.is_history_copy: if self.is_saved(): raise Exception, "History copies of %s are not allowed to change" % type(self).__name__ return super(VersionedModel, self).put(**kwargs) if self.version is None: self.version = 1 else: self.version = self.version +1 self.edited = datetime.now() # auto_now would also affect copies making them out of sync history_copy = copy.copy(self) history_copy.is_history_copy = True history_copy._key = None history_copy._key_name = None history_copy._entity = None history_copy._parent = self def tx(): result = super(VersionedModel, self).put(**kwargs) history_copy._parent_key = self.key() history_copy.put() return result return db.run_in_transaction(tx) Does anyone have a simpler cleaner solution for keeping history of versions for app engine models? EDIT: Moved copy out of tx. Thx @Adam Crossland for the suggestion. A: Take a look at the properties static method on Model classes. With this, you can get a list of properties, and use that to get their values, something like this: @classmethod def clone(cls, other, **kwargs): """Clones another entity.""" klass = other.__class__ properties = other.properties().items() kwargs.update((k, p.__get__(other, klass)) for k, p in properties) return cls(**kwargs)
How to shallow copy app engine model instance to create new instance?
I want to implement a simple VersionedModel base model class for my app engine app. I'm looking for a pattern that does not involve explicitly choosing fields to copy. I am trying out something like this, but it is to hacky for my taste and did not test it in the production environment yet. class VersionedModel(BaseModel): is_history_copy = db.BooleanProperty(default=False) version = db.IntegerProperty() created = db.DateTimeProperty(auto_now_add=True) edited = db.DateTimeProperty() user = db.UserProperty(auto_current_user=True) def put(self, **kwargs): if self.is_history_copy: if self.is_saved(): raise Exception, "History copies of %s are not allowed to change" % type(self).__name__ return super(VersionedModel, self).put(**kwargs) if self.version is None: self.version = 1 else: self.version = self.version +1 self.edited = datetime.now() # auto_now would also affect copies making them out of sync history_copy = copy.copy(self) history_copy.is_history_copy = True history_copy._key = None history_copy._key_name = None history_copy._entity = None history_copy._parent = self def tx(): result = super(VersionedModel, self).put(**kwargs) history_copy._parent_key = self.key() history_copy.put() return result return db.run_in_transaction(tx) Does anyone have a simpler cleaner solution for keeping history of versions for app engine models? EDIT: Moved copy out of tx. Thx @Adam Crossland for the suggestion.
[ "Take a look at the properties static method on Model classes. With this, you can get a list of properties, and use that to get their values, something like this:\n @classmethod\n def clone(cls, other, **kwargs):\n \"\"\"Clones another entity.\"\"\"\n klass = other.__class__\n properties = other.properti...
[ 2 ]
[]
[]
[ "datastore", "google_app_engine", "python", "shallow_copy" ]
stackoverflow_0003691064_datastore_google_app_engine_python_shallow_copy.txt
Q: __init__, inheritance and variadic parameters I'd like to subclass an existing scons class (named SConsEnvironment) which has the following __init__ prototype: def __init__(self, platform=None, tools=None, toolpath=None, variables=None, parse_flags = None, **kw): In my own class Environment, which derives from SConsEnvironment, I tried to do: def __init__(self, platform=None, tools=None, toolpath=None, variables=None, parse_flags = None, **kw): if ('ENV' not in kw): kw['ENV'] = os.environ.copy() super(EIDEnvironment, self).__init__( platform, tools, toolpath, variables, parse_flags, kw) //Error here Python complains: TypeError: __init__() takes at most 6 arguments (7 given): Unless I don't know how to count anymore, it seems that both __init__ functions take 7 arguments. I'm sure there is a good reason for this not to work, but what is it and how can I solve this ? A: In the super(EIDEnvironment, self).__init__(...) call, change kw to **kw. As the code is currently written, you're passing a dictionary containing the keyword args, but not actually passing them as keyword args. A: I guess you need to unpack kw otherwise you pass it as a dictionary: super(EIDEnvironment, self).__init__( platform, tools, toolpath, variables, parse_flags, **kw)
__init__, inheritance and variadic parameters
I'd like to subclass an existing scons class (named SConsEnvironment) which has the following __init__ prototype: def __init__(self, platform=None, tools=None, toolpath=None, variables=None, parse_flags = None, **kw): In my own class Environment, which derives from SConsEnvironment, I tried to do: def __init__(self, platform=None, tools=None, toolpath=None, variables=None, parse_flags = None, **kw): if ('ENV' not in kw): kw['ENV'] = os.environ.copy() super(EIDEnvironment, self).__init__( platform, tools, toolpath, variables, parse_flags, kw) //Error here Python complains: TypeError: __init__() takes at most 6 arguments (7 given): Unless I don't know how to count anymore, it seems that both __init__ functions take 7 arguments. I'm sure there is a good reason for this not to work, but what is it and how can I solve this ?
[ "In the super(EIDEnvironment, self).__init__(...) call, change kw to **kw. As the code is currently written, you're passing a dictionary containing the keyword args, but not actually passing them as keyword args.\n", "I guess you need to unpack kw otherwise you pass it as a dictionary:\nsuper(EIDEnvironment, self...
[ 3, 1 ]
[]
[]
[ "inheritance", "initialization", "python", "variadic_functions" ]
stackoverflow_0003699580_inheritance_initialization_python_variadic_functions.txt
Q: SQLAlchemy memory hog on select statement As per the SQLAlchemy, select statements are treated as iterables in for loops. The effect is that a select statement that would return a massive amount of rows does not use excessive memory. I am finding that the following statement on a MySQL table: for row in my_connections.execute(MyTable.__table__.select()): yield row Does not seem to follow this, as I overflow available memory and begin thrashing before the first row is yielded. What am I doing wrong? A: The basic MySQLdb cursor fetches the entire query result at once from the server. This can consume a lot of memory and time. Use MySQLdb.cursors.SSCursor when you want to make a huge query and pull results from the server one at a time. Therefore, try passing connect_args={'cursorclass': MySQLdb.cursors.SSCursor} when creating the engine: from sqlalchemy import create_engine, MetaData import MySQLdb.cursors engine = create_engine('mysql://root:zenoss@localhost/e2', connect_args={'cursorclass': MySQLdb.cursors.SSCursor}) meta = MetaData(engine, reflect=True) conn = engine.connect() rs = s.execution_options(stream_results=True).execute() See http://www.sqlalchemy.org/trac/ticket/1089 Note that using SSCursor locks the table until the fetch is complete. This affects other cursors using the same connection: Two cursors from the same connection can not read from the table concurrently. However, cursors from different connections can read from the same table concurrently. Here is some code demonstrating the problem: import MySQLdb import MySQLdb.cursors as cursors import threading import logging import config logger = logging.getLogger(__name__) query = 'SELECT * FROM huge_table LIMIT 200' def oursql_conn(): import oursql conn = oursql.connect( host=config.HOST, user=config.USER, passwd=config.PASS, db=config.MYDB) return conn def mysqldb_conn(): conn = MySQLdb.connect( host=config.HOST, user=config.USER, passwd=config.PASS, db=config.MYDB, cursorclass=cursors.SSCursor) return conn def two_cursors_one_conn(): """Two SSCursors can not use one connection concurrently""" def worker(conn): cursor = conn.cursor() cursor.execute(query) for row in cursor: logger.info(row) conn = mysqldb_conn() threads = [threading.Thread(target=worker, args=(conn, )) for n in range(2)] for t in threads: t.daemon = True t.start() # Second thread may hang or raise OperationalError: # File "/usr/lib/pymodules/python2.7/MySQLdb/cursors.py", line 289, in _fetch_row # return self._result.fetch_row(size, self._fetch_type) # OperationalError: (2013, 'Lost connection to MySQL server during query') for t in threads: t.join() def two_cursors_two_conn(): """Two SSCursors from independent connections can use the same table concurrently""" def worker(): conn = mysqldb_conn() cursor = conn.cursor() cursor.execute(query) for row in cursor: logger.info(row) threads = [threading.Thread(target=worker) for n in range(2)] for t in threads: t.daemon = True t.start() for t in threads: t.join() logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s %(threadName)s] %(message)s', datefmt='%H:%M:%S') two_cursors_one_conn() two_cursors_two_conn() Note that oursql is an alternative set of MySQL bindings for Python. oursql cursors are true server-side cursors which fetch rows lazily by default. With oursql installed, if you change conn = mysqldb_conn() to conn = oursql_conn() then two_cursors_one_conn() runs without hanging or raising an exception.
SQLAlchemy memory hog on select statement
As per the SQLAlchemy, select statements are treated as iterables in for loops. The effect is that a select statement that would return a massive amount of rows does not use excessive memory. I am finding that the following statement on a MySQL table: for row in my_connections.execute(MyTable.__table__.select()): yield row Does not seem to follow this, as I overflow available memory and begin thrashing before the first row is yielded. What am I doing wrong?
[ "The basic MySQLdb cursor fetches the entire query result at once from the server.\nThis can consume a lot of memory and time.\nUse MySQLdb.cursors.SSCursor when you want to make a huge query and\npull results from the server one at a time.\nTherefore, try passing connect_args={'cursorclass': MySQLdb.cursors.SSCurs...
[ 14 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003699532_python_sqlalchemy.txt