Re: Pandas or Numpy
Hey, I don’t know but in case you don’t get other good answers, I’m pretty sure Numpy is more of a mathematical library and Pandas is definitely for handling spreadsheet data. So maybe both. Julius On Sun 23. Jan 2022 at 18:28, Chris Angelico wrote: > On Mon, 24 Jan 2022 at 04:10, Tobiah wrote: > > > > I know very little about either. I need to handle score input files > > for Csound. Each line is a list of floating point values where each > > column has a particular meaning to the program. > > > > I need to compose large (hundreds, thousands, maybe millions) lists > > and be able to do math on, or possibly sort by various columns, among > other > > operations. A common requirement would be to do the same math operation > > on each value in a column, or redistribute the values according to an > > exponential curve, etc. > > > > One wrinkle is that the first column of a Csound score is actually a > > single character. I was thinking if the data types all had to be the > > same, then I'd make a translation table or just use the ascii value > > of the character, but if I could mix types that might be a smidge better. > > > > It seems like both libraries are possible choices. Would one > > be the obvious choice for me? > > > > I'm not an expert, but that sounds like a job for Pandas to me. It's > excellent at handling tabular data, and yes, it's fine with a mixture > of types. Everything else you've described should work fine (not sure > how to redistribute on an exponential curve, but I'm sure it's not > hard). > > BTW, Pandas is built on top of Numpy, so it's kinda "both". > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Advanced ways to get object information from within python
Hello, I would like to significantly increase my abilities to find the information I am seeking about any Python object I am using from within Python. I find this to be a really essential skill set. After reading documentation, it really helps to get under the hood at the command line and start testing your own competence by examining all the methods and classes, and their arguments and return types and so on. I was hoping someone could help me fill in more details about what I currently know. I'd like to use Scrapy as an example, since it's a library I'm currently learning. import scrapy I assume I'll start with "dir", as it's the most convenient. dir(scrapy) shows this: ['Field', 'FormRequest', 'Item', 'Request', 'Selector', 'Spider', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_txv', 'exceptions', 'http', 'item', 'link', 'linkextractors', 'selector', 'signals', 'spiders', 'twisted_version', 'utils', 'version_info'] I wish there was a convenient way for me to know what all of these are. I understand "dir" shows everything from the namespace - so that includes methods which are present only because they are imported from other modules, by this module. Let's assume at minimum I know that I should be able to call all these "attributes" (I believe this is what Python calls them - an attribute can be anything, a method, a variable, etc. But then, how to distinguish between this general notion of an "attribute" vs a specific attribute of a class? Or is that called a "property" or something?) I can confirm that every single name in the above list works when I call it from scrapy, like this: >>> scrapy.Field >>> scrapy.utils But I can't conveniently iterate over all of these to see all their types, because dir() returns a list of strings. How can I iterate over all attributes? I can't use "getattr" because that requires you to enter the name of what you're looking for. I would like to spit out all attributes with their types, so I can know what my options are in more detail than dir() provides. This is basically a dead-end for me until someone can illuminate this strategy I'm pursuing, so now I'd like to focus on inspect and help. inspect.getmembers is useful in principle, but I find the results to give information overload. This is just an excerpt of what it returns: pprint.pprint(inspect.getmembers(scrapy)) [('Field', ), ('Selector', ), ('Spider', ), ('__all__', ['__version__', 'version_info', 'twisted_version', 'Spider', Why does it just list the name and type for some classes, but for others goes on to a sublist? __all__ does not list any type in adjacent angular brackets, it just goes on to list some attributes without any information about what they are. Can I suppress sublists from being printed with inspect.getmethods? Or can I recursively require sublists also display their type? Lastly, the "help" function. I find "help" to similarly be a situation of information overload. Again, it starts with a list of "package contents". I'm not sure I see the use of this long list of names, without much description of what they are. Next, it lists "classes", but I don't understand: builtins.dict(builtins.object) scrapy.item.Field parsel.selector.Selector(builtins.object) scrapy.selector.unified.Selector(parsel.selector.Selector, scrapy.utils.trackref.object_ref) What determines the order of these classes - the order in which they appear in the source code? What about the indentation? builtins.dict() is a Python builtin. Then why is it listed inside of Scrapy's "help" - are all builtins necessarily listed inside a class or just the builtins it specifically imported or inherited? My best guess is the most indented lines are what is actually written in the class, the lines above are just listing the inheritance? So scrapy.item.Field inherits the Python dictionary class, and it does this because that way you can treat the class like a dictionary sometimes, using dictionary methods and so on? class Field(builtins.dict) | Container of field metadata | | Method resolution order: | Field | builtins.dict | builtins.object | | Data descriptors defined here: What are data descriptors? I understand IDE's tend to just print the docstring of a method as a sort of overlay while you are writing with it, but I'm not able to use the __docstring__ variable well - scrapy.__docstring__, scrapy.Spider.__docstring__, and so on, return "object has no attribute __docstring__". I'm really fond of inspect.getsource(), all else failing, though - that's very clear and insightful. There's more to learn but that's enough questions for now. I'd really appreciate anybody helping me find effective ways of investigating modules, classes and methods from the command line. Thanks very much, Julius --
Short, perfect program to read sentences of webpage
Hey, This is something I have been working on for a very long time. It’s one of the reasons I got into programming at all. I’d really appreciate if people could input some advice on this. This is a really simple program which extracts the text from webpages and displays them one sentence at a time. It’s meant to help you study dense material, especially documentation, with much more focus and comprehension. I actually hope it can be of help to people who have difficulty reading. I know it’s been of use to me at least. This is a minimally acceptable way to pull it off currently: deepreader.py: import sys import requests import html2text import nltk url = sys.argv[1] # Get the html, pull out the text, and sentence-segment it in one line of code sentences = nltk.sent_tokenize(html2text.html2text(requests.get(url).text)) # Activate an elementary reader interface for the text for index, sentence in enumerate(sentences): # Print the sentence print(“\n” + str(index) + “/“ + str(len(sentences)) + “: “ + sentence + “\n”) # Wait for user key-press x = input(“\n> “) EOF That’s it. A lot of refining is possible, and I’d really like to see how some more experienced people might handle it. 1. The HTML extraction is not perfect. It doesn’t produce as clean text as I would like. Sometimes random links or tags get left in there. And the sentences are sometimes randomly broken by newlines. 2. Neither is the segmentation perfect. I am currently researching developing an optimal segmenter with tools from Spacy. Brevity is greatly valued. I mean, anyone who can make the program more perfect, that’s hugely appreciated. But if someone can do it in very few lines of code, that’s also appreciated. Thanks very much, Julius -- https://mail.python.org/mailman/listinfo/python-list
HTML extraction
Hey, Could anyone please comment on the purest way simply to strip HTML tags from the internal text they surround? I know Beautiful Soup is a convenient tool, but I’m interested to know what the most minimal way to do it would be. People say you usually don’t use Regex for a second order language like HTML, so I was thinking about using xpath or lxml, which seem like very pure, universal tools for the job. I did find an example for doing this with the re module, though. Would it be fair to say that to just strip the tags, Regex is fine, but you need to build a tree-like object if you want the ability to select which nodes to keep and which to discard? Can xpath / lxml do that? What are the chief differences between xpath / lxml and Beautiful Soup? Thanks, Julius -- https://mail.python.org/mailman/listinfo/python-list
Urllib.request vs. Requests.get
Hey, I am currently working on a simple program which scrapes text from webpages via a URL, then segments it (with Spacy). I’m trying to refine my program to use just the right tools for the job, for each of the steps. Requests.get works great, but I’ve seen people use urllib.request.urlopen() in some examples. It appealed to me because it seemed lower level than requests.get, so it just makes the program feel leaner and purer and more direct. However, requests.get works fine on this url: https://juno.sh/direct-connection-to-jupyter-server/ But urllib returns a “403 forbidden”. Could anyone please comment on what the fundamental differences are between urllib vs. requests, why this would happen, and if urllib has any option to prevent this and get the page source? Thanks, Julius -- https://mail.python.org/mailman/listinfo/python-list
[issue45934] python curses newterm implementation
Julius Hamilton added the comment: I’m currently planning on studying the C code for initscr and newterm so I can really understand how they work. I’ll post any updates about this soon. Thanks. -- ___ Python tracker <https://bugs.python.org/issue45934> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue45934] python curses newterm implementation
Julius Hamilton added the comment: I’m trying to patch this bug. Here are my current working questions: 1. What is the relationship between an fd (file descriptor) and a terminal? What software / hardware component goes to “fd 0” to receive input from it? Is there a GNU Screen command to receive stdin from “fd n”, fd 3 for example? 2. Looking at the source code: def initscr(): import _curses, curses # we call setupterm() here because it raises an error # instead of calling exit() in error cases. setupterm(term=_os.environ.get("TERM", "unknown"), fd=_sys.__stdout__.fileno()) stdscr = _curses.initscr() for key, value in _curses.__dict__.items(): if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'): setattr(curses, key, value) return stdscr - why does initscr() begin by importing _curses and curses? Precompiled C curses and non-compiled C or is the second importing Python? How can a module be importing itself? - they call “setupterm”, a C curses function, because it raises an error if there’s a problem in case of just quitting. But how so, specifically? Do the errors get detected at stderr and then the terminal raises another error or something? I’m not clear on the details. Plus, why can they call this function without referring to the enclosing package, curses.setupterm? Is that a C thing that all functions are automatically added to the namespace? - Someone wrote that “initscr” actually calls “newterm”, in the code. So I guess I should look at the C newterm code, see how it works and see if a direct implementation is possible. (I said in an email I would double post an email I sent but instead I’m posting more specific questions here related to that email. Also, I’m still studying an email Guido sent, so apologies for any redundant questions here.) Thanks, Julius On Sun 5. Dec 2021 at 00:01, Éric Araujo wrote: > > Change by Éric Araujo : > > > -- > stage: -> needs patch > versions: -Python 3.10, Python 3.6, Python 3.7, Python 3.8, Python 3.9 > > ___ > Python tracker > <https://bugs.python.org/issue45934> > ___ > -- ___ Python tracker <https://bugs.python.org/issue45934> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue45934] python curses newterm implementation
Julius Hamilton added the comment: I’m trying to patch this bug. Here are my current working questions: 1. What is the relationship between an fd (file descriptor) and a terminal? What software / hardware component goes to “fd 0” to receive input from it? Is there a GNU Screen command to receive stdin from “fd n”, fd 3 for example? 2. Looking at the source code: def initscr(): import _curses, curses # we call setupterm() here because it raises an error # instead of calling exit() in error cases. setupterm(term=_os.environ.get("TERM", "unknown"), fd=_sys.__stdout__.fileno()) stdscr = _curses.initscr() for key, value in _curses.__dict__.items(): if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'): setattr(curses, key, value) return stdscr - why does initscr() begin by importing _curses and curses? Precompiled C curses and non-compiled C or is the second importing Python? How can a module be importing itself? - they call “setupterm”, a C curses function, because it raises an error if there’s a problem in case of just quitting. But how so, specifically? Do the errors get detected at stderr and then the terminal raises another error or something? I’m not clear on the details. Plus, why can they call this function without referring to the enclosing package, curses.setupterm? Is that a C thing that all functions are automatically added to the namespace? - Someone wrote that “initscr” actually calls “newterm”, in the code. So I guess I should look at the C newterm code, see how it works and see if a direct implementation is possible. (I said in an email I would double post an email I sent but instead I’m posting more specific questions here related to that email. Also, I’m still studying an email Guido sent, so apologies for any redundant questions here.) Thanks, Julius -- ___ Python tracker <https://bugs.python.org/issue45934> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue45934] python curses newterm implementation
Change by Julius Hamilton : -- nosy: +Guido.van.Rossum, juliushamilton100 ___ Python tracker <https://bugs.python.org/issue45934> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39345] Py_Initialize Hangs on Windows 10
New submission from Darren Hamilton : This is related to https://bugs.python.org/issue17797, which is closed. Using Python 3.7.4, Windows 10.0.18362, Visual Studio 2017 and running as a C Application. Py_Initialize() eventually calls is_valid_fd with STDIN. The behavior appears to cause both dup() and fstat() to hang indefinitely (using RELEASE MSVCRT DLLs, it works correctly using MSVCRT Debug DLLs). The call stack shows Windows is waiting for some Windows Event. The recommended patch in issue17797 will not work. is_valid_fd appears to want to read the 'input' using a file descriptor. since both dup and fstat hang, I realized that isatty() would indicate if the file descriptor is valid and works for any predefined FD descriptor(STDIN-0, STDOUT-1, STDERR-2). #if defined(MS_WINDOWS) struct stat buf; if (fd >= fileno(stdin) && fd <= fileno(stderr)) { return (_isatty(fd) == 0 && errno == EBADF) ? 0 : 1; } else if (fstat(fd, ) < 0 && (errno == EBADF || errno == ENOENT)) return 0; return 1; #else -- components: Library (Lib), Windows messages: 360070 nosy: dhamilton, paul.moore, steve.dower, tim.golden, zach.ware priority: normal severity: normal status: open title: Py_Initialize Hangs on Windows 10 type: behavior versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue39345> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
PyKMIP 0.7.0
I am pleased to announce the release of PyKMIP 0.7.0. PyKMIP is a Python implementation of the Key Management Interoperability Protocol (KMIP), a communications protocol for the storage and maintenance of keys, certificates, and other secret objects. PyKMIP provides clients for conducting key management operations against KMIP appliances and a software server application for testing and demonstration. The library is licensed under Apache 2.0 and supports Python 2.7, 3.3-3.6. Changelog: * Add support for Python 3.6 * Add support for the InitialDate attribute * Add server support for the GetAttributeList operation * Add server support for the Locate operation * Add client and server support for the MAC operation * Add client and server support for the Revoke operation * Add client and server support for the Encrypt operation * Add client and server support for the Decrypt operation * Add client and server support for the DeriveKey operation * Add client and server support for the Sign operation * Add client and server support for the SignatureVerify operation * Add client and server support for retrieving wrapped keys * Add client and server support for storing wrapped keys * Add KMIP 1.4 enumerations * Add server config option enabling certificate extension checks * Add server config option defining set of usable TLS ciphers * Add server config option setting the server log level * Update the server to enforce checking object state and usage masks * Update server Locate support to allow object name filtering * Remove support for Python 2.6 * Fix bug with multithreading support with the SQLite backend * Fix bug with how open() is mocked in the server test suite * Fix bug with mismapped polymorphic identity for certificate objects * Fix bug with socket interrupt handling under Python 3.5 * Fix bug with detached instance errors in the server test suite GitHub: https://github.com/OpenKMIP/PyKMIP PyPI: https://pypi.python.org/pypi/PyKMIP/0.7.0 IRC: #pykmip on freenode.net Thanks to all of the contributors for their time and effort. Cheers, Peter Hamilton -- https://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
PyKMIP 0.6.0
I am pleased to announce the release of PyKMIP 0.6.0. PyKMIP is a Python implementation of the Key Management Interoperability Protocol (KMIP), a communications protocol for the storage and maintenance of keys, certificates, and other secret objects. PyKMIP provides clients for conducting key management operations against KMIP appliances and a software server application for testing and demonstration. The library is licensed under Apache 2.0 and supports Python 2.6, 2.7, 3.3-3.5. Changelog: * Add support for Python 3.5 * Add support for the State and OperationPolicyName attributes * Add server support for the Activate and GetAttributes operations * Add server support for certificate-based client authentication * Add server support for object access control via operation policies * Add server support for loading of user-defined operation policies * Add client support for the GetAttributes operation * Update clients to support operation policy names with objects * Update ProxyKmipClient to support names when creating new objects * Remove coveralls integration * Fix bug with early server termination on missing request credential * Fix bug with closing the client while unconnected to a server * Fix bug with default values overriding server config file settings * Fix bug with early server termination on bad client certificates * Fix bug with deprecated usage of the bandit config file * Fix bug with ProxyKmipClient registering unset object attributes GitHub: https://github.com/OpenKMIP/PyKMIP PyPI: https://pypi.python.org/pypi/PyKMIP/0.6.0 <https://pypi.python.org/pypi/PyKMIP/0.5.0> IRC: #pykmip on freenode.net Thanks to all of the contributors for their time and effort. Cheers, Peter Hamilton -- https://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
PyKMIP 0.5.0
I am pleased to announce the release of PyKMIP 0.5.0. PyKMIP is a Python implementation of the Key Management Interoperability Protocol (KMIP), a communications protocol for the storage and maintenance of keys, certificates, and other secret objects. PyKMIP provides clients for conducting key management operations against KMIP appliances and a software server application for testing and demonstration. The library is licensed under Apache 2.0 and supports Python 2.6, 2.7, 3.3, and 3.4. Changelog: * Add KmipServer server implementation * Add KmipSession to manage threaded client/server connections * Add KmipEngine for processing core server application logic * Add KmipEngine support for CRUD operations for managed objects * Add SQLAlchemy/SQLite support for KmipEngine data storage * Add CryptographyEngine component for cryptographic operations * Add pending deprecation warning for Python 2.6 support * Add pending deprecation warning for the KMIPServer implementation * Add support for building Sphinx documentation * Add support for SQLAlchemy tables to all Pie objects * Add Python magic methods to Attribute and Name objects * Add Attribute class unit tests * Add bin script to run the KmipServer * Add setup entry points to run the KmipServer * Update DiscoverVersions demo with optional versions argument * Update all demo scripts to setup their own logging infrastructure * Update README with information on the KmipServer implementation * Remove expired certificate files from the integration test suite * Remove default package log configuration and configuration file * Fix bug with Locate payload parsing optional values * Fix bug with DateTime string tests and move to UTC representation GitHub: https://github.com/OpenKMIP/PyKMIP PyPI: https://pypi.python.org/pypi/PyKMIP/0.5.0 IRC: #pykmip on freenode.net Thanks to all of the contributors for their time and effort. Cheers, Peter Hamilton -- https://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
[Glitch?] Python has just stopped working
I woke up two days ago to find out that python literally won't work any more. I have looked everywhere, asked multiple Stack Overflow questions, and am ready to give up. Whenever I run python (3.5), I get the following message: Fatal Python error: Py_initialize: unable to load the file system codec ImportError: No module named 'encodings' Current thread 0x2168 (most recent call first): If there's anything you know that I could do to fix this, then please tell me. I've tried uninstalling and reparing, so it's not those. Thanks! -- https://mail.python.org/mailman/listinfo/python-list
PyKMIP 0.4.1
I am pleased to announce the release of PyKMIP 0.4.1. PyKMIP is a Python implementation of the Key Management Interoperability Protocol (KMIP), a communications protocol for the storage and maintenance of keys, certificates, and other secret objects. PyKMIP provides clients for conducting key management operations against KMIP appliances. The library is licensed under Apache 2.0 and supports Python 2.6, 2.7, 3.3, and 3.4. Changelog: * Add support for the GetAttributeList operation * Add integration with Travis CI, Codecov/Coveralls, and Bandit * Add client/server failover support using multiple IP addresses * Add additional attribute unit tests * Update implementations of KMIP primitives * Reorganize server code to prepare for refactoring * Remove use of exec when handling library version numbers * Remove broken server script GitHub: https://github.com/OpenKMIP/PyKMIP PyPI: https://pypi.python.org/pypi/PyKMIP/0.4.1 IRC: #pykmip on freenode.net Thanks to all of the contributors for their time and effort. Cheers, Peter Hamilton -- https://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Simpleaudio 1.0.0 Release
Hello everyone, This is my announcement for a new MIT-licensed package/module called 'simpleaudio' that provides cross-platform audio playback capability for Python 3. Have a look at the documentation (link below) for installation, examples, and a tutorial. Wheels for OSX and Windows, as well as the source distribution for Linux, are on PyPI. http://simpleaudio.readthedocs.org The project source it at: https://github.com/hamiltron/py-simple-audio For help with usage, please post on StackOverflow with the tag 'pysimpleaudio'. For bugs or distribution issues, or please email simpleaudio.b...@gmail.com. Thanks and have fun. -Joe Hamilton jhamilto...@georgefox.edu -- https://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: Bug!
On 8/21/2015 7:02 PM, Chris Angelico wrote: On Sat, Aug 22, 2015 at 9:53 AM, sohcahto...@gmail.com wrote: On Friday, August 21, 2015 at 3:42:36 PM UTC-7, hamilton wrote: On 8/21/2015 1:41 PM, Chris Angelico wrote: Python 3.5 does not support Windows XP. Is there a simple explanation for this ? Or is it just is. I have no relationship with the Python developers, but I would say that running such an old operating system is simply irresponsible due to security issues and should be discouraged in any way possible. Windows XP is 14 years old. In the computing world, that's *ancient*. It's time to upgrade and join the modern world. The security concerns of XP aren't Python's problem, and Python isn't in the business of twisting people's arms to make them upgrade just for the sake of upgrading. However, every new version of Windows introduces new APIs and features, so maintaining support for an older version means ignoring all features added since then; conversely, dropping support for XP means taking advantage of anything that was added in Vista. That's why the change in support. ChrisA Thank You ChrisA, this make the best sense. -- https://mail.python.org/mailman/listinfo/python-list
Re: Bug!
On 8/21/2015 1:41 PM, Chris Angelico wrote: Python 3.5 does not support Windows XP. Is there a simple explanation for this ? Or is it just is. -- https://mail.python.org/mailman/listinfo/python-list
Re: Creating .exe file in Python
On 6/17/2015 7:20 AM, Chris Angelico wrote: On Wed, Jun 17, 2015 at 11:10 PM, subhabrata.bane...@gmail.com wrote: Thank you all. It seems going fine now. I have one additional question if I run the .exe files created in Non Python Windows environment. Linux has Python builtin but in Non Python environment how may I run it? Is there any set of prequisites I have to follow. I am not finding much web help, if any one may kindly suggest. There have been some proposals to make an easy way to produce a single package that has a Windows executable header, but can be easily unpacked and run using a system-provided Linux or Mac OS Python. However, I don't think any have been deployed yet. So the simple answer is: You can't do what you're trying to do. Instead, take a step back, and look at just getting your Python program to run on all platforms... and that's easy, just distribute the .py files. Much MUCH easier, more reliable, and simpler. ChrisA Yes, this is easy. However, the python source can be read by anyone. As a .exe, the source can not be read. Just because the interpreter is open source, does not mean my application should be. -- https://mail.python.org/mailman/listinfo/python-list
Re: OT ish Blocking telemarketers
On 6/12/2015 9:47 PM, Seymore4Head wrote: Yes I have tried the DNCR. It didn't help. The calls are not coming from the US although the caller ID says they are. So you want to block calls from a faked number ?!? ( do you have a good program to select lotto numbers?? :-) On my cell phone, I have my ringer turned off and it only vibrates, so I get a chance to see the number calling. If the number has already been logged into my phone, then it has a name attached to it. If no name is displayed, I do not answer. I will google the number to see if that number has a history. ( see http://800notes.com ) If you still have a landline, check with your provider to see if they offer call blocking. Years ago, USWEST had call blocking, but a limited amount of numbers could be entered. ( after talking with them about this, they told me that they had limited space per home phone number to store blocked numbers. ) DNCR is NOT the enemy, SCAMmers use what ever number they think they can get away with to make bogus calls. Until the NSA makes their data available to the public, SCAM callers will continue. -- https://mail.python.org/mailman/listinfo/python-list
Re: Human Rights and Justice in Islam
On 5/24/2015 3:59 AM, Steven D'Aprano wrote: On Sun, 24 May 2015 09:34 am, hamilton wrote: [quoted bullshit from a spammer] [tried to argue with said spammer] Please don't reply to fly-by-spammers. Even if the spammer was interested in honest debate -- and he is not (fortunately!) -- the last thing we want on a Python newsgroup is for it to be hijacked about arguments about religion. Sorry, it just hit me .. :-( -- https://mail.python.org/mailman/listinfo/python-list
Re: Human Rights and Justice in Islam
On 5/23/2015 8:11 AM, bv4bv4...@gmail.com wrote: Human Rights and Justice in Islam Description: A glimpse at the foundations of human rights laid by Islam. By islam-guide.com Islam provides many human rights for the individual. The following are some of these human rights that Islam protects. The life and property of all citizens in an Islamic state So if you are a Member of Islamic State you have rights, other wise you are an infidel and subject to death from the whim of Allah or whom ever thinks they are Allah. Does that sound right ?? -- https://mail.python.org/mailman/listinfo/python-list
Re: Monotheism - One God
On 3/19/2015 3:57 PM, bv4bv4...@gmail.com wrote: Monotheism - One God The religion of Islam is based on one core belief, that there is no god worthy of worship but Allah. Man has invented many GODs, in their image. Pick One: http://www.godchecker.com/ -- https://mail.python.org/mailman/listinfo/python-list
Re: HELP!! How to ask a girl out with a simple witty Python code??
On 3/7/2015 10:19 PM, Grant Edwards wrote: On 2015-03-07, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: alister wrote: a popular UK soap made an extreme effort not to show a cross or Christmas tree during a church wedding in case it offended not-Christians. In today's climate, when offending certain varieties of non-Christian can get you blown up or shot, it might not be quite as silly as it sounds. The same can happen if you offend certain varieties of Christians. Does Centennial Olympic Park sound familiar ? Christians and Republicans forgot what Jesus had to say. Which means they are NOT Christians. http://www.amazon.com/How-Republicans-Stole-Religion-Religious/dp/0385516045 -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: 9/11 Missing Links is the video that Jews do not want you to see!
On 9/24/2012 9:35 PM, Suzi Mrezutttii wrote: Google and watch 9/11 Missing Links before Jews remove it from youtube anytime now! Hey dude, Nice name, a boy named sue !!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Q: What does the double underscore __ mean?
On 9/9/2012 6:39 AM, Dave Angel wrote: See the identical thread you posted on tutor, where it was a better match. Would you please post that link for those of us that did not see that one. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On 8/28/2012 8:54 PM, Dennis Lee Bieber wrote: 2) does the printer appear as a serial port by the OS? Or as a printer device? The OP posted the link to the manual. If your not going to at least look it over, . USB Printer Interface The LabelWriter 450 series printers all communicate with the host computer using a full-speed USB 2.0 interface. This interface also operates with USB Version 1.1 or later. The printers implement the standard USB Printer Class Device interface for communications (see http://www.usb.org/developers/devclass/). hamilton PS: Page 14 -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending USB commands with Python
On 8/28/2012 11:04 PM, alex23 wrote: On Aug 29, 1:03 pm, hamilton hamil...@nothere.com wrote: The OP posted the link to the manual. If your not going to at least look it over, . Speaking for myself, I _don't_ go out of my way to read extra material But, you will give advice that has no value. Anything you post here from now on will be suspect. hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Text editors (was Re: Search and replace text in XML file?)
On 7/28/2012 1:23 PM, wxjmfa...@gmail.com wrote: For info: http://scintilla.org/ Just did a quick check on scintilla. This looks like a single file editor. Is there a project like capability in there that I did not notice ? Thanks hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Text editors (was Re: Search and replace text in XML file?)
On 7/28/2012 4:42 PM, Chris Angelico wrote: On Sun, Jul 29, 2012 at 7:43 AM, hamilton hamil...@nothere.com wrote: On 7/28/2012 1:23 PM, wxjmfa...@gmail.com wrote: For info: http://scintilla.org/ Just did a quick check on scintilla. This looks like a single file editor. Is there a project like capability in there that I did not notice ? Scintilla is a text editing widget; SciTE is a Scintilla-based Text Editor (and is by the same author). The editor wraps up Scintilla with facilities for handling multiple files simultaneously (multiple buffers/tabbed display/whatever you want to call it). ChrisA Ok, so the answer is no. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: can someone teach me this?
On 7/21/2012 9:06 AM, Devin Jeanpierre wrote: On Fri, Jul 20, 2012 at 11:15 PM, hamilton hamil...@nothere.com wrote: You are an idiot, or a scammer. Please be nice. -- Devin Devin, When someone asks me to download a compressed file, its just like the SCAM junk email I get all too often. If the OP would learn how to post on usenet, I would have been happy to help out. I apologize to the group, but the OP needs to learn how to post. hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: can someone teach me this?
On 7/20/2012 8:09 PM, Menghsiu Lee wrote: Hi, I have tried 1000 times to compile this python file to be an exe file by using py2exe and gui2exe But, it does not work out. I am thinking if there can be some genius teaching me how to make this happen. The link in below is the complete code with all sources. Everything is open to everyone since I change this from another expert. http://dl.dropbox.com/u/63928380/blackjack.rar Oh yea, let me download a rar file without an explanation. You are an idiot, or a scammer. Thanks for your help and instructions. Best regards, menghsiu -- http://mail.python.org/mailman/listinfo/python-list
Re: Diagramming code
Thank you Fred. I am new to python and am reviewing code I find online. Some projects do have docs that spell out what its doing, but many projects that I have download have just the code. I have my own personal style to decypher C and C++ code. But python is still foreign to me. hamilton On 7/16/2012 11:02 AM, Sells, Fred wrote: You leave many relevant questions unanswered. 1. Is the original developer/team available or have you been left with the code and little or no doc's? 2. How big is big in terms of the number of files/modules in the project? 3. Is there a reasonable structure to the project in terms of directories and a meaningful hierarchy 4. Does the project currently work and you just have to maintain/enhance it or was it abandoned by the original team in an unknown state and you have to save a sinking ship? 5. Are you an experienced Python programmer or a beginner. 6. Is the original code pythonic (i.e. clean and simple with brief, well organized methods) or do you have functions over 50 lines of code with multiple nested control statements and meaningless variable names? 7. Is there any documentation that defines what it should do and how it should do it. i.e. how do you know when it's working? These issues are not really Python specific, but if you've been given a broken project that has 200 poorly organized modules and little or no documentation and no access to the original team, a good first step would be to update your resume ;) OK then, let me ask, how do you guys learn/understand large projects ? hamilton -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Diagramming code
Is there any software to help understand python code ? Thanks hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: Diagramming code
On 7/15/2012 7:38 PM, Chris Rebert wrote: On Sun, Jul 15, 2012 at 6:26 PM, hamilton hamil...@nothere.com wrote: Subject: Diagramming code Is there any software to help understand python code ? What sort of diagrams? Control flow diagrams? Class diagrams? Sequence diagrams? Module dependency diagrams? There are many different types you could be referring to. Here's a relatively comprehensive list: http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview Regards, Chris -- UML: Kill it with fire! OK then, let me ask, how do you guys learn/understand large projects ? hamilton -- http://mail.python.org/mailman/listinfo/python-list
Plone Conference 2010 schedule published
Over 400 attendees are set to meet at the 8th annual Plone Conference for a week-long programme of training, talks and developer sprints from the 25th to 31st October at the Thistle Grand Hotel in Bristol, UK. Plone Conference 2010 registrations are open. Plone, an Open Source Content Management System used throughout the world has a massive following and Plone events are held around the globe. The largest of these is the annual Plone Conference and this year will be held in the UK. Plone is used for developing websites, intranet and portals for corporations, NGOs and the public sector. Organised by Netsight Internet Solutions, it promises to bring together developers, designers, end users and business people. This year an additional event is being planned as a one-day mini-conference on the 26th October called Plone in Business which will be aimed specifically at analysts, advisors, evaluators and information professionals looking to find out more about Plone and see a showcase of successful Plone projects from across the sectors. It will also see the launch of the JBoye Plone Community of Practice. The main part of the conference, from the 27th - 29th October, has over 50 scheduled talks from speakers from 19 countries and includes an 'unconference' day in which talks will be proposed by the attendees. Plone Conference 2010 scheduled talks include: * Easier and faster Plone theming with Deliverance * Design and Development with Dexterity * Enterprise Search in Plone with Solr * Boosting productivity with Plone-driven Plone development * Brasil.gov.br: Building a digital nation with Plone Alan Runyan, co-founder of Plone and president of Enfold Systems along with Alex Limi, fellow co-founder of Plone and now Firefox User Experience Lead at Mozilla will be delivering a keynote. There will also be a guest keynote by Richard Noble, OBE, project director of the Bloodhound SSC project attempting be build a car to pass the 1,000mph land speed mark. The conference falls at a great time, with the recent release of Plone 4, a product that raises the bar in the Content Management System market with a faster, more user-friendly and more refined version of the product. So far, registrations for the conference have come from over 30 countries around the world. To find out more about the conference and to register, visit http://ploneconf2010.org. -- Matt Hamilton ma...@netsight.co.uk Netsight Internet Solutions, Ltd. Business Vision on the Internet http://www.netsight.co.uk +44 (0)117 9090901 Web Design | Zope/Plone Development and Consulting | Co-location | Hosting -- http://mail.python.org/mailman/listinfo/python-list
Web shopping carts
Hey People, I am wondering if there are any OS shopping cart application written in python? Regards, Luke Hamilton Solutions Architect RPM Solutions Pty. Ltd. Mobile: 0430 223 558 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Web shopping carts
Thanks... Do you happen to have anymore details? From: Tino Wildenhain [EMAIL PROTECTED] Date: Wed, 10 Sep 2008 06:52:40 -0500 To: Luke Hamilton [EMAIL PROTECTED] Cc: python-list@python.org python-list@python.org Subject: Re: Web shopping carts Luke Hamilton wrote: Hey People, I am wondering if there are any OS shopping cart application written in python? Yes there are. HTH Tino -- http://mail.python.org/mailman/listinfo/python-list
Re: Web shopping carts
From: Tino Wildenhain [EMAIL PROTECTED] Date: Wed, 10 Sep 2008 08:40:42 -0500 To: Luke Hamilton [EMAIL PROTECTED] Cc: python-list@python.org python-list@python.org Subject: Re: Web shopping carts Hi, Luke Hamilton wrote: Thanks... Do you happen to have anymore details? Yes well... you guess it was supposed to be a funny comment but would you happen to have anymore details on your requirements as well? Your simple question was just asking for making fun of it. It was actually meant to be a pretty general question. I was really trying to get a feel for what was out there, so I can then to start to have a look at there capabilities. (Other than that please see the answer given by Fredrik) And unfortunately Google hasn't been much help... Ah, btw, I'd check the the other posts of long term members if you see something in the appearance different to yours :-) (not related to your question itself) Cheers Tino ... Luke Hamilton wrote: Hey People, I am wondering if there are any OS shopping cart application written in python? Yes there are. HTH Tino -- http://mail.python.org/mailman/listinfo/python-list
Vmware api
Hi List, Has anyone here played around with getting python to talk to the vmware api's. I have had a quick look at vmware's api and there is no out of the box python packages, but I believe that there might be some third party wrappers around? If anyone has any info that would be great. Thanks Regards, Luke Hamilton Solutions Architect RPM Solutions Pty Ltd Mobile: 0430 223 558 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: size of block device by ftell()
Seongsu Lee [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: I want to get the size of a block device by ftell(). I found that I can get the size of a device by seek() and tell() in Python. But not in C. What is difference between them? How can I get the size of a block device by ftell()? [snip] fp = fopen(d, r); fseek(fp, 0L, SEEK_END); l = ftell(fp); fclose(fp); return l; # ./ftell_test 362031 -1 You need to check the return values. ftell is returning -1, which is an indicator that it failed. If you were to print out errno, you could then look up why it's failing. (Or, you could call perror(3) or strerror(3) to get it translated into text for you.) --- # ./ftell_test.py 362031 120034091520 Or, if you convert the python version's output to hexadecimal and count the digits, you might figure out the proximate cause of your program's failure. GH -- http://mail.python.org/mailman/listinfo/python-list
RE: List loops
From: Tommy Grav Hi everyone, I have a list of objects where I have want to do two loops. I want to loop over the list and inside this loop, work on all the elements of the list after the one being handled in the outer loop. I can of course do this with indexes: alist = range(3) for i in xrange(len(alist)): ... for j in xrange(i+1,len(alist)): ... print i,j,alist[i],alist[j] ... 0 1 0 1 0 2 0 2 1 2 1 2 Is there a way to do this without using indexes? You have to use indices because you are printing the indices. Given that, the following loop does what it looks like you are trying to do. alist = range(3) for index, i in enumerate(alist): for jndex, j in enumerate(alist[index:]): print index, jndex, i, j 0 0 0 0 0 1 0 1 0 2 0 2 1 0 1 1 1 1 1 2 2 0 2 2 -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
Fwd: NUCULAR fielded text searchable indexing
On 10/9/07, Grant Edwards [EMAIL PROTECTED] wrote: On 2007-10-09, Robin Becker [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Oct 9, 8:46 am, Istvan Albert [EMAIL PROTECTED] wrote: ps. there is a python project named The Devil Framework, I cringe every time I hear about it.Nucularis not as bad, but it is close. Aw shucks. I thought it was funny. Can't I make fun of politicians in my open source projects? Besides there is a great tradition of tounge-in-cheek package names, like Cold fusion, for example. ... I think it's an excellent name :) And Bush would probably pronounce it Nuke-lee-ur. I dislike Bush as much as the next guy, but could we please keep politics off the group? -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: pytz has so many timezones!
On 10/9/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: On Oct 9, 8:34 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Oct 8, 1:03 pm, Carsten Haese [EMAIL PROTECTED] wrote: On Mon, 2007-10-08 at 10:41 -0700, [EMAIL PROTECTED] wrote: For example, Windows has seperate listings for Central America Central Time (US Canada) Guadalahara, Mexico City, Monterry - New Guadalahara, Mexico City, Monterry - Old Saskatchewan but they are all GMT-6 But they could have different rules for Daylight Saving Time. Which only matters if you're setting your clock. That's BS. If I'm supposed to be attending a video-conference that spans a few continents which is scheduled using a web-app, it's VITAL that I get the invitation and reminder rendered in MY local timezone, DST included. And for the matter of There are only 25 timezones: -12, -11, ... -1, 0 (GMT), +1, ... +11, +12. who says that timezones have to be separated by one hour each? The Earth says. It takes 24 hours to revolve. It only takes 24 hours for the Earth to revolve once because we defined an hour as 1/24 of the time it takes for the Earth to revolve once. We could have said an hour was 1/10 that time, or 1/2, or 1/27.284. Or why don't we have a global time? Like UTC? What about GMT? I hear that much more than UTC. Your 25 timezones are an abstraction the same way Not the same way at all. The 25 timezones I speak of are not merely an abstraction, but related to longitude. as are the 400 apparently in use by people all over the world Where the correlation to longitude is much looser. Granted, it doesn't need to be for non-navigational purposes. And although governments can legislate things like DST, they can't legislate longitude. But your 25 timezones are only useful to the people that use those 25 timezones. And the time zone I use is not one of those 25 timezones. - and last time I checked, there was no fundamental law in physics or such that limited the allowed or sensible number of timezones... Isn't there some law somewhere that says the circumference of a sphere is 360deg? Doesn't that same law mean that no two points on a sphere can be seperated by more than 180deg longitude? Doesn't that make GMT+13 non-sensible? A timezone is an arbitrary geographical designation. It has nothing to do with latitude or longitude. While some time zones may be defined as a geographical region between two longitudes, others may be defined by geographical borders or convienent terrain features. Take a look at the international date line. It doesn't follow a longitudinal line, but instead jogs east around Asia and then west around the Aleutian Islands. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: List loops
On 10/9/07, John Machin [EMAIL PROTECTED] wrote: On 10/10/2007 1:33 AM, Hamilton, William wrote: From: Tommy Grav Hi everyone, I have a list of objects where I have want to do two loops. I want to loop over the list and inside this loop, work on all the elements of the list after the one being handled in the outer The man said after ... alist = range(3) for index, i in enumerate(alist): for jndex, j in enumerate(alist[index:]): ... so you need index+1 ... print index, jndex, i, j 0 0 0 0 ... to avoid the above unwanted output. Hey, if I got it right, he'd have no work to do himself. :) -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: tkinter question
-Original Message- From: Kevin Walzer See http://www.codebykevin.com/blosxom/business/phynchronicity-new.png: this is an application I develop. The layout is all handled by pack and paned windows. Where you you use grid in a layout like this? I'd use a three row grid, with the middle row containing a frame with another grid in it. I don't try to create a single massive grid that manages everything, I break it up into subgrids of related widgets. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: sorteddict [was a PEP proposal, but isn't anymore!]
From: thebjorn What's stabledict? I'm assuming that ordereddict is a mapping that maintains insertion order(?) Yes, ordereddict is a dict that maintains insertion order. Stabledict is probably a dict that maintains _an_ order, so that repr() and the like return the same value when used on dicts containing the same data. In the Smalltalk collection hierarchy SortedCollection is a subclass of OrderedCollection, which implies to me that it'd be better to add an ordereddict first. That depends entirely on how ordereddict and sorteddict function. If they are similar there might be a benefit. However, an ordereddict would probably be best implemented with an internal list of keys, whereas the consensus seems to be using a tree for sorteddict. In this case, trying to build sorteddict from ordereddict is going to give you extra baggage and overhead for no benefit. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: sorteddict PEP proposal [started off as orderedict]
From: Paul Hankin Here's a first go. Sorting occurs when the keys are iterated over, making it fast (almost as a dict) for construction, insertion, and deletion, but slow if you're iterating a lot. You should look at some use cases to decide if this approach is best, or if a sorted datastructure should be used instead, but my instinct is that this is a decent approach. Certainly, you're unlikely to get a simpler implementation :) class sorteddict(dict): A sorted dictionary def __init__(self, arg=None, cmp=None, key=None, reverse=False): if arg: super(sorteddict, self).__init__(arg) else: super(sorteddict, self).__init__() self._cmp = cmp self._key = key self._reverse = reverse def keys(self): return sorted(super(sorteddict, self).keys(), cmp=self._cmp, key=self._key, reverse=self._reverse) def iter_keys(self): return (s for s in self.keys()) def items(self): return [(key, self[key]) for key in self.keys()] def iter_items(self): return ((key, self[key]) for key in self.keys()) def values(self): return [self[key] for key in self.keys()] def iter_values(self): return (self[key] for key in self.keys()) def __str__(self): return '{' + ', '.join('%s: %s' % (repr(k), repr(v)) for k, v in self.iter_items()) + '}' def __repr__(self): return str(self) def __iter__(self): return self.iter_keys() You could speed up keys() at the cost of memory if you maintained a list of keys in the instance. Doing so would let you use an unsorted flag that gets set when a new key is added and checked when keys() is called. If the flag is unset, just return a copy of the list. Otherwise, sort the list in place, return a copy, and unset the flag. (Copies because you don't want the master key list to be modified by code using the class.) The use case for this seems to be when you have a dictionary that you need to often work through in sorted order. Sorting the keys every time keys() is called isn't an improvement over using a regular dict and sorting the keys normally. So the extra memory cost of maintaining an internal keys list looks reasonable to me. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: An ordered dictionary for the Python library?
From: Michele Simionato On Sep 12, 3:54 pm, Mark Summerfield [EMAIL PROTECTED] wrote: On 12 Sep, 13:46, Michele Simionato [EMAIL PROTECTED] Actually I meant by key order, so insertion order doesn't matter at all. If you need a dictionary-like data structure that respects insertion order you could use a list of (key, value) tuples. Another respondent asked about use cases. I have found time and again that I needed (key, value) pairs where the key is some string that provides a representation for human readers and the value is some internal key (e.g., database ID) that the system uses internally. In these cases I often need to present the user with a list of items from which to choose and want to present them in sorted order. Naturally, I could use an ordinary dict and then do this: for string in sorted(d.keys()): process(string) But what happens when I need to do this a *lot* and when the number of items is hundreds or a few thousands? I'm having to sort again and again, since it is often the case that the items in the list changes during the runtime of the application. So my solution in C++ is to use an ordered dictionary (a map in C++ jargon), which in Python means I can simply write: for string in od.keys(): process(string) For your use case I would wrap a list [(key, value)] with a dict-like object and I would use the bisect module in the standard library to keep the inner list ordered. Or subclass dict to carry along a sorted list of keys with it and return that when dict.keys() is called. Even better, only have .keys() sort the keys list when a key has been added to it since the last call. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Checking if elements are empty
From: Steve Holden Neil Cerutti wrote: On 2007-09-10, Chris Mellon [EMAIL PROTECTED] wrote: On 9/10/07, Neil Cerutti [EMAIL PROTECTED] wrote: Agreed; but I prefer 'if y[0] == ', absent more context and better names. Probably should use u if you're going to take that route, as this will fail spuriously if y[0] contains a unicode string that can't be implicitly converted to ascii. Personally, I prefer the boolean check and I'll let operations fail elsewhere if there's a type mismatch. I have a quibble not with the functionality of the boolean check, but with its expressiveness. if y[0] == expresses more, i.e., that I expect y[0] to contain a Python byte string. I have a quibble with a test that will raise an exception when the anticipated condition is true. Your test is patently absurd, as you would have discovered had you bothered to try it: y = if y[0] == : ... print True ... else: ... print False ... Traceback (most recent call last): File stdin, line 1, in module IndexError: string index out of range Further, when the string is *not* the null string the test will always return False, as you will be comparing two strings of unequal length. So, absent a solution that works, len(y) == 0 looks pretty good. Going back to the OP, the problem is taking a string such as x = ' \tff' then splitting that string like this y = x.split('\t') The question is, does the first element of the list y contain an empty string or not? In this case, the logic in the following conditional is perfectly valid. if y[0] == : ...print True ... else ...print False (len(y[0]) == 0) would also work, and is the solution you originally gave the OP. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: newbie: stani's python editor if-else
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED] Sent: Tuesday, September 11, 2007 8:26 AM To: python-list@python.org Subject: Re: newbie: stani's python editor if-else On Sep 10, 11:24 pm, madzientist [EMAIL PROTECTED] wrote: hi, two quick questions: a) i am using SPE (latest version) and for some reason, when i type, say if 1==2: print not equal else: print equal the else is at the same indentation level as the preceding print statement, and i get a syntax error why doesn't spe automatically put the else at the level of the if statement ? what am i dong wrong ? once i manually change the indentation, the code snippet runs perfectly. b) if this is not the group for such elementary questions, please do let me know. thanks suresh I agree with Steve. I have yet to see an IDE for Python (or anything else) that unindents statements. Even IDLE, the Official IDE for Python, doesn't do that. IDLE (At least, IDLE 1.0.5) unindents in obvious situations. I think it's only on break, continue, pass, and return statements, but there may be others. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Excel process still running after program completion.
From: Chris I have a python script that is driving Excel and using the win32com module. However, upon program completion there's still an Excel.exe process running in the background that I must terminate through Task Manager. Reading up on other threads indicate that maybe I still have some Excel objects referenced within my code. Is this why the process doesn't terminate? The related (I hope) parts of my code is here. x1App = Dispatch(Excel.Application) Book1 = x1App.Workbooks.Open(ExcelLogPath+\\outputLog-template.xls) x1App.Visible = 1 for sheets in Book1.Worksheets: if sheets.Name == file_name: sheetExists = True if sheetExists != True: activeSheet = Book1.Worksheets.Add(After=Book1.Worksheets(1)) activeSheet.Name = file_name testNum[file_name] = 0 Book1.Worksheets(file_name).Select() Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = Original File Name Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value = file_name Book1.ActiveSheet.Pictures().Insert(output).Select() Book1.SaveAs(Filename=path) x1App.ActiveWorkbook.Close(SaveChanges=0) x1App.Quit() del x1App del Book1 del activeSheet What am I missing? In my Excel projects, I terminate it with: xlBook.Close() xlApp.Quit() I haven't had a problem with Excel staying open after the program ends. (On a tangent, I want to find the person who thought it was a good idea to use the same symbol in a font for 1, l, and I and do some unpleasant things.) -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Python code-writing for the blind. Was (Re: newbie: stani's pythoneditor if-else)
From: madzientist Thanks, everybody, for the very very useful and kind responses. There is a second reason why I asked the question about automatic de- indenting. I am teaching myself Python partly so I can then help my technically astute, but blind friend learn programming. For the many reasons that Pythonistas like to cite often, I thought Python would be a good choice to learn programming, and that perhaps the indentation problem would be solved by the use of an intelligent editor. But now I am not so sure, though I will try Emacs. Is there anyone here with experience in such issues ? Maybe for her sake, I should switch to learning Perl ;) ;) More seriously, the added issue is that SPE uses spaces, not a single tab to indent the lines, and I believe it is extremely tedious to use screen-readers to keep track of blank spaces at the beginning of each line. I have not tried it myself yet, but I will soon. Is Python a bad choice for the blind programmer, as a result of a tight linkage between visual aspects of the code and its function ? I wish the site blindprogramming.com weren't so lifeless... Can you set SPE to use a single space rather than the typical four spaces? Python should accept it just fine. You'll still have problems reading other people's code. Maybe you can write a quick script that converts code down to one-space indents. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Silent SaveAs when using the Excel win32com module
From: Chris I'm trying to create an excel file which will act as a log, however I want to overwrite the file if it exists. Looking at the SaveAs method I can't find anything that would allow it. I don't want the prompt to appear to ask whether to replace the file or not. I just want to replace it without thinking. Thanks in advance. Check if the file exists and delete it before saving the new one. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: application version checking against database
From: imageguy We are trying to implement a system that checks the version of the application against a version number stored in the database. We don't want the app and the db don't become out of sync. We have tried setting a __version__ variable in the top most module, however, it seems that this is not accessible for the modules that are subsequently imported. There are a several locations in the app where we want to do the version check, but we would like to have one place to set the version number, namely the top level module. We have thought of creating a Version class and passing it around, but aren't really keen on that idea. Any suggestions/ideas would be helpful. NOTE: the app is developed in wxPython. You could add a Version module that contains the version number and any functions related to the version checking, and import that into the modules that do version checking. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: list index()
From: [EMAIL PROTECTED] How could it not be an exception, in the plain English sense of the word? Most certainly you're asking for the index because you want to do something with the index. If the item is not found, you have no index, so that's a special case that must be handled separately. There is no logical difference between handling that special case in an except clause versus handling it with an if-branch. In my case of have done os.listdir() on two directories. I want to see what files are in directory A that are not in directory B. I have used exceptions in other languages and only do so on logic that should never happen. In this case it is known that some of the files will not be in both lists. I just want to know which ones. I think you may be confusing exceptions and assertions. Asserts are generally used to trap conditions that should not happen, while exceptions in Python are a standardized way to handle errors of all sorts. Where in C you would, say, open a file and check the return code to ensure that the file actually exists before using it, in Python you wrap the open statement in a try/except block instead. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Something in the function tutorial confused me.
From: Lee Fleming On Aug 6, 6:25 am, Neil Cerutti [EMAIL PROTECTED] wrote: Because when the function is called, the line if y is None: y = [] is executed, binding a brand new empty list to y. This rebinding happens every time the function is called, unless you provide an argument for y that is not None. Thanks for the prompt replies. But I am still confused. This is what confuses me The first time you call the function, say with f(23), after the function ends, y no longer equals None. Therefore, calling f again, this time like this f(24), should make y equal [23,24], because the 'if y == None' test fails, or at least I think it fails, because y.append(x) added something that was not equal to None during the previous call. When you call f(23), the variable y within it gets created and points at None. When f(23) exits, the y that it created gets destroyed. (Well, goes out of scope, but even if it's not garbage collected it won't ever come back into scope.) When you then call f(24), a new y is created that also points to None, and disappears forever when f(24) exits. The values in a def statement are created when the def is executed, but the variables are only created when the function is actually called, and new ones are created every time the function is called. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Something in the function tutorial confused me.
From: Lee Fleming On Aug 6, 12:30 pm, Hamilton, William [EMAIL PROTECTED] wrote: When you call f(23), the variable y within it gets created and points at None. When f(23) exits, the y that it created gets destroyed. (Well, goes out of scope, but even if it's not garbage collected it won't ever come back into scope.) When you then call f(24), a new y is created that also points to None, and disappears forever when f(24) exits. The values in a def statement are created when the def is executed, but the variables are only created when the function is actually called, and new ones are created every time the function is called. -- -Bill Hamilton- Hide quoted text - - Show quoted text - why isn't the y in def f (x, y = []): something garbage-collected? The y is garbage-collected. However, the [] in the def statement is not. The list is created when the statement is evaluated. Every time that f() is called with a default value, the new y created will point to the same list. If that list is mutated into [23], it will still be [23] the next time f() is called, and the new y created in that call will point at the same list (now [23]) that the (now destroyed) y pointed to in the first call. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Bug in Time module, or in my understanding?
From: Joshua J. Kugler I am getting results like these with the time module: import time int(time.mktime(time.strptime('2007-03-11 02:00:00', '%Y-%m-%d %H:%M %S'))) 1173610800 int(time.mktime(time.strptime('2007-03-11 03:00:00', '%Y-%m-%d %H:%M %S'))) 1173610800 time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173610800)) '2007-03-11 03:00:00' I know it probably has something to do with daylight savings, but how can I get back out that which I put in? The times concerned are all standard time, so how can I keep the time module from asserting its belief that I want to convert to daylight savings? Incidentally, it only happens with times on 2007-03-11 from 02:00:00 to 02:59:59, and not with time data from past years. I get similar results, except with hours 01:00:00 and 02:00:00. I am in US Central time (GMT-6). int(time.mktime(time.strptime('2007-03-11 00:00:00','%Y-%m-%d %H:%M:%S'))) 1173592800 int(time.mktime(time.strptime('2007-03-11 01:00:00','%Y-%m-%d %H:%M:%S'))) 1173596400 int(time.mktime(time.strptime('2007-03-11 02:00:00','%Y-%m-%d %H:%M:%S'))) 1173596400 int(time.mktime(time.strptime('2007-03-11 03:00:00','%Y-%m-%d %H:%M:%S'))) 117360 -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Making Gridded Widgets Expandable
From: Jim Hi, I'm looking at page 548 of Programming Python (3rd Edition) by Mark Lutz. The following GUI script works with no problem, i.e., the rows and columns expand: = # Gridded Widgets Expandable page 548 from Tkinter import * colors = [red, white, blue] def gridbox(root): Label(root, text = 'Grid').grid(columnspan = 2) r = 1 for c in colors: l = Label(root, text=c, relief=RIDGE, width=25) e = Entry(root, bg=c, relief=SUNKEN, width=50) l.grid(row=r, column=0, sticky=NSEW) e.grid(row=r, column=1, sticky=NSEW) root.rowconfigure(r, weight=1) r += 1 root.columnconfigure(0, weight=1) root.columnconfigure(1, weight=1) root = Tk() gridbox(Toplevel(root)) Button(root, text=Quit, command=root.quit).grid() mainloop() = However, the following GUI script using class does not expand rows and columns: = # Gridded Widgets Expandable 2 from Tkinter import * colors = [red, white, blue] class GUI(Frame): def __init__(self,master): Frame.__init__(self,master) self.grid() self.gridbox() def gridbox(self): Label(self, text = 'Grid').grid(columnspan = 2) r = 1 for c in colors: l = Label(self, text=c, relief=RIDGE, width=25) e = Entry(self, bg=c, relief=SUNKEN, width=50) l.grid(row=r, column=0, sticky=NSEW) e.grid(row=r, column=1, sticky=NSEW) self.rowconfigure(r, weight=1) r += 1 self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) root = Tk() root.title(Gridded Widgets Expandable) app = GUI(root) Button(root, text=Quit, command=root.quit).grid() root.mainloop() = What am I missing? In the first, your gridbox has Toplevel(root) as its master, causing it to be created in a new window. In the second, it has Frame(root) as its master, which does not create a new window. Changing Frame to Toplevel in the class statement and the call to __init__ causes them to act identically. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: PEP 3107 and stronger typing (note: probably a newbie question)
From: Paul Rubin greg [EMAIL PROTECTED] writes: E.g. your program might pass its test and run properly for years before some weird piece of input data causes some regexp to not quite work. Then you get a bug report, you fix it, and you add a test for it so that particular bug can't happen again. Why on earth would anyone prefer taking a failure in the field over having a static type check make that particular failure impossible? Because static typechecking won't make that particular failure impossible, but instead just change it from a type error into a data error that may or may not be harder to identify. If your program gets a piece of data that breaks it, you'll get a failure in the field. Static typechecking won't prevent that. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Collections of non-arbitrary objects ?
From: walterbyrd Yes, but those languages also have the notion of structures that do not allow arbitrary collections. That is what I was wondering about when I started the thread. It's fine that python has four different ways of creating collections of arbitrary data types, but I thought it might be helpful if python had, at least, one way of a creating a collection of non-arbitrary data. The thing is, in python all data is arbitrary. The differences between the data types float, int, string, etc. are unimportant. What is important is the _behavior_ of those types. If it is really necessary to check data when putting it into your collection (user input, processing side-effects will cause damage, etc.), test that it behaves the way you need it to behave rather than requiring a specific type. It seems to me that tuple are essentially immutable lists. So why impose that immutability restriction on a data collection? Why not just have lists and not tuples? What can a tuple do that a list can not do? Why was python designed so that tuples could be used for dictionary indexes, but not lists? Could it be because imposing that restriction on a data collection insures a certain degree of integrity? My point is: sometimes imposing some restrictions can give a degree in built-in integrity. Maybe you don't need that integrity insurance, if you code carefully enough, but can you always count on that? Tuples are more like structs in C. They are collections of data in a particular order. Lists, on the other hand, are ordered collections of data that all exhibit the same behavior. You don't have to use them like that, but those are the uses they were developed for as I understand it. Function arguments are the obvious example of a tuple. The position of an argument in the argument tuple defines how it is used in the function; get the position wrong, and the function will act unexpectedly and probably raise an exception. Iterating over a set of function arguments doesn't make much sense in the general case. Lists, are generally intended to be iterated over. You may take a list of items that are addable, and add them. You may take a list of file-like objects and concatenate them into one file-like object. (And, note the -like part of that. They don't have to be files, they just have to be things that _behave_ like files for the file-like functions you'll be using.) BTW: I'm not assuming that it will always be me running my own app. Sure, if an exception occureed while I was running my own app, I'd probably know what to do. But if somebody else (who - god forbid - didn't know python was running the app, things might be more difficult. So, what happens when this user tries to put something into your restricted list that isn't allowed? I expect they'll produce an exception of some sort, and the app will crash if you don't handle that exception. Which is exactly what will happen if you don't restrict the list data and it gets processed. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
Excel file interface for Python 2.3?
I'm in need of a module that will let me create Excel workbooks from within Python. Something like PyExcelerator, but it needs to work with Python 2.3. (A third-party limitation that I have no control over.) Can anyone point me to what I need? All my searches keep leading back to PyExcelerator. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: c[:]()
From: Warren Stringer Hmmm, this is for neither programmer nor computer; this is for a user. If I wanted to write code for the benefit for the computer, I'd still be flipping switches on a PDP-8. ;-) This is inconsistent: why does c[:][0]() work but c[:]() does not? Why does c[0]() has exactly the same results as c[:][0]() ? Moreover, c[:][0]() implies that a slice was invoked c[:] is a copy of c, if c is a list, tuple, string, or other object that supports slicing. c[:][0] points to the same object as c[0]. If that object is a function, then c[:][0]() and c[0]() do the same thing, because they both point to the same function. c[:]() does not make sense, because c is a tuple and not a function. Similarly, c[0:1]() will not make sense because while c is a tuple of one object, it is still a tuple and not a function. Note that c[0] is not the same as c[0:1]: the former is the object pointed to by the first member of the tuple, while the second is a tuple containing a single member pointing to the first member of the original tuple. There isn't an inconsistency because the two notations mean completely different things. So, tell me, for scheduling a lot of asynchronous events, what would be more readable than this: bidders = [local_members] + [callin_members] bidders[:].sign_in(roster) ... Does bidders[:].sort() make sense? In your scheme, would this tell the various contents of bidders to sort their own contents, or would it do the currently valid action of sorting a copy of the bidders list? I think you misunderstand how the slice operator works. A slice of a tuple is itself a tuple. If you want to act on the contents of that tuple, you need to act on those contents individually either by indexing them (c[0]) or iterating over them (for f in c:). -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Installing Python in a path that contains a blank
From: John Machin On 21/05/2007 11:30 PM, Konrad Hinsen wrote: I am trying to install Python from sources in my home directory on a Mac cluster (running MacOS X 10.4.8). The path to my home directory contains a blank, and since the installation procedure insists on getting an absolute path for the prefix, I cannot avoid installing to a path whose name contains a blank. Python does not seem to be prepared for this, as it uses only the part before the blank, resulting in numerous error messages. Does anyone know a workaround? On Windows, the workaround for pesky paths (i.e. containing blanks or just inconveniently long) is the subst command: command-promptsubst X: C:\Documents and Settings Thereafter X:\foo can be used wherever C:\Documents and Settings\foo would otherwise be required. There's also short filename substitution. C:\Documents and Settings\foo can be replaced with C:\docume~1\foo. In general, you take the first six non-space characters and append ~digit to it. I've never run into a situation where digit was anything other than 1, but I'm pretty sure that you increment it if you have multiple files/directorys in the same directory that have the same first six non-space characters. This should work on any Windows long-filename system where you need 8.3 filenames for backwards compatibility. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: 'int' object is not callable in an threaded app
From: king kikapu Hi, i have a problem with the following piece of code that id just drive me nuts (from the morning...) I think is more Python specific than Qt, folks from Qt forum have already give me directions of how to do it but that Python error message is just impossible for me to figure out. And i am sure that it something just under my nose... So, i have a form with 2 spin boxes, a button and a progress bar. When i hit the button i expect to see the progressbar filled with the values of spFrom and spTo (the 2 spinboxes) I was given help if how to setup correctly the Signals and Slots mechanism but i am stuck at this Python error at the worker.start() command: TypeError: 'int' object is not callable Before i go and suicide, has anybody an idea what is going on here ??... import sys from PyQt4 import QtCore, QtGui from calculatorform_ui import Ui_CalculatorForm from ui_countNumbers import Ui_MainWindow from time import sleep class WorkerThread(QtCore.QThread): def __init__(self, start, end): QtCore.QThread.__init__(self) self.start = start self.end = end def run(self): for x in range(start, end): self.emit(QtCore.SIGNAL(updateProgress), x) class CountNumbersForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) @QtCore.pyqtSignature() def on_start_clicked(self): worker.start() def updateProgress(self, val): self.ui.progres.setValue(val) if __name__ == __main__: app = QtGui.QApplication(sys.argv) count = CountNumbersForm(); worker = WorkerThread(count.ui.spFrom.value(), count.ui.spTo.value() + 1); QtCore.QObject.connect(worker, QtCore.SIGNAL(updateProgress), count.updateProgress, QtCore.Qt.QueuedConnection) count.show() sys.exit(app.exec_()) It appears that worker.start gets set to the result of count.ui.spFrom.value(). If that result is an int, then worker.start() is going to generate the TypeError you received. Did you actually mean to call worker.run() instead? --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: tkinter button state = DISABLED
From: Eric Brunel On Thu, 17 May 2007 09:30:57 +0200, Hendrik van Rooyen [EMAIL PROTECTED] wrote: Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 16 May 2007 03:22:17 -0300, Hendrik van Rooyen I have never seen this working in Tkinter, unless the button was pressed on the widget in question - and worse, once you have clicked down on a ButtonRelease binding you can move the mouse pointer anywhere you like, even out of the application and when you release it, the bound function is called... Its either a bug or a feature, I don't know. Uhmm... I'm not sure I understand you completely. I only said that the command is fired only when the mouse button is pressed on the widget, AND released inside the same widget. If both events don't happen in the same widget, command won't fire. Maybe you are saying the same thing... anyway I'm not a Tk expert. No command is ok and you have described it right - its ButtonRelease that seems broken to me Apparently, this behaviour is the intended one, at least for buttons; see: http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm#M11 As for the question why?, maybe you should ask it on the c.l.tcl newsgroup? The difference between bind and the button's command parameter makes sense to me. You'd use bind to create something like a right-click menu, where you want the same thing to happen whether the button is disabled or not. You use the command parameter when you care about the state of the button. -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Random selection
From: Tartifola Hi, I have a list with probabilities as elements [p1,p2,p3] with of course p1+p2+p3=1. I'd like to draw a random element from this list, based on the probabilities contained in the list itself, and return its index. Any help on the best way to do that? Thanks ran = random.random() ran 0.70415952329234965 for index, value in enumerate(x): if sum(x[0:index]) ran: print index, ran break 2 0.704159523292 -- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: tkFileDialog.askopenfilename()
From: [EMAIL PROTECTED] Hi, When I call tkFileDialog.askopenfilename() , the dialog box opens with the current directory as the default directory. Is it possible to open the dialog box with a directory other than the current directory. Can we pass in a user defined starting directory. Thanks Rahul This link has a decent amount of info about the various dialog modules. http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Trying to choose between python and java
From: Beliavsky On May 15, 1:30 am, Anthony Irwin [EMAIL PROTECTED] wrote: snip #5 someone said that they used to use python but stopped because the language changed or made stuff depreciated (I can fully remember which) and old code stopped working. Is code written today likely to still work in 5+ years or do they depreciate stuff and you have to update? Because Python 3 will change the syntax of print to disallow print Hello, world. a substantial fraction of Python programs in existence, including all of my programs, will be broken. Draw your own conclusions. No, they'll work just fine. They just won't work with Python 3. It's not like the Python Liberation Front is going to hack into your computer in the middle of the night and delete you 2.x installation. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: change of random state when pyc created??
From: Alan Isaac I'm sure my first pass will be flawed, but here goes: http://docs.python.org/lib/typesmapping.html: to footnote (3), add phrase which may depend on the memory location of the keys to get: Keys and values are listed in an arbitrary order, which may depend on the memory location of the keys. This order is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. http://docs.python.org/lib/types-set.html: append a new sentence to 2nd paragraph Iteration over a set returns elements in an arbitrary order, which may depend on the memory location of the elements. It's possible there are other factors that can affect this as well. A more general statement is probably more appropriate: Keys and values are listed in an arbitrary order. This order is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions as well as factors outside the scope of the containing program. Iteration over a set returns elements in an arbitrary order, which may depend on factors outside the scope of the containing program. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: keyword checker - keyword.kwlist
From: [EMAIL PROTECTED] Hi I try to check whether a given input is keyword or not. However this script won't identify keyword input as a keyword. How should I modify it to make it work? #!usr/bin/env python import keyword input = raw_input('Enter identifier to check ') if input in keyword.kwlist: print input + is keyword else: print input + is not keyword It works fine for me. Well, it did once I realized that 'keyword.py' was not a good name to save the file under. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: keyword checker - keyword.kwlist
From: [EMAIL PROTECTED] F:\Ohjelmat\Python25\Lib\keyword.pyc That's your problem. Rename keyword.py to keywordcheck.py, and delete keyword.pyc in this directory, and it should work fine. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Simulating simple electric circuits
From: Bjoern Schliessmann Sounds more familiar than the analog approach. Maybe I misunderstood something ... but I can't transfer my problem to this way of thinking yet. My biggest problem is the fact that relays aren't really interested in voltage, but current. Also, I find it difficult to transfer this circuit logic to boolean logic I can contruct logic gates from. Sometimes, electric circuits are used in different directions. You shouldn't have to worry about current degrading. You apply a current to the relay's coil, and it passes through the coil to ground and triggers the relay. The relay's outputs open or close connections from the current source to the connected devices' inputs. The only time you'd have to worry about low currents is if a single relay is connected to a lot of device inputs, because the current is split across the inputs. From a logic standpoint, all you care about is whether each input and output is on or off. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Strange terminal behavior after quitting Tkinter application
From: Chris I'll admit to being surprised at seeing a claim that a tkinter application, started within an interactive session, without a mainloop, even runs... I could see it maybe happening from Idle, since Idle is running a tkinter mainloop, so the application bindings may have just become added widgets to the Idle loop (but of course, a second mainloop would conflict heavily). You can try by building a working Tkinter GUI interactively from the standard Python interpreter, and see that the GUI works (i.e. processes events) at the same time. If you build it as a class (such as the code in Chris's original post) it works; if you do it all directly, nothing happens until you run mainloop(). It works, but I'm not sure that it was intended to work that way. I think your problem is related to that difference. You'll probably be better off creating a new interpreter window as part of your program, if you really need access to the interpreter alongside your GUI. You may be able to extract IDLE's interpreter window and use it directly. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Strange terminal behavior after quitting Tkinter application
-Original Message- From: Chris Subject: Re: Strange terminal behavior after quitting Tkinter application Clicking 'Quit' or on the window's 'x' causes the application to quit without messing up the terminal. With root.mainloop() commented out, though, no combination of root.quit(), root.destroy(), and sys.exit() stops the terminal from getting messed up. So, I should call mainloop() for my application...except that I want to use the commandline, too, and calling mainloop() freezes the commandline. I wonder if there is another way to use the commandline and have a GUI? I couldn't find any clear information about that. Can you run it in the background? IIRC, if you put an ampersand ('') at the end of the command line, it will run as a background process and leave your command line available for other tasks. (The marker may be something other than , it's been a long, long time since I've used *nix in a gui environment.) --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: How to check if a string is empty in python?
-Original Message- From: [EMAIL PROTECTED] On May 4, 5:02 am, Jaswant [EMAIL PROTECTED] wrote: This is a simple way to do it i think s=hello if(len(s)==0): ... print Empty ... else: ... print s ... hello But you are still making the assumption that s is a string. (BTW, you need quotes around your example.) For example: print a,b 11 11 Can you tell which one is the string? I.e., which one had quotes around it? If you correctly assume that it was b, then yes, your example works. print len(b) 2 If you incorrectly assume it was a, then the example doesn't work. print len(a) Traceback (most recent call last): File pyshell#8, line 1, in module print len(a) TypeError: object of type 'int' has no len() You have to know that a variable is a string before you try to do a len(). Dynamic typing is a feature, but that doesn't relieve you of the necessary tests. Your point would be important if the question were How can I tell if x is an empty string? On the other hand, How to check if a string is empty? implies that the OP already knows it is a string. Maybe he's been using string methods on it, maybe he got it from a function that he knows provides a string. Maybe he's checked its type. It doesn't really matter, if he's aware it is a string he doesn't have to test it for stringness. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: re-importing modules
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of John Nagle Sent: Monday, April 30, 2007 7:32 PM To: python-list@python.org Subject: Re: re-importing modules [EMAIL PROTECTED] wrote: In addition to the warning that reload() does not recursively reload modules that the reloaded module depends on, be warned that reloading a module does not magically affect any functions or objects from the old version that you may be holding on to. Maybe reloading modules should be deprecated. The semantics are awful, and it interferes with higher-performance implementations. I'd rather it weren't, personally. I'm using Python with a third-party application that provides an interactive prompt. Removing reload() would mean spending a good three minutes waiting for the application to restart any time I make the slightest change in a module supporting that application. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Dict Copy Compare
-Original Message- From: Steven D'Aprano Sent: Monday, April 30, 2007 10:14 PM To: python-list@python.org Subject: RE: Dict Copy Compare On Mon, 30 Apr 2007 12:50:58 -0500, Hamilton, William wrote: On quick question, how can I order a dict by the 'values' (not keys) before looping? Is that possible? The easiest way I can think of is to create a new dict that's reversed. reverseDict = {} for key in dict1: if dict1[key] not in reverseDict: reverseDict[dict1[key]]=[key] else: reverseDict[dict1[key]].append(key) This gives you a dictionary that has the old dict's values as keys, and the old dict's keys as lists of values. You can then sort the keys of this dict and do what you want with it. Of course, the values in dict1 have to be valid dictionary keys for this to work. If they aren't, you may be able to get away with converting them to strings. Oh man, maybe you need to re-think what you consider easier. for value in dict1.itervalues() do_something_with(value) This iterates through a list of values, with no information about the keys at all. Not particularly applicable to the OP's needs. If you need the keys as well: for key, value in dict1.iteritems() do_something_with(key, value) This iterates through values and keys, in no particular order. Still not useful. If you need to process the values (say, sort them) first: pairs = list(dict1.iteritems()) # or dict1.items() pairs.sort() for key, value in pairs: do_something_with(key, value) I'll leave sorting by value instead of key as an exercise. Hrmm. Maybe you missed the part where the OP was asking how to sort a dict's contents by value? I'm pretty sure I quoted it. My bit of code would be better if I had used iteritems() (I hadn't come across that function yet). But, it's a solution, and more useful than vague statements about what someone else needs to rethink and various bits of code that don't solve the problem presented. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: import structures
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of spohle Sent: Monday, April 30, 2007 10:03 AM To: python-list@python.org Subject: Re: import structures On Apr 30, 8:00 am, Paul McGuire [EMAIL PROTECTED] wrote: On Apr 30, 9:56 am, spohle [EMAIL PROTECTED] wrote: hi, i have written a small project for myself all in seperate classes and each of the classes lives in a seperate file. now i am looking for an import structure something like import wx, and then have access to all my classes just like wx.Button or wx.BoxSizer etc. as of now i have a __init__.py file in the directory with: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) but i still have to import each class by it's own. im really looking for something like import wx and then get all my access right away under this new namespace. thank you in advance If it really is a small project, consider just putting all the classes into a single module, say spohlePkg.py. Then your users would import this module using import spohlePkg, and would access the classes as spohlePkg.ClassA, spohlePkg.ClassB, etc. -- Paul yeah i had that, but my classes grew really fast and i decided to split them up. but you're right that in one file that would solve my problem. still hoping to find a way for the seperate files. If you've got modules a, b, and c, you can create a wrapper module d that imports from each of those. from a import * from b import * from c import * Then, import d and use it as the module name. So if a had a SomeThing class, you could do this: import d x = d.SomeThing() --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: import structures
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of spohle Sent: Monday, April 30, 2007 10:25 AM To: python-list@python.org Subject: Re: import structures On Apr 30, 8:16 am, Hamilton, William [EMAIL PROTECTED] wrote: If you've got modules a, b, and c, you can create a wrapper module d that imports from each of those. from a import * from b import * from c import * Then, import d and use it as the module name. So if a had a SomeThing class, you could do this: import d x = d.SomeThing() --- -Bill Hamilton that doesn't seem to work for me. the from a import * will only give me a not d.a from blah import * puts everything in blah into the current module's namespace (or so I understand it). This is different from import blah: with the latter, you have to use x = blah.SomeThing(). With the former, you can simply say x = SomeThing(). So, if a has a class SomeThing, and you import it into d using from a import *, in d you can use SomeThing's methods directly. If you then use import d in your main script, you can create a SomeThing instance with x = d.SomeThing(). --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Dict Copy Compare
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Robert Rawlins - Think Blue Sent: Monday, April 30, 2007 6:09 AM To: 'Tim Golden' Cc: python-list@python.org Subject: RE: Dict Copy Compare On quick question, how can I order a dict by the 'values' (not keys) before looping? Is that possible? The easiest way I can think of is to create a new dict that's reversed. reverseDict = {} for key in dict1: if dict1[key] not in reverseDict: reverseDict[dict1[key]]=[key] else: reverseDict[dict1[key]].append(key) This gives you a dictionary that has the old dict's values as keys, and the old dict's keys as lists of values. You can then sort the keys of this dict and do what you want with it. Of course, the values in dict1 have to be valid dictionary keys for this to work. If they aren't, you may be able to get away with converting them to strings. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Python keywords
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of gtb Sent: Thursday, April 26, 2007 1:50 PM To: python-list@python.org Subject: Re: Python keywords On Apr 26, 10:16 am, Larry Bates [EMAIL PROTECTED] wrote: http://docs.python.org/ref/keywords.html in keyword is a general one and can be used for many objects. x in 'xyz' y in ['a','b','c','y','z''] z in ('a','b','c','y','z'] key in {'key1':1, 'key2': 2} The in you see with a for isn't associated with the for loop but rather the sequence you are iterating over for i in range(10): -Larry Thanks Larry. I saw that page you referenced above and that is how I knew it was a keyword. But I still have found nodocumentation that supports the examples you provided. http://docs.python.org/ref/comparisons.html#l2h-438 This information is 2 clicks away from any page in the reference: click the index link, then scroll down to the link to in operator. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Tutorial creates confusion about slices
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Antoon Pardon Sent: Tuesday, April 24, 2007 7:40 AM To: python-list@python.org Subject: Re: Tutorial creates confusion about slices On 2007-04-24, Michael Bentley [EMAIL PROTECTED] wrote: On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote: People don't read tutorials in a strictly linear fashion. They can continue to later subjects and then come back here to see how things tie together. So the fact that it is only confusing to those who know more than is already presented doesn't seem a very good reason to leave it in. Yet they understand that earlier in the document, there is likely to be a less complete coverage of a given topic. There is in fact, a link on that page that includes a more complete coverage of that topic (which I mentioned to you in an earlier message IIRC). That there is more complete coverage elsewhere is no good reason to come with an explanation that suggests things working in a way that will be contradicted by that more complete coverage. Even after people have read the more complete coverage it is still very possible that they will come back to this part of the text and get the wrong idea of how things work. That's how everything I've ever learned has been taught. Start with a simple explanation that may not be completely accurate but is functional, then fill in the details later when there is a context to put them in. The tutorial could start out by explaining everything at the implementation level; it doesn't because it is a _tutorial_, intended to give new users the context they need to understand the more complicated nuances of the language. If it covered every fiddly little detail, it wouldn't be a tutorial. It would be a language reference document instead. A more complete coverage elsewhere is not an adequate remedy for a tekst suggesting things working differently than they actually do. Sure in the long run people will figger out how things actually work and that the explanation given in that section is totally inadequate for negative steps. But I prefer that people don't loose too much time figgering out that a particular explanation only works for particular cases and not in general. Submit a patch if you want it changed. I'm sure your valuable insights will greatly improve the quality of the python documentation. Fat chance, if they reason like you. So you're saying your insights aren't valuable? --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Tutorial creates confusion about slices
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Antoon Pardon Sent: Monday, April 23, 2007 7:38 AM To: python-list@python.org Subject: Tutorial creates confusion about slices The following is part of the explanation on slices in the tutorial: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is all very well with a simple slice like: HelpA[2:4]= lp But it give the wrong idea when using the following extended slice: HelpA[4:2:-1] = Ap So this doesn't result in the reverse of the previous expression while the explanation above suggest it does. It makes sense if you recognize that the negative step value also flips which side the index is on. +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 -6 -5 -4 -3 -2 -1 --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: Iterate through a dictionary of lists one line at a time
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of wswilson Sent: Wednesday, April 18, 2007 1:39 PM To: python-list@python.org Subject: Iterate through a dictionary of lists one line at a time Here is my code: listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} I need to output: id name a Joe b Jane c Bob I could do: print 'id', 'name' for id, name in zip(listing['id'], listing['name']): print id, name but that only works if there are two entries in the dictionary, id and name, and I know what they are. My problem is I don't know how many of these entries there will be. Thanks for any help you can give! for x in xrange(len(listing['id'])): ... print ... for key in listing.keys(): ... print listing[key][x], a Joe b Jane c Bob --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: tuples, index method, Python's design
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Steven D'Aprano Sent: Wednesday, April 11, 2007 7:49 AM To: python-list@python.org Subject: Re: tuples, index method, Python's design (There is one other option: you care that 32 is somewhere in the tuple, but you don't care where. That's when you use the in operator.) Anyway, that was the original design. When you see tuple, think struct. If you have a struct, it doesn't make a whole lot of sense to ask which field contains 32?, and so according to this intended usage, giving tuples index and count methods would be a Bad Idea: it just makes extra work for the Python Dev team, for no benefit. Personally, I think that tuples do double-duty as *both* immutable lists and structs/records. So even though index and count methods don't make sense for a struct, it does make sense for an immutable list, and I for one would not object to seeing tuples grow those two methods. From another function, you receive a tuple of data that it extracted from a stream. Within that tuple is a marker that indicates where the head of the incoming stream's data structure is. You need to find the marker and scan from that location on to sync your local data structure to the incoming stream's data. Should the external function provide the stream data in a list rather than a tuple? Probably, but someone else wrote the function so that's out of your control. Can you cast the tuple to a list? Sure, but for a large tuple that's potentially a large speed and memory hit. That probably the biggest general use case for tuple.index(). A third-party module returns a tuple in which you need to find a piece of data. --- -Bill Hamilton [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: passing class by reference does not work??
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of wswilson Sent: Wednesday, April 11, 2007 9:24 AM To: python-list@python.org Subject: passing class by reference does not work?? Here is my code: class A(): val = 0 def b(item, a): a.val = a.val + 1 return item + a.val def c(): d = [1, 2, 3] print [b(item, A()) for item in d] c() I expected this to output [2, 4, 6]. However, it outputs [2, 3, 4] which is not what I wanted. I thought that if I passed the A() instance in my list comprehension in c(), then the changes I made to a.val in b() would be reflected in the A() instance next time the list comprehension called b(). But, obviously that is not happening. I'm kinda new at python so I may be missing something obvious here. Any suggestions? A() is not the class A. It calls the constructor of class A, returning an instance. If you change that line to: print [b(item, A) for item in d] you'll get the output you expected. --- -Bill Hamilton [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: pop() clarification
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Scott I understand all that. What I don't understand is why all the documentation I see says, When removing a specific element from a list using pop() it must be in this format: list.pop([i]). At first I took that to mean that list.pop(i) would return some type of error, but it doesn't. I can't find any documentation saying that this rule that I keep reading about (again list.pop([i]) ) is the only format to use when removing a specific element because..with the explaination to follow. I believe that the [i] notation is to indicate that it has to be a valid index to your list. If i isn't a valid index, you get an IndexError. spam=['this', 'is', 'a', 'list'] spam.pop(1) 'is' spam.pop(4) Traceback (most recent call last): File pyshell#10, line 1, in -toplevel- spam.pop(4) IndexError: pop index out of range --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: tuples, index method, Python's design
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Chris Mellon Sent: Wednesday, April 11, 2007 9:12 AM To: python-list@python.org Subject: Re: tuples, index method, Python's design So, when you have a) a third party module that you cannot change and b) it shouldn't return a tuple but it does anyway and c) it's a big enough tuple that is large enough that conversion to a list is prohibitive, that's a general use case for tuple.index? Has this supposedly general and common use case actually happened? To me? No. Is it reasonable to believe it could happen? Yes. Is it reasonable to say, We don't think this is likely to happen often, so we won't provide a simple way to deal with it? Well, I'm not a developer, so it's not my decision. --- -Bill Hamilton [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Project organization and import redux
I apologize for bringing up something that's a month dead. But, I've been reading through the recent archives and came across this discussion, and want to make sure I understand a particular about the interactive prompt. Martin Unsal martinunsal at gmail.com wrote: I'm perfectly well aware that I'm not going to be able to reload a widget in the middle of a running GUI app, for example. I'm not looking for gotcha free, I'll settle for minimally useful. Here's an analogy. In C, you can do an incremental build and run your modified application without having to first reboot your computer. In Python, where reload() is essentially the incremental build process, and the interpreter is essentially a virtual machine, you guys are saying that my best option is to just reboot the virtual machine to make sure I have a clean slate. It may be the path of least resistance, but to say that it is necessary or inevitable is 1960s mainframe thinking. Yes, the interpreter is a virtual machine. But the interactive prompt is not a command line in that virtual machine. Instead, it is the statement that is about to be executed by a program running in that virtual machine. When you type a statement and press enter, that statement is executed as the next line of the program. It's analogous to using a debugger to step through a C program line by line, except you're providing those lines immediately rather than having to write and compile them in advance. Restarting the interactive prompt isn't like rebooting the computer; it's just restarting a program that is running on the computer. At worst, the interpreter is a computer that automatically shuts down when the program running on it ends. Is this a valid understanding of the workings of the interactive prompt, or am I way off base? --- -Bill Hamilton [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping issues
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of [EMAIL PROTECTED] Sent: Thursday, April 05, 2007 1:01 PM To: python-list@python.org Subject: Looping issues What I am trying to do is compare two files to each other. If the 2nd file contains the same line the first file contains, I want to print it. I wrote up the following code: correct_settings = open(C:\Python25\Scripts\Output \correct_settings.txt,r) current_settings = open(C:\Python25\Scripts\Output\output.txt,r) for line in correct_settings: for val in current_settings: if val == line: print line + found. correct_settings.close() current_settings.close() For some reason this only looks at the first line of the correct_settings.txt file. Any ideas as to how i can loop through each line of the correct_settings file instead of just looking at the first? = I think the problem is that it's actually only looping through current_settings once; for the remaining lines in correct_settings, current_settings is at EOF and produces nothing to be matched. for line in correct_settings: if line in current_settings: print line + found. This may do what you want. --- -Bill Hamilton [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Objects, lists and assigning values
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Manuel Graune Sent: Thursday, April 05, 2007 12:14 PM To: python-list@python.org Subject: Objects, lists and assigning values Hello, while trying to learn how to program using objects in python (up to now simple scripts were sufficient for my needs) I stumbled over the a problem while assigning values to an object. The following piece of code shows what I intend to do: ---snip--- class new_class(object): def __init__( self, internal_list=[]): self.internal_list= internal_list external_list=[[b*a for b in xrange(1,5)] for a in xrange(1,5)] print external_list first_collection=[new_class() for i in xrange(4)] temporary_list=[[] for i in xrange(4)] for i in xrange(4): for j in xrange(4): temporary_list[i].append(external_list[i][j]) first_collection[i].internal_list=temporary_list[i] #Now everything is as I want it to be: for i in xrange(4): print first_collection[i].internal_list #Now I tried to get the same result without the temporary #variable: second_collection=[new_class() for i in xrange(4)] for i in xrange(4): for j in xrange(4): second_collection[i].internal_list.append(external_list[i][j]) #Which obviously leads to a very different result: for i in xrange(4): print second_collection[i].internal_list ---snip--- Can someone explain to me, what's happening here and why the two approaches do not lead to the same results? Thanks in Advance. Changing the definition of the class init function to: def __init__( self, internal_list=None): if internal_list: self.internal_list= internal_list else: self.internal_list= [] fixes it. The list in the default parameter of your version is created once; every time an instance of the class is created, the self.internal_list in that new class is assigned the same list instance as all the other class instances. When you append something to any of those classes' lists, all of the classes' lists appear to change because they're all actually the same list. Your first_collection works because you're reassigning the class parameter to a new list. The second_collection doesn't work because you're appending to the (flawed) existing list assignment. --- -Bill Hamilton [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Python script produces sem_trywait: Permission denied
Hi, I've seen this question posted many places arount the Internet, but I've not seen any answers. We've been seeing this same error for some time, probably as long as Hudson has (given that it's now mid-October 2005); we just ignored it, since it didn't seem to cause problems. However, if anyone does have a solution to it I'd like to see it. I hate having unresolved wierdnesses in our code. -- Mark E. Hamilton Orion International Technologies, Inc. Sandia National Laboratory, NM. 505-844-7666 -- http://mail.python.org/mailman/listinfo/python-list
Python script produces sem_trywait: Permission denied
Sorry, I probably should have re-stated the problem: We're using Python 2.3.5 on AIX 5.2, and get the follow error messages from some of our code. I haven't yet tracked down exactly where it's coming from: sem_trywait: Permission denied sem_wait: Permission denied sem_post: Permission denied We don't run these scripts as root, so I can't say whether they work as root. I suspect they would, though, since root has permissions to do anything. -- Mark E. Hamilton Orion International Technologies, Inc. Sandia National Laboratory, NM. 505-844-7666 -- http://mail.python.org/mailman/listinfo/python-list