content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
---|---|---|---|---|---|---|---|---|
Q:
How to access the session object in Django Syndication framework code
Quick question. In my syndication feed framework code,
http://docs.djangoproject.com/en/dev/ref/contrib/syndication/
what is the best way to get access to the session? I don't have
access to the request, and I can't use
from django.contrib.sessions.backends.db import SessionStore
as I don't know the session ID, but I need to access some of the
variables in the session.
i.e. I have:
from django.contrib.syndication.feeds import Feed
class LatestPhotos(Feed):
...
and in that LatestPhotos class, I need to access something in the session to help control the logic flow. I can't find any documentation on the best way to do it.
Thanks
Thanks!
A:
It seems like a design flaw to be trying to access session data in the LatestPhoto's class. I would assume that if your syndication feed depended on a session variable, then the items you're syndicating (LatestPhotos) should be constructed with that variable?
Can you make the logic flow decision before you construct the LatestPhotos object, or at the very least pass the session ID in to the LatestPhotos init routine?
A:
Figured it out - drrr, so simple. The syndication framework Feed class has a member called request...so simple I never thought of it :)
[this comment applies to django 1.1 and earlier syndication framework]
|
How to access the session object in Django Syndication framework code
|
Quick question. In my syndication feed framework code,
http://docs.djangoproject.com/en/dev/ref/contrib/syndication/
what is the best way to get access to the session? I don't have
access to the request, and I can't use
from django.contrib.sessions.backends.db import SessionStore
as I don't know the session ID, but I need to access some of the
variables in the session.
i.e. I have:
from django.contrib.syndication.feeds import Feed
class LatestPhotos(Feed):
...
and in that LatestPhotos class, I need to access something in the session to help control the logic flow. I can't find any documentation on the best way to do it.
Thanks
Thanks!
|
[
"It seems like a design flaw to be trying to access session data in the LatestPhoto's class. I would assume that if your syndication feed depended on a session variable, then the items you're syndicating (LatestPhotos) should be constructed with that variable?\nCan you make the logic flow decision before you construct the LatestPhotos object, or at the very least pass the session ID in to the LatestPhotos init routine?\n",
"Figured it out - drrr, so simple. The syndication framework Feed class has a member called request...so simple I never thought of it :)\n[this comment applies to django 1.1 and earlier syndication framework]\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0000972267_django_python.txt
|
Q:
Python and reading lines
When i run an .exe file it prints stuff out to the screen. I don't know the specific line of where i want printed out but is there a way I can get python to print the next line after one that says "Summary" ? I know that is in there when it prints and I need the info right after. Thanks!
A:
Really simple Python solution:
def getSummary(s):
return s[s.find('\nSummary'):]
This returns everything after the first instance of Summary
If you need to be more specific, I'd recommend regular expressions.
A:
actually
program.exe | grep -A 1 Summary
would do your job.
A:
If the exe prints to screen then pipe that output to a text file. I have assumed the exe is on windows, then from the command line:
myapp.exe > output.txt
And your reasonably robust python code would be something like:
try:
f = open("output.txt", "r")
lines = f.readlines()
# Using enumerate gives a convenient index.
for i, line in enumerate(lines) :
if 'Summary' in line :
print lines[i+1]
break # exit early
# Python throws this if 'Summary' was there but nothing is after it.
except IndexError, e :
print "I didn't find a line after the Summary"
# You could catch other exceptions, as needed.
finally :
f.close()
|
Python and reading lines
|
When i run an .exe file it prints stuff out to the screen. I don't know the specific line of where i want printed out but is there a way I can get python to print the next line after one that says "Summary" ? I know that is in there when it prints and I need the info right after. Thanks!
|
[
"Really simple Python solution:\ndef getSummary(s):\n return s[s.find('\\nSummary'):]\n\nThis returns everything after the first instance of Summary\nIf you need to be more specific, I'd recommend regular expressions.\n",
"actually \nprogram.exe | grep -A 1 Summary \n\nwould do your job.\n",
"If the exe prints to screen then pipe that output to a text file. I have assumed the exe is on windows, then from the command line: \n\nmyapp.exe > output.txt\n\nAnd your reasonably robust python code would be something like:\ntry:\n f = open(\"output.txt\", \"r\")\n lines = f.readlines()\n # Using enumerate gives a convenient index.\n for i, line in enumerate(lines) :\n if 'Summary' in line :\n print lines[i+1]\n break # exit early\n# Python throws this if 'Summary' was there but nothing is after it.\nexcept IndexError, e :\n print \"I didn't find a line after the Summary\"\n# You could catch other exceptions, as needed.\nfinally :\n f.close()\n\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"command_prompt",
"printing",
"python"
] |
stackoverflow_0000970975_command_prompt_printing_python.txt
|
Q:
Why is Logging going in an infinite Loop?
I have the following code:
#!/usr/bin/env python
import logging
import sys
import copy
class Wrapper:
def write(self, s):
#sys.__stdout__.write(s)
loggy = logging.getLogger('foobar')
loggy.info(s)
def blah():
logger = logging.getLogger('foobar')
logger.setLevel(logging.DEBUG)
streamhandle = logging.StreamHandler(sys.stdout)
streamhandle.setFormatter(logging.Formatter('[%(message)s]'))
logger.addHandler(streamhandle)
sys.stdout = Wrapper()
sys.stderr = Wrapper()
if __name__ == '__main__':
blah()
logger = logging.getLogger('')
#print logger.handlers
#for handler in logger.handlers:
# print handler
fooy = logging.getLogger('foobar')
#print fooy.handlers
sys.stdout.write('i love you')
logging.log(logging.DEBUG, 'i love you')
This code causes python to go in an infinite recursive loop, and the output is actually incredibly cool:
[Error in sys.exitfunc:
]
[INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc:
This keeps growing exponentially :) Its pretty but why is this happening?
A:
The infinite loop is happening because your logger's StreamHandler is set to write its log messages to sys.stdout, but sys.stdout is in turn wrapped and writes back to the very logger that just sent it a write message.
Depending on your goals, you're probably better having the Wrapper actually perform output, rather than use logging internally. Something like:
class Wrapper(object):
def write(self, s):
sys.__stdout__.write(s) # sys.__stdout__ points to the original stdout, rather
# than the redirected sys.stdout
|
Why is Logging going in an infinite Loop?
|
I have the following code:
#!/usr/bin/env python
import logging
import sys
import copy
class Wrapper:
def write(self, s):
#sys.__stdout__.write(s)
loggy = logging.getLogger('foobar')
loggy.info(s)
def blah():
logger = logging.getLogger('foobar')
logger.setLevel(logging.DEBUG)
streamhandle = logging.StreamHandler(sys.stdout)
streamhandle.setFormatter(logging.Formatter('[%(message)s]'))
logger.addHandler(streamhandle)
sys.stdout = Wrapper()
sys.stderr = Wrapper()
if __name__ == '__main__':
blah()
logger = logging.getLogger('')
#print logger.handlers
#for handler in logger.handlers:
# print handler
fooy = logging.getLogger('foobar')
#print fooy.handlers
sys.stdout.write('i love you')
logging.log(logging.DEBUG, 'i love you')
This code causes python to go in an infinite recursive loop, and the output is actually incredibly cool:
[Error in sys.exitfunc:
]
[INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc:
]
[INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:INFO:foobar:Error in sys.exitfunc:
This keeps growing exponentially :) Its pretty but why is this happening?
|
[
"The infinite loop is happening because your logger's StreamHandler is set to write its log messages to sys.stdout, but sys.stdout is in turn wrapped and writes back to the very logger that just sent it a write message.\nDepending on your goals, you're probably better having the Wrapper actually perform output, rather than use logging internally. Something like:\nclass Wrapper(object):\n def write(self, s):\n sys.__stdout__.write(s) # sys.__stdout__ points to the original stdout, rather\n # than the redirected sys.stdout\n\n"
] |
[
6
] |
[] |
[] |
[
"logging",
"python"
] |
stackoverflow_0000975456_logging_python.txt
|
Q:
What is the proper way to compute the fully expanded width of wx.TreeCtrl
The preferred size of the wx.TreeCtrl seems to be the minimum size into which all elements will fit when the tree is completely collapsed. Is there a good (ie cross-platform compatible) way to compute the width of the tree with everything expanded? My current solution is this:
def max_width(self):
dc = wx.ScreenDC()
dc.SetFont(self.GetFont())
widths = []
for item, depth in self.__walk_items():
if item != self.root:
width = dc.GetTextExtent(self.GetItemText(item))[0] + self.GetIndent()*depth
widths.append(width)
return max(widths) + self.GetIndent()
This works great in win32, but no good under linux. Is there some way to get the TreeCtrl itself to tell me its size so that I can override the size it reports? (ALways returning the maximally expanded width)
edit: pardon me for not providing the functions I use above, but you get the idea, I'm walking the tree, and getting the width of every label, and returning the total width of the widest one (accounting for indent)
A:
I find that the GetBestSize seems to consider the collapsed items. For example, with the wxTreeCtrl in the demo (using Ubuntu, and wxPython 2.8.7.1), when I change the length of the inner text string (line 74 in my version of the demo) the return value of self.tree.GetBestSize() does take this new length of the inner string into account, even though the tree is unexpanded. Maybe you need to call SetQuickBestSize(False)?
A:
This code works for me on both windows and linux:
def compute_best_size(self):
if os.name == 'nt':
best_size = (self.__max_width_win32(), -1)
else:
best_size = (self.__max_width(), -1)
self.SetMinSize(best_size)
def __max_width_win32(self):
dc = wx.ScreenDC()
dc.SetFont(self.GetFont())
widths = []
for item, depth in self.__walk_items():
if item != self.root:
width = dc.GetTextExtent(self.GetItemText(item))[0] + self.GetIndent()*depth
widths.append(width)
return max(widths) + self.GetIndent()
def __max_width(self):
self.Freeze()
expanded = {}
for item in self.get_items():
if item is not self.root:
expanded[item] = self.IsExpanded(item)
self.ExpandAll()
best_size = self.GetBestSize()
for item in expanded:
if not expanded[item]: self.Collapse(item)
self.Thaw()
return best_size[0]
... And call compute_best_size() every time a new item is added to the tree.
|
What is the proper way to compute the fully expanded width of wx.TreeCtrl
|
The preferred size of the wx.TreeCtrl seems to be the minimum size into which all elements will fit when the tree is completely collapsed. Is there a good (ie cross-platform compatible) way to compute the width of the tree with everything expanded? My current solution is this:
def max_width(self):
dc = wx.ScreenDC()
dc.SetFont(self.GetFont())
widths = []
for item, depth in self.__walk_items():
if item != self.root:
width = dc.GetTextExtent(self.GetItemText(item))[0] + self.GetIndent()*depth
widths.append(width)
return max(widths) + self.GetIndent()
This works great in win32, but no good under linux. Is there some way to get the TreeCtrl itself to tell me its size so that I can override the size it reports? (ALways returning the maximally expanded width)
edit: pardon me for not providing the functions I use above, but you get the idea, I'm walking the tree, and getting the width of every label, and returning the total width of the widest one (accounting for indent)
|
[
"I find that the GetBestSize seems to consider the collapsed items. For example, with the wxTreeCtrl in the demo (using Ubuntu, and wxPython 2.8.7.1), when I change the length of the inner text string (line 74 in my version of the demo) the return value of self.tree.GetBestSize() does take this new length of the inner string into account, even though the tree is unexpanded. Maybe you need to call SetQuickBestSize(False)?\n",
"This code works for me on both windows and linux:\ndef compute_best_size(self):\n if os.name == 'nt':\n best_size = (self.__max_width_win32(), -1)\n else:\n best_size = (self.__max_width(), -1)\n self.SetMinSize(best_size)\n\ndef __max_width_win32(self):\n dc = wx.ScreenDC()\n dc.SetFont(self.GetFont())\n widths = []\n for item, depth in self.__walk_items():\n if item != self.root:\n width = dc.GetTextExtent(self.GetItemText(item))[0] + self.GetIndent()*depth\n widths.append(width)\n return max(widths) + self.GetIndent()\n\ndef __max_width(self):\n self.Freeze()\n expanded = {}\n for item in self.get_items():\n if item is not self.root:\n expanded[item] = self.IsExpanded(item)\n self.ExpandAll()\n best_size = self.GetBestSize()\n for item in expanded:\n if not expanded[item]: self.Collapse(item)\n self.Thaw()\n return best_size[0]\n\n... And call compute_best_size() every time a new item is added to the tree.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"size",
"wxpython"
] |
stackoverflow_0000960489_python_size_wxpython.txt
|
Q:
Distributing Ruby/Python desktop apps
Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?
I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.
RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.
Generally — what is the current fad?
BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.
A:
I don't know about ruby2exe, but py2exe works perfeclty fine. Even with librairies like wxWidgets. Edit: you don't even have to ask the user to install wxWidgets, it's bundled with the app (same goes for py2app)
I use it for my very small project here.
For the Mac crowd, py2app works fine too with wxWidgets.
A:
For Ruby, the One-Click Ruby Application Builder (OCRA) is emerging as the successor to RubyScript2Exe.
Ocra works with both Ruby 1.8.6 and 1.9.1, and with wxRuby. Supports LZMA compression for relatively compact executables.
A:
I don't know about Ruby, but the standard for Python is py2exe to create Windows binaries. For me, the cross-plattform pyinstaller has worked well, once. For your GUI, TkInter is the standard. A lot of people like wxPython. All those are fairly actively developed. I suggest playing a little bit around with these options to decide whether Python is the better choice.
A:
The state of affairs is pretty bad. The most reliable method at present is probably to use JRuby. I know that's probably not the answer you want to hear, but, as you say, ruby2exe is unreliable, and Shoes is a long way off (and isn't even intended to be a full-scale application). Personally, I dislike forcing users to install GTK or Qt or wxWidgets, but the JVM is fairly ubiquitous.
A:
Depending on how far you development is, Shoes is pretty good. Its basically it's own Ruby Distribution. It may be a bit hidden (in the files menu), but it allows you to package your application for all 3 platforms without having that Shoes startup screen.
The rendering engine behind it is Cairo.
A:
I don't think anyone really answered his question.
As for me, I use VB to do Shell() calls to Ocra compiled Ruby scripts.
It works pretty well and allows me to create apps that run in all modern OS.
Linux testing is done by using Wine to run and ensuring that I use a pre .NET version of VB for the .exe compilation.
|
Distributing Ruby/Python desktop apps
|
Is there any way besides Shoes to develop and distribute cross-platform GUI desktop applications written in Ruby?
I come to believe that general bugginess of _why's applications is exceptionally crippling in case of Shoes, and anything more complex than a two-button form is a pain to maintain.
RubyGTK, wxRuby, etc seem to be promising, but they do not solve the issue of distributing an app in a way that doesn't require Ruby pre-installed on users' computers — and libraries like ruby2exe seem to be horribly out-of-date and incomplete.
Generally — what is the current fad?
BTW: if there is a really easy solution to this in Python, I may consider redoing the stuff I'm up to in Python.
|
[
"I don't know about ruby2exe, but py2exe works perfeclty fine. Even with librairies like wxWidgets. Edit: you don't even have to ask the user to install wxWidgets, it's bundled with the app (same goes for py2app)\nI use it for my very small project here.\nFor the Mac crowd, py2app works fine too with wxWidgets.\n",
"For Ruby, the One-Click Ruby Application Builder (OCRA) is emerging as the successor to RubyScript2Exe. \nOcra works with both Ruby 1.8.6 and 1.9.1, and with wxRuby. Supports LZMA compression for relatively compact executables.\n",
"I don't know about Ruby, but the standard for Python is py2exe to create Windows binaries. For me, the cross-plattform pyinstaller has worked well, once. For your GUI, TkInter is the standard. A lot of people like wxPython. All those are fairly actively developed. I suggest playing a little bit around with these options to decide whether Python is the better choice.\n",
"The state of affairs is pretty bad. The most reliable method at present is probably to use JRuby. I know that's probably not the answer you want to hear, but, as you say, ruby2exe is unreliable, and Shoes is a long way off (and isn't even intended to be a full-scale application). Personally, I dislike forcing users to install GTK or Qt or wxWidgets, but the JVM is fairly ubiquitous.\n",
"Depending on how far you development is, Shoes is pretty good. Its basically it's own Ruby Distribution. It may be a bit hidden (in the files menu), but it allows you to package your application for all 3 platforms without having that Shoes startup screen.\nThe rendering engine behind it is Cairo.\n",
"I don't think anyone really answered his question.\nAs for me, I use VB to do Shell() calls to Ocra compiled Ruby scripts.\nIt works pretty well and allows me to create apps that run in all modern OS.\nLinux testing is done by using Wine to run and ensuring that I use a pre .NET version of VB for the .exe compilation.\n"
] |
[
11,
8,
6,
2,
1,
0
] |
[
"I've read about (but not used) Seattlerb's Wilson, which describes itself as a pure x86 assembler, but it doesn't sound like it'd be cross-platform or GUI.\n"
] |
[
-2
] |
[
"desktop",
"python",
"ruby",
"software_distribution",
"user_interface"
] |
stackoverflow_0000940149_desktop_python_ruby_software_distribution_user_interface.txt
|
Q:
redirecting sys.stdout to python logging
So right now we have a lot of python scripts and we are trying to consolidate them and fix and redundancies. One of the things we are trying to do, is to ensure that all sys.stdout/sys.stderr goes into the python logging module.
Now the main thing is, we want the following printed out:
[<ERROR LEVEL>] | <TIME> | <WHERE> | <MSG>
Now all sys.stdout / sys.stderr msgs pretty much in all of the python error messages are in the format of [LEVEL] - MSG, which are all written using sys.stdout/sys.stderr. I can parse the fine, in my sys.stdout wrapper and in the sys.stderr wrapper. Then call the corresponding logging level, depending on the parsed input.
So basically we have a package called foo, and a subpackage called log. In __init__.py we define the following:
def initLogging(default_level = logging.INFO, stdout_wrapper = None, \
stderr_wrapper = None):
"""
Initialize the default logging sub system
"""
root_logger = logging.getLogger('')
strm_out = logging.StreamHandler(sys.__stdout__)
strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_TIME_FORMAT, \
DEFAULT_LOG_TIME_FORMAT))
root_logger.setLevel(default_level)
root_logger.addHandler(strm_out)
console_logger = logging.getLogger(LOGGER_CONSOLE)
strm_out = logging.StreamHandler(sys.__stdout__)
#strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_MSG_FORMAT, \
# DEFAULT_LOG_TIME_FORMAT))
console_logger.setLevel(logging.INFO)
console_logger.addHandler(strm_out)
if stdout_wrapper:
sys.stdout = stdout_wrapper
if stderr_wrapper:
sys.stderr = stderr_wrapper
def cleanMsg(msg, is_stderr = False):
logy = logging.getLogger('MSG')
msg = msg.rstrip('\n').lstrip('\n')
p_level = r'^(\s+)?\[(?P<LEVEL>\w+)\](\s+)?(?P<MSG>.*)$'
m = re.match(p_level, msg)
if m:
msg = m.group('MSG')
if m.group('LEVEL') in ('WARNING'):
logy.warning(msg)
return
elif m.group('LEVEL') in ('ERROR'):
logy.error(msg)
return
if is_stderr:
logy.error(msg)
else:
logy.info(msg)
class StdOutWrapper:
"""
Call wrapper for stdout
"""
def write(self, s):
cleanMsg(s, False)
class StdErrWrapper:
"""
Call wrapper for stderr
"""
def write(self, s):
cleanMsg(s, True)
Now we would call this in one of our scripts for example:
import foo.log
foo.log.initLogging(20, foo.log.StdOutWrapper(), foo.log.StdErrWrapper())
sys.stdout.write('[ERROR] Foobar blew')
Which would be converted into an error log message. Like:
[ERROR] | 20090610 083215 | __init__.py | Foobar Blew
Now the problem is when we do that, The module where the error message was logged is now the __init__ (corresponding to foo.log.__init__.py file) which defeats the whole purpose.
I tried doing a deepCopy/shallowCopy of the stderr/stdout objects, but that does nothing, it still says the module the message occured in __init__.py. How can i make it so this doesn't happen?
A:
The problem is that the logging module is looking a single layer up the call stack to find who called it, but now your function is an intermediate layer at that point (Though I'd have expected it to report cleanMsg, not __init__, as that's where you're calling into log()). Instead, you need it to go up two levels, or else pass who your caller is into the logged message. You can do this by inspecting up the stack frame yourself and grabbing the calling function, inserting it into the message.
To find your calling frame, you can use the inspect module:
import inspect
f = inspect.currentframe(N)
will look up N frames, and return you the frame pointer. ie your immediate caller is currentframe(1), but you may have to go another frame up if this is the stdout.write method.
Once you have the calling frame, you can get the executing code object, and look at the file and function name associated with it. eg:
code = f.f_code
caller = '%s:%s' % (code.co_filename, code.co_name)
You may also need to put some code to handle non-python code calling into you (ie. C functions or builtins), as these may lack f_code objects.
Alternatively, following up mikej's answer, you could use the same approach in a custom Logger class inheriting from logging.Logger that overrides findCaller to navigate several frames up, rather than one.
A:
I think the problem is that your actual log messages are now being created by the logy.error and logy.info calls in cleanMsg, hence that method is the source of the log messages and you are seeing this as __init__.py
If you look in the source of Python's lib/logging/__init__.py you will see a method defined called findCaller which is what the logging module uses to derive the caller of a logging request.
Perhaps you can override this on your logging object to customise the behaviour?
|
redirecting sys.stdout to python logging
|
So right now we have a lot of python scripts and we are trying to consolidate them and fix and redundancies. One of the things we are trying to do, is to ensure that all sys.stdout/sys.stderr goes into the python logging module.
Now the main thing is, we want the following printed out:
[<ERROR LEVEL>] | <TIME> | <WHERE> | <MSG>
Now all sys.stdout / sys.stderr msgs pretty much in all of the python error messages are in the format of [LEVEL] - MSG, which are all written using sys.stdout/sys.stderr. I can parse the fine, in my sys.stdout wrapper and in the sys.stderr wrapper. Then call the corresponding logging level, depending on the parsed input.
So basically we have a package called foo, and a subpackage called log. In __init__.py we define the following:
def initLogging(default_level = logging.INFO, stdout_wrapper = None, \
stderr_wrapper = None):
"""
Initialize the default logging sub system
"""
root_logger = logging.getLogger('')
strm_out = logging.StreamHandler(sys.__stdout__)
strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_TIME_FORMAT, \
DEFAULT_LOG_TIME_FORMAT))
root_logger.setLevel(default_level)
root_logger.addHandler(strm_out)
console_logger = logging.getLogger(LOGGER_CONSOLE)
strm_out = logging.StreamHandler(sys.__stdout__)
#strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_MSG_FORMAT, \
# DEFAULT_LOG_TIME_FORMAT))
console_logger.setLevel(logging.INFO)
console_logger.addHandler(strm_out)
if stdout_wrapper:
sys.stdout = stdout_wrapper
if stderr_wrapper:
sys.stderr = stderr_wrapper
def cleanMsg(msg, is_stderr = False):
logy = logging.getLogger('MSG')
msg = msg.rstrip('\n').lstrip('\n')
p_level = r'^(\s+)?\[(?P<LEVEL>\w+)\](\s+)?(?P<MSG>.*)$'
m = re.match(p_level, msg)
if m:
msg = m.group('MSG')
if m.group('LEVEL') in ('WARNING'):
logy.warning(msg)
return
elif m.group('LEVEL') in ('ERROR'):
logy.error(msg)
return
if is_stderr:
logy.error(msg)
else:
logy.info(msg)
class StdOutWrapper:
"""
Call wrapper for stdout
"""
def write(self, s):
cleanMsg(s, False)
class StdErrWrapper:
"""
Call wrapper for stderr
"""
def write(self, s):
cleanMsg(s, True)
Now we would call this in one of our scripts for example:
import foo.log
foo.log.initLogging(20, foo.log.StdOutWrapper(), foo.log.StdErrWrapper())
sys.stdout.write('[ERROR] Foobar blew')
Which would be converted into an error log message. Like:
[ERROR] | 20090610 083215 | __init__.py | Foobar Blew
Now the problem is when we do that, The module where the error message was logged is now the __init__ (corresponding to foo.log.__init__.py file) which defeats the whole purpose.
I tried doing a deepCopy/shallowCopy of the stderr/stdout objects, but that does nothing, it still says the module the message occured in __init__.py. How can i make it so this doesn't happen?
|
[
"The problem is that the logging module is looking a single layer up the call stack to find who called it, but now your function is an intermediate layer at that point (Though I'd have expected it to report cleanMsg, not __init__, as that's where you're calling into log()). Instead, you need it to go up two levels, or else pass who your caller is into the logged message. You can do this by inspecting up the stack frame yourself and grabbing the calling function, inserting it into the message.\nTo find your calling frame, you can use the inspect module:\nimport inspect\nf = inspect.currentframe(N)\n\nwill look up N frames, and return you the frame pointer. ie your immediate caller is currentframe(1), but you may have to go another frame up if this is the stdout.write method.\nOnce you have the calling frame, you can get the executing code object, and look at the file and function name associated with it. eg:\ncode = f.f_code\ncaller = '%s:%s' % (code.co_filename, code.co_name)\n\nYou may also need to put some code to handle non-python code calling into you (ie. C functions or builtins), as these may lack f_code objects.\nAlternatively, following up mikej's answer, you could use the same approach in a custom Logger class inheriting from logging.Logger that overrides findCaller to navigate several frames up, rather than one.\n",
"I think the problem is that your actual log messages are now being created by the logy.error and logy.info calls in cleanMsg, hence that method is the source of the log messages and you are seeing this as __init__.py\nIf you look in the source of Python's lib/logging/__init__.py you will see a method defined called findCaller which is what the logging module uses to derive the caller of a logging request.\nPerhaps you can override this on your logging object to customise the behaviour? \n"
] |
[
6,
2
] |
[] |
[] |
[
"logging",
"python"
] |
stackoverflow_0000975248_logging_python.txt
|
Q:
Perl and CopSSH
I'm trying to automate a process on a remote machine using a python script. The machine is a windows machine and I've installed CopSSH on it in order to SSH into it to run commands. I'm having trouble getting perl scripts to run from the CopSSH terminal. I get a command not found error. Is there a special way that I have to have perl installed in order to do this? Or does anyone know how to install perl with CopSSH?
A:
I suspect CopSSH is giving you different environment vars to a normal GUI login. I'd suggest you type 'set' and see if perl is in the path with any other environment vars it might need.
Here is some explanation of setting up the CopSSH user environment. It may be of use.
A:
I just realized CopSSH is based on Cygwin which I think means paths would have to be specified differently. Try using, for example,
/cygdrive/c/Program\ Files/My\ Program/myprog.exe
instead of
"C:\Program Files\My Program\myprog.exe".
BTW, the following CopSSH FAQ might be applicable as well: http://www.itefix.no/i2/node/31.
A:
Are you using ActiveState or Strawberry Perl? What error messages are you getting? You may find the answers to How do I run programs with Strawberry Perl helpful.
|
Perl and CopSSH
|
I'm trying to automate a process on a remote machine using a python script. The machine is a windows machine and I've installed CopSSH on it in order to SSH into it to run commands. I'm having trouble getting perl scripts to run from the CopSSH terminal. I get a command not found error. Is there a special way that I have to have perl installed in order to do this? Or does anyone know how to install perl with CopSSH?
|
[
"I suspect CopSSH is giving you different environment vars to a normal GUI login. I'd suggest you type 'set' and see if perl is in the path with any other environment vars it might need. \nHere is some explanation of setting up the CopSSH user environment. It may be of use.\n",
"I just realized CopSSH is based on Cygwin which I think means paths would have to be specified differently. Try using, for example, \n/cygdrive/c/Program\\ Files/My\\ Program/myprog.exe \ninstead of \n\"C:\\Program Files\\My Program\\myprog.exe\".\nBTW, the following CopSSH FAQ might be applicable as well: http://www.itefix.no/i2/node/31.\n",
"Are you using ActiveState or Strawberry Perl? What error messages are you getting? You may find the answers to How do I run programs with Strawberry Perl helpful.\n"
] |
[
4,
3,
2
] |
[] |
[] |
[
"openssh",
"perl",
"python",
"ssh"
] |
stackoverflow_0000975785_openssh_perl_python_ssh.txt
|
Q:
cx_Oracle And User Defined Types
Does anyone know an easier way to work with user defined types in Oracle using cx_Oracle?
For example, if I have these two types:
CREATE type my_type as object(
component varchar2(30)
,key varchar2(100)
,value varchar2(4000))
/
CREATE type my_type_tab as table of my_type
/
And then a procedure in package my_package as follows:
PROCEDURE my_procedure (param in my_type_tab);
To execute the procedure in PL/SQL I can do something like this:
declare
l_parms my_type_tab;
l_cnt pls_integer;
begin
l_parms := my_type_tab();
l_parms.extend;
l_cnt := l_parms.count;
l_parms(l_cnt) := my_type('foo','bar','hello');
l_parms.extend;
l_cnt := l_parms.count;
l_parms(l_cnt) := my_type('faz','baz','world');
my_package.my_procedure(l_parms);
end;
However, I was wondering how I can do it in Python, similar to this code:
import cx_Oracle
orcl = cx_Oracle.connect('foo:[email protected]:5555/blah' + instance)
curs = orcl.cursor()
params = ???
curs.execute('begin my_package.my_procedure(:params)', params=params)
If the parameter was a string I can do this as above, but since it's an user-defined type, I have no idea how to call it without resorting to pure PL/SQL code.
Edit: Sorry, I should have said that I was looking for ways to do more in Python code instead of PL/SQL.
A:
While cx_Oracle can select user defined types, it does not to my knowledge support passing in user defined types as bind variables. So for example the following will work:
cursor.execute("select my_type('foo', 'bar', 'hello') from dual")
val, = cursor.fetchone()
print val.COMPONENT, val.KEY, val.VALUE
However what you can't do is construct a Python object, pass it in as an input argument and then have cx_Oracle "translate" the Python object into your Oracle type. So I would say you're going to have to construct your input argument within a PL/SQL block.
You can pass in Python lists, so the following should work:
components=["foo", "faz"]
values=["bar", "baz"]
keys=["hello", "world"]
cursor.execute("""
declare
type udt_StringList is table of varchar2(4000) index by binary_integer;
l_components udt_StringList := :p_components;
l_keys udt_StringList := :p_keys;
l_values udt_StringList := :p_values;
l_parms my_type_tab;
begin
l_parms.extend(l_components.count);
for i in 1..l_components.count loop
l_parms(i) := my_type(l_components(i), l_keys(i), l_values(i));
end loop;
my_package.my_procedure(l_parms);
end;""", p_components=components, p_values=values, p_keys=keys)
A:
Are you trying to populate the table of objects more efficiently?
If you can do a SELECT, have a look at the BULK COLLECT INTO clause
|
cx_Oracle And User Defined Types
|
Does anyone know an easier way to work with user defined types in Oracle using cx_Oracle?
For example, if I have these two types:
CREATE type my_type as object(
component varchar2(30)
,key varchar2(100)
,value varchar2(4000))
/
CREATE type my_type_tab as table of my_type
/
And then a procedure in package my_package as follows:
PROCEDURE my_procedure (param in my_type_tab);
To execute the procedure in PL/SQL I can do something like this:
declare
l_parms my_type_tab;
l_cnt pls_integer;
begin
l_parms := my_type_tab();
l_parms.extend;
l_cnt := l_parms.count;
l_parms(l_cnt) := my_type('foo','bar','hello');
l_parms.extend;
l_cnt := l_parms.count;
l_parms(l_cnt) := my_type('faz','baz','world');
my_package.my_procedure(l_parms);
end;
However, I was wondering how I can do it in Python, similar to this code:
import cx_Oracle
orcl = cx_Oracle.connect('foo:[email protected]:5555/blah' + instance)
curs = orcl.cursor()
params = ???
curs.execute('begin my_package.my_procedure(:params)', params=params)
If the parameter was a string I can do this as above, but since it's an user-defined type, I have no idea how to call it without resorting to pure PL/SQL code.
Edit: Sorry, I should have said that I was looking for ways to do more in Python code instead of PL/SQL.
|
[
"While cx_Oracle can select user defined types, it does not to my knowledge support passing in user defined types as bind variables. So for example the following will work:\ncursor.execute(\"select my_type('foo', 'bar', 'hello') from dual\")\nval, = cursor.fetchone()\nprint val.COMPONENT, val.KEY, val.VALUE\n\nHowever what you can't do is construct a Python object, pass it in as an input argument and then have cx_Oracle \"translate\" the Python object into your Oracle type. So I would say you're going to have to construct your input argument within a PL/SQL block.\nYou can pass in Python lists, so the following should work:\ncomponents=[\"foo\", \"faz\"]\nvalues=[\"bar\", \"baz\"]\nkeys=[\"hello\", \"world\"]\ncursor.execute(\"\"\"\ndeclare\n type udt_StringList is table of varchar2(4000) index by binary_integer;\n l_components udt_StringList := :p_components;\n l_keys udt_StringList := :p_keys;\n l_values udt_StringList := :p_values;\n l_parms my_type_tab;\nbegin\n l_parms.extend(l_components.count);\n for i in 1..l_components.count loop\n l_parms(i) := my_type(l_components(i), l_keys(i), l_values(i));\n end loop;\n\n my_package.my_procedure(l_parms);\nend;\"\"\", p_components=components, p_values=values, p_keys=keys)\n\n",
"Are you trying to populate the table of objects more efficiently?\nIf you can do a SELECT, have a look at the BULK COLLECT INTO clause\n"
] |
[
3,
0
] |
[
"I'm not quite sure what you mean by hard-coded, but you can build a dynamic array like this:\nSQL> desc my_procedure\nParameter Type Mode Default? \n--------- ----------- ---- -------- \nP_IN MY_TYPE_TAB IN \n\nSQL> declare\n 2 l_tab my_type_tab;\n 3 begin\n 4 select my_type(owner, table_name, column_name)\n 5 bulk collect into l_tab\n 6 from all_tab_columns\n 7 where rownum <= 10;\n 8 my_procedure (l_tab);\n 9 end;\n 10 /\n\nPL/SQL procedure successfully completed\n\nThis has been tested with Oracle 11.1.0.6.\n"
] |
[
-1
] |
[
"cx_oracle",
"oracle",
"python"
] |
stackoverflow_0000971250_cx_oracle_oracle_python.txt
|
Q:
Eclipse + local CVS + PyDev
I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)
It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?
Regards and thanks in advance for any clues. Please forgive my English ;)
A:
Last time I tried this, Eclipse did not support direct access to local repositories in the same way that command line cvs does because command line cvs has both client and server functionality whereas Eclipse only has client functionality and needs to go through (e.g.) pserver, so you would probably need to have a cvs server running.
Turns out that I didn't really need it anyway as Eclipse keeps its own history of all changes so I only needed to do an occasional manual update to cvs at major milestones.
[Eventually I decided not to use cvs at all with Eclipse under Linux as it got confused by symlinks and started deleting my include files when it "synchronised" with the repository.]
A:
If you don't mind a switch to Subversion, Eclipse has its SubClipse plugin.
A:
I tried Eclipse+Subclipse and Eclipse+Bazaar plugin. Both work very well, but I have found that Tortoise versions of those version source control tools are so good that I resigned from Eclipse plugins. On Windows Tortoise XXX are my choice. They integrate with shell (Explorer or TotalCommander), changes icon overlay if file is changed, shows log, compare revisions etc. etc.
A:
As others have indicated, there are plugins available for Eclipse for SVN, Bazar, Mercurial and Git.
Even so, despite their presence, I find using the command line the most comfortable.
svn commit -m 'now committing'
Assuming you are not committing for more than several times a day, this should work well enough. Is there anything specific that is preventing you from using the command line?
A:
I would definitely recommend switching over to a different VCS—I prefer Mercurial, along with a lot of the Python community. That way, you'll be able to work locally, but still have the ability to publish your changes to the world later.
You can install TortoiseHg for Windows Explorer, and the MercurialEclipse plugin for Eclipse.
There's even a Mercurial for CVS users document to help you change over, and a list of mostly-equivalent commands.
A:
I believe Eclipse does have CVS support built in - or at least it did have when I last used it a couple of years ago.
For further information on how to use CVS with Eclipse see the Eclipse CVS FAQ
A:
I recently moved my house and don't have yet an access to internet.
CVS and SVN are the Centralized Version control systems. Rather than having to install them on your local system just for single version control, you could use DVCS like Mercurial or Git.
When you clone a Mercurial Repository, you have literally all versions of all the repo files available locally.
A:
I use Eclipse with a local CVS repository without issue. The only catch is that you cannot use the ":local:" CVS protocol. Since you're on Windows, I recommend installing TortoiseCVS and then configuring the included CVSNT server as follows:
Control Panel: CVSNT
Repository configuration: create a repository and publish it
Note the Server Name and make sure it matches your hostname
Eclipse: Create a new repository location using the :pserver: connection type and point it to your local hostname
This (or any actual source control system) has the advantage over the Eclipse Local History of being able to associate checkin comments with changes, group changes into change sets, etc. You can use the Eclipse Local History to recover from minor mistakes, but it's no replacement for source control (and expires as well: see Window->Preferences General->Workspace->Local History).
|
Eclipse + local CVS + PyDev
|
I tried several Python IDEs (on Windows platform) but finally I found only Eclipse + PyDev meeting my needs. This set of tools is really comfortable and easy to use. I'm currently working on a quite bigger project. I'd like to have a possibility to use CVS or any other version control system which would be installed on my local harddrive (I recently moved my house and don't have yet an access to internet.)
It doesn't matter for me if it'd be CVS - can also be any other version control system. It'd be great if it will be not too hard to configure with Eclipse. Can anyone give me some possible solution? Any hints?
Regards and thanks in advance for any clues. Please forgive my English ;)
|
[
"Last time I tried this, Eclipse did not support direct access to local repositories in the same way that command line cvs does because command line cvs has both client and server functionality whereas Eclipse only has client functionality and needs to go through (e.g.) pserver, so you would probably need to have a cvs server running.\nTurns out that I didn't really need it anyway as Eclipse keeps its own history of all changes so I only needed to do an occasional manual update to cvs at major milestones.\n[Eventually I decided not to use cvs at all with Eclipse under Linux as it got confused by symlinks and started deleting my include files when it \"synchronised\" with the repository.]\n",
"If you don't mind a switch to Subversion, Eclipse has its SubClipse plugin.\n",
"I tried Eclipse+Subclipse and Eclipse+Bazaar plugin. Both work very well, but I have found that Tortoise versions of those version source control tools are so good that I resigned from Eclipse plugins. On Windows Tortoise XXX are my choice. They integrate with shell (Explorer or TotalCommander), changes icon overlay if file is changed, shows log, compare revisions etc. etc.\n",
"As others have indicated, there are plugins available for Eclipse for SVN, Bazar, Mercurial and Git.\nEven so, despite their presence, I find using the command line the most comfortable.\nsvn commit -m 'now committing'\n\nAssuming you are not committing for more than several times a day, this should work well enough. Is there anything specific that is preventing you from using the command line?\n",
"I would definitely recommend switching over to a different VCS—I prefer Mercurial, along with a lot of the Python community. That way, you'll be able to work locally, but still have the ability to publish your changes to the world later.\nYou can install TortoiseHg for Windows Explorer, and the MercurialEclipse plugin for Eclipse.\nThere's even a Mercurial for CVS users document to help you change over, and a list of mostly-equivalent commands.\n",
"I believe Eclipse does have CVS support built in - or at least it did have when I last used it a couple of years ago.\nFor further information on how to use CVS with Eclipse see the Eclipse CVS FAQ\n",
"\nI recently moved my house and don't have yet an access to internet.\n\nCVS and SVN are the Centralized Version control systems. Rather than having to install them on your local system just for single version control, you could use DVCS like Mercurial or Git.\nWhen you clone a Mercurial Repository, you have literally all versions of all the repo files available locally.\n",
"I use Eclipse with a local CVS repository without issue. The only catch is that you cannot use the \":local:\" CVS protocol. Since you're on Windows, I recommend installing TortoiseCVS and then configuring the included CVSNT server as follows:\n\nControl Panel: CVSNT\n\n\nRepository configuration: create a repository and publish it\nNote the Server Name and make sure it matches your hostname\n\nEclipse: Create a new repository location using the :pserver: connection type and point it to your local hostname\n\nThis (or any actual source control system) has the advantage over the Eclipse Local History of being able to associate checkin comments with changes, group changes into change sets, etc. You can use the Eclipse Local History to recover from minor mistakes, but it's no replacement for source control (and expires as well: see Window->Preferences General->Workspace->Local History).\n"
] |
[
4,
1,
1,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"cvs",
"eclipse",
"pydev",
"python"
] |
stackoverflow_0000969121_cvs_eclipse_pydev_python.txt
|
Q:
Can Python adodbapi be used to connect to a paradox db?
Can Python adodbapi be used to connect to a paradox db? If yes what would the connection string look like?
A:
Yes, that depends on the Paradox ADODB driver you have installed in your windows.
Examples:
For Paradox 5.x, using Microsoft Jet OLEDB 4.0 driver:
r"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\myDb;
Extended Properties=Paradox 5.x;"
For Paradox 5.x, using Microsoft's Paradox ODBC Driver:
r"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;
DefaultDir=c:\pathToDb\;Dbq=c:\pathToDb\;CollatingSequence=ASCII;"
For Paradox 7.x, using Microsoft's Paradox ODBC Driver:
r"Provider=MSDASQL;Persist Security Info=False;Mode=Read;
Extended Properties='DSN=Paradox;DBQ=C:\myDb;DefaultDir=C:\myDb;DriverId=538;
FIL=Paradox 7.X;MaxBufferSize=2048;PageTimeout=600;';Initial Catalog=C:\myDb;"
Since you're probably going to use the ODBC driver anyway I strongly suggest you use pyodbc instead. It seems better supported than adodbapi and is also cross-platform.
Remember that you must point to the folder containing the .db files, not to the .db itself.
|
Can Python adodbapi be used to connect to a paradox db?
|
Can Python adodbapi be used to connect to a paradox db? If yes what would the connection string look like?
|
[
"Yes, that depends on the Paradox ADODB driver you have installed in your windows.\nExamples:\nFor Paradox 5.x, using Microsoft Jet OLEDB 4.0 driver:\nr\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\myDb;\nExtended Properties=Paradox 5.x;\"\n\nFor Paradox 5.x, using Microsoft's Paradox ODBC Driver:\nr\"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;\nDefaultDir=c:\\pathToDb\\;Dbq=c:\\pathToDb\\;CollatingSequence=ASCII;\"\n\nFor Paradox 7.x, using Microsoft's Paradox ODBC Driver:\nr\"Provider=MSDASQL;Persist Security Info=False;Mode=Read;\nExtended Properties='DSN=Paradox;DBQ=C:\\myDb;DefaultDir=C:\\myDb;DriverId=538;\nFIL=Paradox 7.X;MaxBufferSize=2048;PageTimeout=600;';Initial Catalog=C:\\myDb;\"\n\nSince you're probably going to use the ODBC driver anyway I strongly suggest you use pyodbc instead. It seems better supported than adodbapi and is also cross-platform.\nRemember that you must point to the folder containing the .db files, not to the .db itself.\n"
] |
[
0
] |
[] |
[] |
[
"paradox",
"python"
] |
stackoverflow_0000976324_paradox_python.txt
|
Q:
How can I make lxml's parser preserve whitespace outside of the root element?
I am using lxml to manipulate some existing XML documents, and I want to introduce as little diff noise as possible. Unfortunately by default lxml.etree.XMLParser doesn't preserve whitespace before or after the root element of a document:
>>> xml = '\n <etaoin>shrdlu</etaoin>\n'
>>> lxml.etree.tostring(lxml.etree.fromstring(xml))
'<etaoin>shrdlu</etaoin>'
>>> lxml.etree.tostring(lxml.etree.fromstring(xml)) == xml
False
Is this possible using lxml? Is it supported by the underlying libxml2?
A:
I don't know of any XML library that will do it for you. But using a regex sounds like a decent idea if you really need to do this.
>>> xml = '\n <etaoin>shrdlu</etaoin>\n'
>>> head, tail = re.findall(r"^\s*|\s*$", xml)[:2]
>>> root = etree.fromstring(xml)
>>> out = head + etree.tostring(root) + tail
>>> out == xml
True
A:
Capture the whitespace with a regex and add it back to the string when you're done.
|
How can I make lxml's parser preserve whitespace outside of the root element?
|
I am using lxml to manipulate some existing XML documents, and I want to introduce as little diff noise as possible. Unfortunately by default lxml.etree.XMLParser doesn't preserve whitespace before or after the root element of a document:
>>> xml = '\n <etaoin>shrdlu</etaoin>\n'
>>> lxml.etree.tostring(lxml.etree.fromstring(xml))
'<etaoin>shrdlu</etaoin>'
>>> lxml.etree.tostring(lxml.etree.fromstring(xml)) == xml
False
Is this possible using lxml? Is it supported by the underlying libxml2?
|
[
"I don't know of any XML library that will do it for you. But using a regex sounds like a decent idea if you really need to do this.\n>>> xml = '\\n <etaoin>shrdlu</etaoin>\\n'\n>>> head, tail = re.findall(r\"^\\s*|\\s*$\", xml)[:2]\n>>> root = etree.fromstring(xml)\n>>> out = head + etree.tostring(root) + tail\n>>> out == xml\nTrue\n\n",
"Capture the whitespace with a regex and add it back to the string when you're done.\n"
] |
[
1,
0
] |
[] |
[] |
[
"lxml",
"python",
"whitespace",
"xml"
] |
stackoverflow_0000973079_lxml_python_whitespace_xml.txt
|
Q:
Can I make Python 2.5 exit on ctrl-D in Windows instead of ctrl-Z?
I'm used to ending the python interactive interpreter using Ctrl-d using Linux and OS X. On windows though, you have to use CTRL+Z and then enter. Is there any way to use CTRL+D?
A:
You can't use CTRL+D on windows.
CTRL+Z is a windows-specific control char that prints EOF. On *nix, it is typically CTRL+D. That's the reason for the difference.
You can, however, train yourself to use exit(), which is cross-platform.
A:
Ctrl-d works to exit from IPython
(installed by python(x,y) package).
OS: WinXP
Python version: 2.5.4
Edit: I've been informed in the comments by the OP, Jason Baker, that Ctrl-d functionality on Windows OSes is made possible by the PyReadline package: "The pyreadline package is a python implementation of GNU readline functionality it is based on the ctypes based UNC readline package by Gary Bishop. It is not complete. It has been tested for use with windows 2000 and windows xp."
Since you're accustomed to *nix you may like that IPython also offers *nix-like shell functionality without using something like Cygwin...
Proper bash-like tab completion.
Use of / instead of \, everywhere
Persistent %bookmark's
%macro
%store. Especially when used with macros and aliases.
cd -. (easily jump around directory history). Directory history persists across sessions.
%env (see cookbook)
Shadow history - %hist and %rep (see cookbook)
%mglob
Expansion of $python_variables in system commands
var = !ls -la (capture command output to handy string lists)
A:
You can change the key set that Idle should be using.
Under Options->"Configure IDLE..."
go to the "Keys" tab.
On the right you can select the
"IDLE Classic Unix" key set.
A:
Run Cygwin Python if windowisms are bothering you... Unless what you are doing depends on pywin32 that is.
|
Can I make Python 2.5 exit on ctrl-D in Windows instead of ctrl-Z?
|
I'm used to ending the python interactive interpreter using Ctrl-d using Linux and OS X. On windows though, you have to use CTRL+Z and then enter. Is there any way to use CTRL+D?
|
[
"You can't use CTRL+D on windows. \nCTRL+Z is a windows-specific control char that prints EOF. On *nix, it is typically CTRL+D. That's the reason for the difference.\nYou can, however, train yourself to use exit(), which is cross-platform.\n",
"Ctrl-d works to exit from IPython \n(installed by python(x,y) package).\n\nOS: WinXP\nPython version: 2.5.4\n\n\nEdit: I've been informed in the comments by the OP, Jason Baker, that Ctrl-d functionality on Windows OSes is made possible by the PyReadline package: \"The pyreadline package is a python implementation of GNU readline functionality it is based on the ctypes based UNC readline package by Gary Bishop. It is not complete. It has been tested for use with windows 2000 and windows xp.\"\n\nSince you're accustomed to *nix you may like that IPython also offers *nix-like shell functionality without using something like Cygwin...\n\nProper bash-like tab completion.\nUse of / instead of \\, everywhere\nPersistent %bookmark's\n%macro\n%store. Especially when used with macros and aliases.\ncd -. (easily jump around directory history). Directory history persists across sessions.\n%env (see cookbook)\nShadow history - %hist and %rep (see cookbook)\n%mglob\nExpansion of $python_variables in system commands\nvar = !ls -la (capture command output to handy string lists)\n\n",
"You can change the key set that Idle should be using. \n\nUnder Options->\"Configure IDLE...\"\ngo to the \"Keys\" tab. \nOn the right you can select the\n \"IDLE Classic Unix\" key set.\n\n",
"Run Cygwin Python if windowisms are bothering you... Unless what you are doing depends on pywin32 that is.\n"
] |
[
9,
6,
0,
0
] |
[] |
[] |
[
"python",
"python_2.5",
"windows"
] |
stackoverflow_0000976796_python_python_2.5_windows.txt
|
Q:
static stylesheets gets reloaded with each post request
Every time there is a post from page the entire bunch of css gets reloaded. Is it possible to tell them not to come in again and again. There is a series of GET that get fired. Can we optimize in some way or is it normal behavior?
The environment is google apps in python.
A:
Check out Using Static Files and Handlers for Static Files. Since the latter link refer to cache duration of static files, I believe the the caching functionality is possible.
Unlike a traditional web hosting
environment, Google App Engine does
not serve files directly out of your
application's source directory unless
configured to do so. We named our
template file index.html, but this
does not automatically make the file
available at the URL /index.html.
But there are many cases where you
want to serve static files directly to
the web browser. Images, CSS
stylesheets, JavaScript code, movies
and Flash animations are all typically
stored with a web application and
served directly to the browser. You
can tell App Engine to serve specific
files directly without your having to
code your own handler.
A:
If your CSS comes from a static file, then as Steve mentioned you want to put it in a static directory and specify it in your app.yaml file. For example, if your CSS files are in a directory called stylesheets:
handlers:
- url: /stylesheets
static_dir: stylesheets
expiration: "180d"
The critical thing to remember with this is that when you upload a new version of your CSS file, you must change the filename because otherwise, visitors to your site will still be using the old cached version instead of your shiny new one. Simply incrementing a number on the end works well.
If your CSS is dynamically generated, then when the request comes in you want to set the caching in the response object's headers. For example, in your request handler you might have something like this:
class GetCSS(webapp.RequestHandler):
def get(self):
# generate the CSS file here, minify it or whatever
# make the CSS cached for 86400s = 1 day
self.response.headers['Cache-Control'] = 'max-age=86400'
self.response.out.write(your_css)
A:
You just have to put all your css in a "static directory" and specify an expiration into the app.yaml file.
Here is the app.yaml of one of my project:
application: <my_app_id>
version: 1
runtime: python
api_version: 1
skip_files: |
^(.*/)?(
(app\.yaml)|
(index\.yaml)|
(\..*)|
(.*\.pyc)|
(.*\.bat)|
(.*\.svn/.*)|
(.*\.lnk)|
(datastore/.*)|
(img/src_img/.*)|
)$
handlers:
- url: /favicon\.ico
static_files: img/favicon.ico
upload: img/favicon.ico
expiration: 180d
- url: /img
static_dir: img
expiration: 180d
- url: /static-js
static_dir: static-js
expiration: 180d
- url: .*
script: main.py
|
static stylesheets gets reloaded with each post request
|
Every time there is a post from page the entire bunch of css gets reloaded. Is it possible to tell them not to come in again and again. There is a series of GET that get fired. Can we optimize in some way or is it normal behavior?
The environment is google apps in python.
|
[
"Check out Using Static Files and Handlers for Static Files. Since the latter link refer to cache duration of static files, I believe the the caching functionality is possible.\n\nUnlike a traditional web hosting\n environment, Google App Engine does\n not serve files directly out of your\n application's source directory unless\n configured to do so. We named our\n template file index.html, but this\n does not automatically make the file\n available at the URL /index.html.\nBut there are many cases where you\n want to serve static files directly to\n the web browser. Images, CSS\n stylesheets, JavaScript code, movies\n and Flash animations are all typically\n stored with a web application and\n served directly to the browser. You\n can tell App Engine to serve specific\n files directly without your having to\n code your own handler.\n\n",
"If your CSS comes from a static file, then as Steve mentioned you want to put it in a static directory and specify it in your app.yaml file. For example, if your CSS files are in a directory called stylesheets:\nhandlers:\n- url: /stylesheets\n static_dir: stylesheets\n expiration: \"180d\"\n\nThe critical thing to remember with this is that when you upload a new version of your CSS file, you must change the filename because otherwise, visitors to your site will still be using the old cached version instead of your shiny new one. Simply incrementing a number on the end works well.\nIf your CSS is dynamically generated, then when the request comes in you want to set the caching in the response object's headers. For example, in your request handler you might have something like this:\nclass GetCSS(webapp.RequestHandler):\n def get(self):\n # generate the CSS file here, minify it or whatever\n # make the CSS cached for 86400s = 1 day\n self.response.headers['Cache-Control'] = 'max-age=86400' \n self.response.out.write(your_css)\n\n",
"You just have to put all your css in a \"static directory\" and specify an expiration into the app.yaml file.\nHere is the app.yaml of one of my project:\napplication: <my_app_id>\nversion: 1\nruntime: python\napi_version: 1\nskip_files: |\n ^(.*/)?(\n (app\\.yaml)|\n (index\\.yaml)|\n (\\..*)|\n (.*\\.pyc)|\n (.*\\.bat)|\n (.*\\.svn/.*)|\n (.*\\.lnk)|\n (datastore/.*)|\n (img/src_img/.*)|\n )$\n\nhandlers: \n- url: /favicon\\.ico\n static_files: img/favicon.ico\n upload: img/favicon.ico\n expiration: 180d\n\n- url: /img\n static_dir: img\n expiration: 180d\n\n- url: /static-js\n static_dir: static-js\n expiration: 180d\n\n- url: .*\n script: main.py\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"css",
"get",
"google_app_engine",
"post",
"python"
] |
stackoverflow_0000976898_css_get_google_app_engine_post_python.txt
|
Q:
How to expose client_address to all methods, using xmlrpclib?
I create little SimpleXMLRPCServer for check ip of client.
I try this:
Server
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(("localhost", 8000))
def MyIp():
return "Your ip is: %s" % server.socket.getpeername()
server.register_function(MyIp)
server.serve_forever()
Client
import xmlrpclib
se = xmlrpclib.Server("http://localhost:8000")
print se.MyIp()
Error
xmlrpclib.Fault: :(107, 'Transport endpoint is not connected')">
How make client_address visible to all functions?
A:
If you want for example to pass client_address as the first argument to every function, you could subclass SimpleXMLRPCRequestHandler (pass your subclass as the handler when you instantiate SimpleXMLRPCServer) and override _dispatch (to prepend self.client_address to the params tuple and then delegate the rest to SimpleXMLRPCRequestHandler._dispatch). If this approach is OK and you want to see code, just ask!
I'm not sure how you'd safely use anything but the function arguments to "make client_address visible" -- there's no client_address as a bare name, global or otherwise, there's just the self.client_address of each instance of the request handler class (and hacks such as copying it to a global variables feel really yucky indeed -- and unsafe under threading, etc etc).
|
How to expose client_address to all methods, using xmlrpclib?
|
I create little SimpleXMLRPCServer for check ip of client.
I try this:
Server
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(("localhost", 8000))
def MyIp():
return "Your ip is: %s" % server.socket.getpeername()
server.register_function(MyIp)
server.serve_forever()
Client
import xmlrpclib
se = xmlrpclib.Server("http://localhost:8000")
print se.MyIp()
Error
xmlrpclib.Fault: :(107, 'Transport endpoint is not connected')">
How make client_address visible to all functions?
|
[
"If you want for example to pass client_address as the first argument to every function, you could subclass SimpleXMLRPCRequestHandler (pass your subclass as the handler when you instantiate SimpleXMLRPCServer) and override _dispatch (to prepend self.client_address to the params tuple and then delegate the rest to SimpleXMLRPCRequestHandler._dispatch). If this approach is OK and you want to see code, just ask!\nI'm not sure how you'd safely use anything but the function arguments to \"make client_address visible\" -- there's no client_address as a bare name, global or otherwise, there's just the self.client_address of each instance of the request handler class (and hacks such as copying it to a global variables feel really yucky indeed -- and unsafe under threading, etc etc).\n"
] |
[
3
] |
[] |
[] |
[
"python",
"xmlrpclib"
] |
stackoverflow_0000978784_python_xmlrpclib.txt
|
Q:
Is it more efficient to parse external XML or to hit the database?
I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.
A:
First off -- measure. Don't just assume that one is better or worse than the other.
Second, if you really don't want to measure, I'd guess the database is a bit faster (assuming the database is relatively local compared to the web service). Network latency usually is more than parse time unless we're talking a really complex database or really complex XML.
A:
Everyone is being very polite in answering this question: "it depends"... "you should test"... and so forth.
True, the question does not go into great detail about the application and network topographies involved, but if the question is even being asked, then it's likely a) the DB is "local" to the application (on the same subnet, or the same machine, or in memory), and b) the webservice is not. After all, the OP uses the phrases "external service" and "display on your own site." The phrase "parsing it once or however many times you need to each day" also suggests a set of data that doesn't exactly change every second.
The classic SOA myth is that the network is always available; going a step further, I'd say it's a myth that the network is always available with low latency. Unless your own internal systems are crap, sending an HTTP query across the Internet will always be slower than a query to a local DB or DB cluster. There are any number of reasons for this: number of hops to the remote server, outage or degradation issues that you can't control on the remote end, and the internal processing time for the remote web service application to analyze your request, hit its own persistence backend (aka DB), and return a result.
Fire up your app. Do some latency and response times to your DB. Now do the same to a remote web service. Unless your DB is also across the Internet, you'll notice a huge difference.
It's not at all hard for a competent technologist to scale a DB, or for you to completely remove the DB from caching using memcached and other paradigms; the latency between servers sitting near each other in the datacentre is monumentally less than between machines over the Internet (and more secure, to boot). Even if achieving this scale requires some thought, it's under your control, unlike a remote web service whose scaling and latency are totally opaque to you. I, for one, would not be too happy with the idea that the availability and responsiveness of my site are based on someone else entirely.
Finally, what happens if the remote web service is unavailable? Imagine a world where every request to your site involves a request over the Internet to some other site. What happens if that other site is unavailable? Do your users watch a spinning cursor of death for several hours? Do they enjoy an Error 500 while your site borks on this unexpected external dependency?
If you find yourself adopting an architecture whose fundamental features depend on a remote Internet call for every request, think very carefully about your application before deciding if you can live with the consequences.
A:
Consuming the webservices is more efficient because there are a lot more things you can do to scale your webservices and webserver (via caching, etc.). By consuming the middle layer, you also have the options to change the returned data format (e.g. you can decide to use JSON rather than XML). Scaling database is much harder (involving replication, etc.) so in general, reduce hits on DB if you can.
A:
There is not enough information to be able to say for sure in the general case. Why don't you do some tests and find out? Since it sounds like you are using python you will probably want to use the timeit module.
Some things that could effect the result:
Performance of the web service you are using
Reliability of the web service you are using
Distance between servers
Amount of data being returned
I would guess that if it is cacheable, that a cached version of the data will be faster, but that does not necessarily mean using a local RDBMS, it might mean something like memcached or an in memory cache in your application.
A:
It depends - who is calling the web service? Is the web service called every time the user hits the page? If that's the case I'd recommend introducing a caching layer of some sort - many web service API's throttle the amount of hits you can make per hour.
Whether you choose to parse the cached XML on the fly or call the data from a database probably won't matter (unless we are talking enterprise scaling here). Personally, I'd much rather make a simple SQL call than write a DOM Parser (which is much more prone to exceptional scenarios).
A:
It depends from case to case, you'll have to measure (or at least make an educated guess).
You'll have to consider several things.
Web service
it might hit database itself
it can be cached
it will introduce network latency and might be unreliable
or it could be in local network and faster than accessing even local disk
DB
might be slow since it needs to access disk (although databases have internal caches, but those are usually not targeted)
should be reliable
Technology itself doesn't mean much in terms of speed - in one case database parses SQL, in other XML parser parses XML, and database is usually acessed via socket as well, so you have both parsing and network in either case.
Caching data in your application if applicable is probably a good idea.
A:
As a few people have said, it depends, and you should test it.
Often external services are slow, and caching them locally (in a database in memory, e.g., with memcached) is faster. But perhaps not.
Fortunately, it's cheap and easy to test.
A:
Test definitely. As a rule of thumb, XML is good for communicating between apps, but once you have the data inside of your app, everything should go into a database table. This may not apply in all cases, but 95% of the time it has for me. Anytime I ever tried to store data any other way (ex. XML in a content management system) I ended up wishing I would have just used good old sprocs and sql server.
|
Is it more efficient to parse external XML or to hit the database?
|
I was wondering when dealing with a web service API that returns XML, whether it's better (faster) to just call the external service each time and parse the XML (using ElementTree) for display on your site or to save the records into the database (after parsing it once or however many times you need to each day) and make database calls instead for that same information.
|
[
"First off -- measure. Don't just assume that one is better or worse than the other.\nSecond, if you really don't want to measure, I'd guess the database is a bit faster (assuming the database is relatively local compared to the web service). Network latency usually is more than parse time unless we're talking a really complex database or really complex XML.\n",
"Everyone is being very polite in answering this question: \"it depends\"... \"you should test\"... and so forth.\nTrue, the question does not go into great detail about the application and network topographies involved, but if the question is even being asked, then it's likely a) the DB is \"local\" to the application (on the same subnet, or the same machine, or in memory), and b) the webservice is not. After all, the OP uses the phrases \"external service\" and \"display on your own site.\" The phrase \"parsing it once or however many times you need to each day\" also suggests a set of data that doesn't exactly change every second.\nThe classic SOA myth is that the network is always available; going a step further, I'd say it's a myth that the network is always available with low latency. Unless your own internal systems are crap, sending an HTTP query across the Internet will always be slower than a query to a local DB or DB cluster. There are any number of reasons for this: number of hops to the remote server, outage or degradation issues that you can't control on the remote end, and the internal processing time for the remote web service application to analyze your request, hit its own persistence backend (aka DB), and return a result.\nFire up your app. Do some latency and response times to your DB. Now do the same to a remote web service. Unless your DB is also across the Internet, you'll notice a huge difference.\nIt's not at all hard for a competent technologist to scale a DB, or for you to completely remove the DB from caching using memcached and other paradigms; the latency between servers sitting near each other in the datacentre is monumentally less than between machines over the Internet (and more secure, to boot). Even if achieving this scale requires some thought, it's under your control, unlike a remote web service whose scaling and latency are totally opaque to you. I, for one, would not be too happy with the idea that the availability and responsiveness of my site are based on someone else entirely.\nFinally, what happens if the remote web service is unavailable? Imagine a world where every request to your site involves a request over the Internet to some other site. What happens if that other site is unavailable? Do your users watch a spinning cursor of death for several hours? Do they enjoy an Error 500 while your site borks on this unexpected external dependency? \nIf you find yourself adopting an architecture whose fundamental features depend on a remote Internet call for every request, think very carefully about your application before deciding if you can live with the consequences.\n",
"Consuming the webservices is more efficient because there are a lot more things you can do to scale your webservices and webserver (via caching, etc.). By consuming the middle layer, you also have the options to change the returned data format (e.g. you can decide to use JSON rather than XML). Scaling database is much harder (involving replication, etc.) so in general, reduce hits on DB if you can.\n",
"There is not enough information to be able to say for sure in the general case. Why don't you do some tests and find out? Since it sounds like you are using python you will probably want to use the timeit module.\nSome things that could effect the result:\n\nPerformance of the web service you are using\nReliability of the web service you are using\nDistance between servers\nAmount of data being returned\n\nI would guess that if it is cacheable, that a cached version of the data will be faster, but that does not necessarily mean using a local RDBMS, it might mean something like memcached or an in memory cache in your application.\n",
"It depends - who is calling the web service? Is the web service called every time the user hits the page? If that's the case I'd recommend introducing a caching layer of some sort - many web service API's throttle the amount of hits you can make per hour.\nWhether you choose to parse the cached XML on the fly or call the data from a database probably won't matter (unless we are talking enterprise scaling here). Personally, I'd much rather make a simple SQL call than write a DOM Parser (which is much more prone to exceptional scenarios). \n",
"It depends from case to case, you'll have to measure (or at least make an educated guess).\nYou'll have to consider several things.\nWeb service\n\nit might hit database itself\nit can be cached\nit will introduce network latency and might be unreliable\nor it could be in local network and faster than accessing even local disk\n\nDB\n\nmight be slow since it needs to access disk (although databases have internal caches, but those are usually not targeted)\nshould be reliable\n\nTechnology itself doesn't mean much in terms of speed - in one case database parses SQL, in other XML parser parses XML, and database is usually acessed via socket as well, so you have both parsing and network in either case.\nCaching data in your application if applicable is probably a good idea.\n",
"As a few people have said, it depends, and you should test it.\nOften external services are slow, and caching them locally (in a database in memory, e.g., with memcached) is faster. But perhaps not.\nFortunately, it's cheap and easy to test.\n",
"Test definitely. As a rule of thumb, XML is good for communicating between apps, but once you have the data inside of your app, everything should go into a database table. This may not apply in all cases, but 95% of the time it has for me. Anytime I ever tried to store data any other way (ex. XML in a content management system) I ended up wishing I would have just used good old sprocs and sql server.\n"
] |
[
6,
4,
3,
1,
1,
0,
0,
0
] |
[
"It sounds like you essentially want to cache results, and are wondering if it's worth it. But if so, I would NOT use a database (I assume you are thinking of a relational DB): RDBMSs are not good for caching; even though many use them. You don't need persistence nor ACID.\nIf choice was between Oracle/MySQL and external web service, I would start with just using service.\nInstead, consider real caching systems; local or not (memcache, simple in-memory caches etc).\nOr if you must use a DB, use key/value store, BDB works well. Store response message in its serialized form (XML), try to fetch from cache, if not, from service, parse. Or if there's a convenient and more compact serialization, store and fetch that.\n"
] |
[
-1
] |
[
"django",
"mysql",
"parsing",
"python",
"xml"
] |
stackoverflow_0000978581_django_mysql_parsing_python_xml.txt
|
Q:
Thinking in AppEngine
I'm looking for resources to help migrate my design skills from traditional RDBMS data store over to AppEngine DataStore (ie: 'Soft Schema' style). I've seen several presentations and all touch on the the overarching themes and some specific techniques.
I'm wondering if there's a place we could pool knowledge from experience ("from the trenches") on real-world approaches to rethinking how data is structured, especially porting existing applications. We're heavily Hibernate based and have probably travelled a bit down the wrong path with our data model already, generating some gnarly queries which our DB is struggling with.
Please respond if:
You have ported a non-trivial application over to AppEngine
You've created a common type of application from scratch in AppEngine
You've done neither 1 or 2, but are considering it and want to share your own findings so far.
A:
I'm wondering if there's a place we could pool knowledge from experience
Various Google Groups are good for that, though I don't know if any are directly applicable to Java-GAE yet -- my GAE experience so far is all-Python (I'm kind of proud to say that Guido van Rossum, inventor of Python and now working at Google on App Engine, told me I had taught him a few things about how his brainchild worked -- his recommendation mentioning that is now the one I'm proudest, on amongst all those on my linkedin profile;-). [I work at Google but my impact on App Engine was very peripheral -- I worked on "building the cloud", cluster and network management SW, and App Engine is about making that infrastructure useful for third party developers].
There are indeed many essays & presentations on how best to denormalize and shard your data for optimal GAE scaling and performance -- they're of varying quality, though. The books that are out so far are so-so; many more are coming in the next few months, hopefully better ones (I had a project to write one of those, with two very skilled friends, but we're all so busy that we ended up dropping it). In general, I'd recommend the Google I/O videos and the essays that Google blessed in its app engine site and blogs, PLUS every bit of content from appenginefan's blog -- what Guido commended me for teaching him about GAE, I in turn mostly learned from appenginefan (partly through the wonderful app engine meetup in Palo Alto, but his blog is great too;-).
A:
I played around with Google App Engine for Java and found that it had many shortcomings:
This is not general purpose Java application hosting. In particular, you do not have access to a full JRE (e.g. cannot create threads, etc.) Given this fact, you pretty much have to build your application from the ground up with the Google App Engine JRE in mind. Porting any non-trival application would be impossible.
More pertinent to your datastore questions...
The datastore performance is abysmal. I was trying to write 5000 weather observations per hour -- nothing too massive -- but I could not do it because I kept on running into time out exception both with the datastore and the HTTP request. Using the "low-level" datastore API helped somewhat, but not enough.
I wanted to delete those weather observation after 24 hours to not fill up my quota. Again, could not do it because the delete operation took too long. This problem in turn led to my datastore quota filling up. Insanely, you cannot easily delete large swaths of data in the GAE datastore.
There are some features that I did like. Eclipse integration is snazzy. The appspot application server UI is a million times better than working with Tomcat (e.g. nice views of logs). But the minuses far outweighed those benefits for me.
In sum, I constantly found myself having to shave the yak, in order to do something that would have been pretty trivial in any normal Java / application hosting environment.
A:
The timeouts are tight and performance was ok but not great, so I found myself using extra space to save time; for example I had a many-to-many relationship between trading cards and players, so I duplicated the information of who owns what: Card objects have a list of Players and Player objects have a list of Cards.
Normally storing all your information twice would have been silly (and prone to get out of sync) but it worked really well.
In Python they recently released a remote API so you can get an interactive shell to the datastore so you can play with your datastore without any timeouts or limits (for example, you can delete large swaths of data, or refactor your models); this is fantastically useful since otherwise as Julien mentioned it was very difficult to do any bulk operations.
A:
The non relational database design essentially involves denormalization wherever possible.
Example: Since the BigTable doesnt provide enough aggregation features, the sum(cash) option that would be in the RDBMS world is not available. Instead it would have to be stored on the model and the model save method must be overridden to compute the denormalized field sum.
Essential basic design that comes to mind is that each template has its own model where all the required fields to be populated are present denormalized in the corresponding model; and you have an entire signals-update-bots complexity going on in the models.
|
Thinking in AppEngine
|
I'm looking for resources to help migrate my design skills from traditional RDBMS data store over to AppEngine DataStore (ie: 'Soft Schema' style). I've seen several presentations and all touch on the the overarching themes and some specific techniques.
I'm wondering if there's a place we could pool knowledge from experience ("from the trenches") on real-world approaches to rethinking how data is structured, especially porting existing applications. We're heavily Hibernate based and have probably travelled a bit down the wrong path with our data model already, generating some gnarly queries which our DB is struggling with.
Please respond if:
You have ported a non-trivial application over to AppEngine
You've created a common type of application from scratch in AppEngine
You've done neither 1 or 2, but are considering it and want to share your own findings so far.
|
[
"\nI'm wondering if there's a place we could pool knowledge from experience\n\nVarious Google Groups are good for that, though I don't know if any are directly applicable to Java-GAE yet -- my GAE experience so far is all-Python (I'm kind of proud to say that Guido van Rossum, inventor of Python and now working at Google on App Engine, told me I had taught him a few things about how his brainchild worked -- his recommendation mentioning that is now the one I'm proudest, on amongst all those on my linkedin profile;-). [I work at Google but my impact on App Engine was very peripheral -- I worked on \"building the cloud\", cluster and network management SW, and App Engine is about making that infrastructure useful for third party developers].\nThere are indeed many essays & presentations on how best to denormalize and shard your data for optimal GAE scaling and performance -- they're of varying quality, though. The books that are out so far are so-so; many more are coming in the next few months, hopefully better ones (I had a project to write one of those, with two very skilled friends, but we're all so busy that we ended up dropping it). In general, I'd recommend the Google I/O videos and the essays that Google blessed in its app engine site and blogs, PLUS every bit of content from appenginefan's blog -- what Guido commended me for teaching him about GAE, I in turn mostly learned from appenginefan (partly through the wonderful app engine meetup in Palo Alto, but his blog is great too;-).\n",
"I played around with Google App Engine for Java and found that it had many shortcomings:\nThis is not general purpose Java application hosting. In particular, you do not have access to a full JRE (e.g. cannot create threads, etc.) Given this fact, you pretty much have to build your application from the ground up with the Google App Engine JRE in mind. Porting any non-trival application would be impossible.\nMore pertinent to your datastore questions...\nThe datastore performance is abysmal. I was trying to write 5000 weather observations per hour -- nothing too massive -- but I could not do it because I kept on running into time out exception both with the datastore and the HTTP request. Using the \"low-level\" datastore API helped somewhat, but not enough.\nI wanted to delete those weather observation after 24 hours to not fill up my quota. Again, could not do it because the delete operation took too long. This problem in turn led to my datastore quota filling up. Insanely, you cannot easily delete large swaths of data in the GAE datastore.\nThere are some features that I did like. Eclipse integration is snazzy. The appspot application server UI is a million times better than working with Tomcat (e.g. nice views of logs). But the minuses far outweighed those benefits for me.\nIn sum, I constantly found myself having to shave the yak, in order to do something that would have been pretty trivial in any normal Java / application hosting environment.\n",
"The timeouts are tight and performance was ok but not great, so I found myself using extra space to save time; for example I had a many-to-many relationship between trading cards and players, so I duplicated the information of who owns what: Card objects have a list of Players and Player objects have a list of Cards.\nNormally storing all your information twice would have been silly (and prone to get out of sync) but it worked really well.\nIn Python they recently released a remote API so you can get an interactive shell to the datastore so you can play with your datastore without any timeouts or limits (for example, you can delete large swaths of data, or refactor your models); this is fantastically useful since otherwise as Julien mentioned it was very difficult to do any bulk operations. \n",
"The non relational database design essentially involves denormalization wherever possible.\nExample: Since the BigTable doesnt provide enough aggregation features, the sum(cash) option that would be in the RDBMS world is not available. Instead it would have to be stored on the model and the model save method must be overridden to compute the denormalized field sum.\nEssential basic design that comes to mind is that each template has its own model where all the required fields to be populated are present denormalized in the corresponding model; and you have an entire signals-update-bots complexity going on in the models.\n"
] |
[
5,
1,
1,
1
] |
[] |
[] |
[
"data_modeling",
"google_app_engine",
"java",
"python"
] |
stackoverflow_0000976639_data_modeling_google_app_engine_java_python.txt
|
Q:
Extracting IP from request in Python
I have a Pythonic HTTP server that is supposed to determine client's IP. How do I do that in Python? Is there any way to get the request headers and extract it from there?
PS: I'm using WebPy.
A:
Use web.ctx:
class example:
def GET(self):
print web.ctx.ip
More info here
A:
web.env.get('REMOTE_ADDR')
|
Extracting IP from request in Python
|
I have a Pythonic HTTP server that is supposed to determine client's IP. How do I do that in Python? Is there any way to get the request headers and extract it from there?
PS: I'm using WebPy.
|
[
"Use web.ctx:\nclass example:\n def GET(self):\n print web.ctx.ip\n\nMore info here\n",
"web.env.get('REMOTE_ADDR')\n"
] |
[
4,
3
] |
[] |
[] |
[
"header",
"http",
"ip",
"python",
"request"
] |
stackoverflow_0000979599_header_http_ip_python_request.txt
|
Q:
Sending email using google apps SMTP server in Python 2.4
I'm having difficulty getting python 2.4 to connect to gmail's smtp server. My below script doesn't ever get past "connection". I realise there is an SMTP_SSL class in later versions of python and it seems to work fine, but the production environment I have to deal with only has - and likely will only ever have - python 2.4.
print "connecting"
server = smtplib.SMTP("smtp.gmail.com", 465)
print "ehlo"
server.ehlo()
print "start tls"
server.starttls()
print "ehlo"
server.ehlo()
print "log in"
if self.smtpuser:
server.login(smtpuser, smtppassword)
Does anybody have any advice for getting the above code to work with python 2.4?
A:
When I tried setting something similar up for Django apps, I could never get it to work on port 465. Using port 587, which is the other port listed in the GMail docs seemed to work.
A:
Yes I used 587 as the port for my vb.net app too. 465 did not work for me too.
A:
try
server.ehlo('[email protected]')
in both places above
also look at setting
server.set_debuglevel(1) value as required for more info
|
Sending email using google apps SMTP server in Python 2.4
|
I'm having difficulty getting python 2.4 to connect to gmail's smtp server. My below script doesn't ever get past "connection". I realise there is an SMTP_SSL class in later versions of python and it seems to work fine, but the production environment I have to deal with only has - and likely will only ever have - python 2.4.
print "connecting"
server = smtplib.SMTP("smtp.gmail.com", 465)
print "ehlo"
server.ehlo()
print "start tls"
server.starttls()
print "ehlo"
server.ehlo()
print "log in"
if self.smtpuser:
server.login(smtpuser, smtppassword)
Does anybody have any advice for getting the above code to work with python 2.4?
|
[
"When I tried setting something similar up for Django apps, I could never get it to work on port 465. Using port 587, which is the other port listed in the GMail docs seemed to work.\n",
"Yes I used 587 as the port for my vb.net app too. 465 did not work for me too.\n",
"try\nserver.ehlo('[email protected]')\nin both places above\nalso look at setting \nserver.set_debuglevel(1) value as required for more info\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"python",
"python_2.4"
] |
stackoverflow_0000975065_python_python_2.4.txt
|
Q:
Trying to create a Python Server
I am looking at trying to create a python server, which allows me to run root commands on a Centos Server remotely, I would also like the server to be able to respond with the result's of the command.
I have found another question on here which has a basic python server, however it throws a error, the code is:
#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each <> "":
if each[0] <> '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
When i run using python vzctl.py. I get the following error:
File "vzctl.py", line 9
each = each.rstrip()
^
SyntaxError: invalid syntax
Does anyone have any idea of the error, and if it would be possible to add the function of the server responding with the output of the command.
You can see the source of this script at : How can I have a PHP script run a shell script as root?
Thanks,
Ashley
A:
you need to keep indentation at the same level for each nested statement throughout your code.
A:
On a different note: why not using TwistedMatrix?
|
Trying to create a Python Server
|
I am looking at trying to create a python server, which allows me to run root commands on a Centos Server remotely, I would also like the server to be able to respond with the result's of the command.
I have found another question on here which has a basic python server, however it throws a error, the code is:
#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each <> "":
if each[0] <> '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
When i run using python vzctl.py. I get the following error:
File "vzctl.py", line 9
each = each.rstrip()
^
SyntaxError: invalid syntax
Does anyone have any idea of the error, and if it would be possible to add the function of the server responding with the output of the command.
You can see the source of this script at : How can I have a PHP script run a shell script as root?
Thanks,
Ashley
|
[
"you need to keep indentation at the same level for each nested statement throughout your code.\n",
"On a different note: why not using TwistedMatrix?\n"
] |
[
2,
2
] |
[] |
[] |
[
"python",
"syntax_error"
] |
stackoverflow_0000981033_python_syntax_error.txt
|
Q:
Send output from a python server back to client
I now have a small java script server working correctly, called by:
<?php
$handle = fsockopen("udp://78.129.148.16",12345);
fwrite($handle,"vzctlrestart110");
fclose($handle);
?>
On a remote server the following python server is running and executing the comand's
#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each != "":
if each[0] != '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
Is it possible to easily send the output of the command back, when the server is started and is running a command the output is shown in the ssh window, however I want this output to be sent back to the browser of the original client, maybe setting the browser to wait for 15 seconds and then check for any data received via the socket.
I know I am asking quite a lot, however I am creating a PHP script which I have a large knowledge about, however my python knowledge lacks greatly.
Thanks,
Ashley
A:
Yes, you can read the output of the command. For this I would recommend the Python subprocess module. Then you can just s.write() it back.
Naturally this has some implications, you would probably have to let your PHP script run for a while longer since the process may be running slow.
# The pipe behaves like a file object in Python.
process = Popen(cmd, shell=True, stdout=PIPE)
process_output = ""
while process.poll():
process_output += process.stdout.read(256)
s.write(process_output)
# Better yet.
process = Popen(cmd, shell=true, stdout=PIPE)
stdout, stderr = process.communicate() # will read and wait for process to end.
s.write(stdout)
Integrated into your code:
# ... snip ...
import subprocess
con, addr = s.accept()
while True:
datagram = con.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
process = subprocess.Popen(settings[datagram]+" &", shell=True, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
con.send(stdout)
con.close()
s.close()
A:
Here's an example of how to get the output of a command:
>>> import commands
>>> s = commands.getoutput("ls *")
>>> s
'client.py'
|
Send output from a python server back to client
|
I now have a small java script server working correctly, called by:
<?php
$handle = fsockopen("udp://78.129.148.16",12345);
fwrite($handle,"vzctlrestart110");
fclose($handle);
?>
On a remote server the following python server is running and executing the comand's
#!/usr/bin/python
import os
import socket
print " Loading Bindings..."
settings = {}
line = 0
for each in open('/root/actions.txt', 'r'):
line = line + 1
each = each.rstrip()
if each != "":
if each[0] != '#':
a = each.partition(':')
if a[2]:
settings[a[0]] = a[2]
else:
print " Err @ line",line,":",each
print " Starting Server...",
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "OK."
print " Listening on port:", port
while True:
datagram = s.recv(1024)
if not datagram:
break
print "Rx Cmd:", datagram
if settings.has_key(datagram):
print "Launch:", settings[datagram]
os.system(settings[datagram]+" &")
s.close()
Is it possible to easily send the output of the command back, when the server is started and is running a command the output is shown in the ssh window, however I want this output to be sent back to the browser of the original client, maybe setting the browser to wait for 15 seconds and then check for any data received via the socket.
I know I am asking quite a lot, however I am creating a PHP script which I have a large knowledge about, however my python knowledge lacks greatly.
Thanks,
Ashley
|
[
"Yes, you can read the output of the command. For this I would recommend the Python subprocess module. Then you can just s.write() it back.\nNaturally this has some implications, you would probably have to let your PHP script run for a while longer since the process may be running slow.\n# The pipe behaves like a file object in Python.\nprocess = Popen(cmd, shell=True, stdout=PIPE)\nprocess_output = \"\"\nwhile process.poll():\n process_output += process.stdout.read(256)\ns.write(process_output)\n\n# Better yet.\nprocess = Popen(cmd, shell=true, stdout=PIPE)\nstdout, stderr = process.communicate() # will read and wait for process to end.\ns.write(stdout)\n\nIntegrated into your code:\n# ... snip ...\nimport subprocess\ncon, addr = s.accept()\nwhile True:\n datagram = con.recv(1024)\n if not datagram:\n break\n print \"Rx Cmd:\", datagram\n if settings.has_key(datagram):\n print \"Launch:\", settings[datagram]\n process = subprocess.Popen(settings[datagram]+\" &\", shell=True, stdout=subprocess.PIPE)\n stdout, stderr = process.communicate()\n con.send(stdout)\n con.close()\ns.close()\n\n",
"Here's an example of how to get the output of a command:\n>>> import commands\n>>> s = commands.getoutput(\"ls *\")\n>>> s\n'client.py'\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"sockets"
] |
stackoverflow_0000981348_python_sockets.txt
|
Q:
Can Windows drivers be written in Python?
Can Windows drivers be written in Python?
A:
Yes. You cannot create the "classic" kernel-mode drivers. However, starting with XP, Windows offers a User-Mode Driver Framework. They can't do everything, obviously - any driver used in booting the OS obviously has to be kernel-mode. But with UMDF, you only need to implement COM components.
Besides boot-time drivers, you also can't write UMDF drivers that:
Handle interrupts
Directly access hardware, such as direct memory access (DMA)
have strict timing loops
Use nonpaged pool or other resources that are reserved for kernel mode
A:
The definitive answer is not without embedding an interpreter in your otherwise C/assembly driver. Unless someone has a framework available, then the answer is no. Once you have the interpreter and bindings in place then the rest of the logic could be done in Python.
However, writing drivers is one of the things for which C is best suited. I imagine the resulting Python code would look a whole lot like C code and defeat the purpose of the interpreter overhead.
A:
A good way to gain insight why this is practically impossible is by reading Microsoft's advice on the use of C++ in drivers. As a derivative of C, the use of C++ appears to be straightforward. In practice, not so.
For instance, you must decide for every function (and really every assembly instruction) whether it's in pageable or non-pageable memory. This requires extensions to C, careful use of new C++ features, or in this case a special extension to the Python language and VM. In addition, your driver-compatible VM would also have to deal with the different IRQLs - there's a hierarchy of "levels" which restrict what you can and cannot do.
A:
Python runs in a virtual machine, so no.
BUT:
You could write a compiler that translates Python code to machine language. Once you've done that, you can do it.
A:
I don't know the restrictions on drivers on windows (memory allocation schemes, dynamic load of libraries and all), but you may be able to embed a python interpreter in your driver, at which point you can do whatever you want. Not that I think it is a good idea :)
A:
Never say never but eh.. no
You might be able to hack something together to run user-mode parts of drivers in python. But kernel-mode stuff can only be done in C or assembly.
A:
No they cannot. Windows drivers must be written in a language that can
Interface with the C based API
Compile down to machine code
Then again, there's nothing stopping you from writing a compiler that translates python to machine code ;)
|
Can Windows drivers be written in Python?
|
Can Windows drivers be written in Python?
|
[
"Yes. You cannot create the \"classic\" kernel-mode drivers. However, starting with XP, Windows offers a User-Mode Driver Framework. They can't do everything, obviously - any driver used in booting the OS obviously has to be kernel-mode. But with UMDF, you only need to implement COM components. \nBesides boot-time drivers, you also can't write UMDF drivers that:\n\nHandle interrupts\nDirectly access hardware, such as direct memory access (DMA)\nhave strict timing loops\nUse nonpaged pool or other resources that are reserved for kernel mode\n\n",
"The definitive answer is not without embedding an interpreter in your otherwise C/assembly driver. Unless someone has a framework available, then the answer is no. Once you have the interpreter and bindings in place then the rest of the logic could be done in Python.\nHowever, writing drivers is one of the things for which C is best suited. I imagine the resulting Python code would look a whole lot like C code and defeat the purpose of the interpreter overhead.\n",
"A good way to gain insight why this is practically impossible is by reading Microsoft's advice on the use of C++ in drivers. As a derivative of C, the use of C++ appears to be straightforward. In practice, not so. \nFor instance, you must decide for every function (and really every assembly instruction) whether it's in pageable or non-pageable memory. This requires extensions to C, careful use of new C++ features, or in this case a special extension to the Python language and VM. In addition, your driver-compatible VM would also have to deal with the different IRQLs - there's a hierarchy of \"levels\" which restrict what you can and cannot do. \n",
"Python runs in a virtual machine, so no.\nBUT:\nYou could write a compiler that translates Python code to machine language. Once you've done that, you can do it.\n",
"I don't know the restrictions on drivers on windows (memory allocation schemes, dynamic load of libraries and all), but you may be able to embed a python interpreter in your driver, at which point you can do whatever you want. Not that I think it is a good idea :)\n",
"Never say never but eh.. no\nYou might be able to hack something together to run user-mode parts of drivers in python. But kernel-mode stuff can only be done in C or assembly.\n",
"No they cannot. Windows drivers must be written in a language that can \n\nInterface with the C based API\nCompile down to machine code \n\nThen again, there's nothing stopping you from writing a compiler that translates python to machine code ;)\n"
] |
[
18,
3,
3,
1,
1,
0,
0
] |
[] |
[] |
[
"drivers",
"python",
"windows"
] |
stackoverflow_0000981200_drivers_python_windows.txt
|
Q:
Python QuickBase API Help
Hey, I'm having some trouble using the QuickBase API from Python. From the QuickBase guide, there are two methods of hitting the API: POST and GET. I can handle the GET calls, but some API methods require XML to be sent over POST. The link to the documentation is here: http://member.developer.intuit.com/MyIDN/technical_resources/quickbase/framework/httpapiref/HTML_API_Programmers_Guide.htm
I guess I don't quite understand how to pack the XML payload into the POST request from python. Using the urllib.urlencode method, as well as any other way I've created POST requests requires a key-value type data structure, where all I have here is a string. Any help would be appreciated.
A:
Got it. For some reason The data I was sending in my POST needed to have a .strip() placed after it.
|
Python QuickBase API Help
|
Hey, I'm having some trouble using the QuickBase API from Python. From the QuickBase guide, there are two methods of hitting the API: POST and GET. I can handle the GET calls, but some API methods require XML to be sent over POST. The link to the documentation is here: http://member.developer.intuit.com/MyIDN/technical_resources/quickbase/framework/httpapiref/HTML_API_Programmers_Guide.htm
I guess I don't quite understand how to pack the XML payload into the POST request from python. Using the urllib.urlencode method, as well as any other way I've created POST requests requires a key-value type data structure, where all I have here is a string. Any help would be appreciated.
|
[
"Got it. For some reason The data I was sending in my POST needed to have a .strip() placed after it.\n"
] |
[
1
] |
[] |
[] |
[
"api",
"post",
"python",
"quickbase",
"xml"
] |
stackoverflow_0000980932_api_post_python_quickbase_xml.txt
|
Q:
Get original path from django filefield
My django app accepts two files (in this case a jad and jar combo). Is there a way I can preserve the folders they came from?
I need this so I can check later that they came from the same path.
(And later on accept a whole load of files and be able to work out which came from the same folder).
A:
I think that is not possible, most browsers at least firefox3.0 do not allow fullpath to be seen, so even from JavaScript side you can not get full path
If you could get full path you can send it to server, but I think you will have to be satisfied with file name
|
Get original path from django filefield
|
My django app accepts two files (in this case a jad and jar combo). Is there a way I can preserve the folders they came from?
I need this so I can check later that they came from the same path.
(And later on accept a whole load of files and be able to work out which came from the same folder).
|
[
"I think that is not possible, most browsers at least firefox3.0 do not allow fullpath to be seen, so even from JavaScript side you can not get full path\nIf you could get full path you can send it to server, but I think you will have to be satisfied with file name\n"
] |
[
2
] |
[] |
[] |
[
"django",
"field",
"file",
"forms",
"python"
] |
stackoverflow_0000981371_django_field_file_forms_python.txt
|
Q:
windows command line and Python
I have a python script that i want to run from the command line but unsure how to run it. Thanks :)
A:
I do it this way:
C:\path\to\folder> yourscript.py
A:
python myscript.py
A:
See Basic Hints for Windows Command Line Programming.
If your python installation directory is included in %PATH% -
C:\> python myscript.py
If you know the installation path:
C:\> C:\python26\python myscript.py
And, you can insert a hashbang in the 1st line of the script:
#! C:\python26\python
and it will run by typing just the script name. This is the content of p.py:
#!C:\python26\python
import sys
print sys.path
And calling it directly from a cmd.exe window:
C:\>p.py
['C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs',
'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win',
'C:\\Python26', 'C:\\Python26\\lib\\site-packages',
'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib]
A:
If your script is foo.py, you can simply do
C:\Python25\python.exe foo.py
Assuming you have python 2.5 installed in the default location. Alternatively, you can add C:\Python25 to your %PATH%, so that:
python foo.py
will work. But be aware that changing %PATH% may affect applications (that's why it is not done by the python installer by default).
A:
You might find it useful to include a .bat file which calls the .py script. Then all you need to do is to type the name of your script to run it.
Try something like:
python %~dp0\%~n0.py %*
(From http://wiki.tcl.tk/2455)
A:
do you have python installed? if not
install it from python.org
on command line use
python "path to
script.py"
if python is not in PATH
list you can add it to PATH in
environment variables or directly
use path to python.exe e.g.
c:\python25\python.exe myscript.py
|
windows command line and Python
|
I have a python script that i want to run from the command line but unsure how to run it. Thanks :)
|
[
"I do it this way:\nC:\\path\\to\\folder> yourscript.py\n\n",
"python myscript.py\n",
"See Basic Hints for Windows Command Line Programming.\nIf your python installation directory is included in %PATH% -\nC:\\> python myscript.py\n\nIf you know the installation path:\nC:\\> C:\\python26\\python myscript.py\n\nAnd, you can insert a hashbang in the 1st line of the script:\n#! C:\\python26\\python\n\nand it will run by typing just the script name. This is the content of p.py:\n#!C:\\python26\\python\nimport sys\nprint sys.path\n\nAnd calling it directly from a cmd.exe window:\nC:\\>p.py\n['C:\\\\WINDOWS\\\\system32\\\\python26.zip', 'C:\\\\Python26\\\\DLLs',\n'C:\\\\Python26\\\\lib', 'C:\\\\Python26\\\\lib\\\\plat-win',\n'C:\\\\Python26', 'C:\\\\Python26\\\\lib\\\\site-packages', \n'C:\\\\Python26\\\\lib\\\\site-packages\\\\win32', 'C:\\\\Python26\\\\lib]\n\n",
"If your script is foo.py, you can simply do\nC:\\Python25\\python.exe foo.py\n\nAssuming you have python 2.5 installed in the default location. Alternatively, you can add C:\\Python25 to your %PATH%, so that:\npython foo.py\n\nwill work. But be aware that changing %PATH% may affect applications (that's why it is not done by the python installer by default).\n",
"You might find it useful to include a .bat file which calls the .py script. Then all you need to do is to type the name of your script to run it.\nTry something like:\npython %~dp0\\%~n0.py %*\n(From http://wiki.tcl.tk/2455)\n",
"\ndo you have python installed? if not\ninstall it from python.org\non command line use \npython \"path to\n script.py\"\nif python is not in PATH\n list you can add it to PATH in\n environment variables or directly\n use path to python.exe e.g. \n c:\\python25\\python.exe myscript.py\n\n\n"
] |
[
4,
3,
3,
2,
1,
0
] |
[] |
[] |
[
"command_line",
"python",
"windows"
] |
stackoverflow_0000981691_command_line_python_windows.txt
|
Q:
Using a Django custom model method property in order_by()
I'm currently learning Django and some of my models have custom methods to get values formatted in a specific way. Is it possible to use the value of one of these custom methods that I've defined as a property in a model with order_by()?
Here is an example that demonstrates how the property is implemented.
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
def _get_full_name(self):
return u'%s %s' % (self.first_name, self.last_name)
full_name = property(_get_full_name)
def __unicode__(self):
return self.full_name
With this model I can do:
>>> Author.objects.all()
[<Author: John Doh>, <Author: Jane Doh>, <Author: Andre Miller>]
>>> Author.objects.order_by('first_name')
[<Author: Andre Miller>, <Author: Jane Doh>, <Author: John Doh>]
But I cannot do:
>>> Author.objects.order_by('full_name')
FieldError: Cannot resolve keyword 'full_name' into field. Choices are: book, email, first_name, id, last_name
What would be the correct way to use order_by on a custom property like this?
A:
No, you can't do that. order_by is applied at the database level, but the database can't know anything about your custom Python methods.
You can either use the separate fields to order:
Author.objects.order_by('first_name', 'last_name')
or do the ordering in Python:
sorted(Author.objects.all(), key=lambda a: a.full_name)
|
Using a Django custom model method property in order_by()
|
I'm currently learning Django and some of my models have custom methods to get values formatted in a specific way. Is it possible to use the value of one of these custom methods that I've defined as a property in a model with order_by()?
Here is an example that demonstrates how the property is implemented.
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
def _get_full_name(self):
return u'%s %s' % (self.first_name, self.last_name)
full_name = property(_get_full_name)
def __unicode__(self):
return self.full_name
With this model I can do:
>>> Author.objects.all()
[<Author: John Doh>, <Author: Jane Doh>, <Author: Andre Miller>]
>>> Author.objects.order_by('first_name')
[<Author: Andre Miller>, <Author: Jane Doh>, <Author: John Doh>]
But I cannot do:
>>> Author.objects.order_by('full_name')
FieldError: Cannot resolve keyword 'full_name' into field. Choices are: book, email, first_name, id, last_name
What would be the correct way to use order_by on a custom property like this?
|
[
"No, you can't do that. order_by is applied at the database level, but the database can't know anything about your custom Python methods.\nYou can either use the separate fields to order:\nAuthor.objects.order_by('first_name', 'last_name')\n\nor do the ordering in Python:\nsorted(Author.objects.all(), key=lambda a: a.full_name)\n\n"
] |
[
80
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0000981375_django_django_models_python.txt
|
Q:
python recursive class inclusion & instantiation
I would like to import
classes located into a folder named
some-dir/
and named class*.py
and finally instantiate them.
Wich is the best way to look inside the folder, import classes
and instantiate them?
A:
Try:
import os
#get files
files = os.listdir("some-dir/")
classes = []
for f in files:
#find python modules in file listing
if(f.find(".py") != -1):
#remove file extenstion
f = f.rstrip(".py")
#create string to add module to global namespace, import it and instantiate
#class
importStr = "global " + f +";import " + f + "; classes.append(" + f +"())"
#execute the code
exec(importStr)
That's a first stab at it. This assumes you don't have any parameters to pass to the class instantiation.
Don't know if it works, but it's somewhere to start. The "exec" statement lets you execute strings as python code.
Hope this helps you in the right direction.
|
python recursive class inclusion & instantiation
|
I would like to import
classes located into a folder named
some-dir/
and named class*.py
and finally instantiate them.
Wich is the best way to look inside the folder, import classes
and instantiate them?
|
[
"Try:\nimport os\n#get files\nfiles = os.listdir(\"some-dir/\")\nclasses = []\nfor f in files:\n #find python modules in file listing\n if(f.find(\".py\") != -1):\n #remove file extenstion\n f = f.rstrip(\".py\")\n #create string to add module to global namespace, import it and instantiate\n #class\n importStr = \"global \" + f +\";import \" + f + \"; classes.append(\" + f +\"())\"\n #execute the code\n exec(importStr) \n\nThat's a first stab at it. This assumes you don't have any parameters to pass to the class instantiation.\nDon't know if it works, but it's somewhere to start. The \"exec\" statement lets you execute strings as python code.\nHope this helps you in the right direction.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000982038_python.txt
|
Q:
Executing shell commands as given UID in Python
I need a way to execute the os.system() module as different UID's. It would need to behave similar to the following BASH code (note these are not the exact commands I am executing):
su user1
ls ~
mv file1
su user2
ls ~
mv file1
The target platform is GNU Linux Generic.
Of course I could just pass these to the os.system module, but how to send the password? Of course I could run the script as root, but that's sloppy and insecure.
Preferably I would like to do with without requiring any passwords to be in plain text.
A:
I think that's not trivial: you can do that with a shell because each command is launched into its own process, which has its own id. But with python, everything will have the uid of the python interpreted process (of course, assuming you don't launch subprocesses using the subprocess module and co). I don't know a way of changing the user of a process - I don't know if that's even possible - even if it were, you would at least need admin privileges.
What are you trying to do exactly ? This does not sound like the right thing to do for admin purpose, for example. Generally, admin scripts run in a priviledge user - because nobody knows the password of user 2 except user 2 (in theory). Being root means su user always work for a 'normal' user, without requesting password.
A:
maybe sudo can help you here, otherwise you must be root to execute os.setuid
alternatively if you want to have fun you can use pexpect to do things
something like this, you can improve over this
p = pexpect.spawn("su guest")
p.logfile = sys.stdout
p.expect('Password:')
p.sendline("guest")
A:
The function you're looking for is called os.seteuid. I'm afraid you probably won't escape executing the script as root, in any case, but I think you can use the capabilities(7) framework to 'fence in' the execution a little, so that it can change users--but not do any of the other things the superuser can.
Alternatively, you might be able to do this with PAM. But generally speaking, there's no 'neat' way to do this, and David Cournapeau is absolutely right that it's traditional for admin scripts to run with privileges.
A:
Somewhere along the line, some process or other is going to need an effective UID of 0 (root), because only such a process can set the effective UID to an arbitrary other UID.
At the shell, the su command is a SUID root program; it is appropriately privileged (POSIX jargon) and can set the real and effective UID. Similarly, the sudo command can do the same job. With sudo, you can also configure which commands and UID are allowed. The crucial difference is that su requires the target user's password to let you in; sudo requires the password of the user running it.
There is, of course, the issue of whether a user should know the passwords of other users. In general, no user should know any other user's password.
Scripting UID changes is hard. You can do:
su altuser -c "commands to execute as altuser"
sudo -u altuser commands to execute as altuser
However, su will demand a password from the controlling terminal (and will fail if there is no controlling terminal). If you use sudo, it will cache credentials (or can be configured to do so) so you only get asked once for a password - but it will prompt the first time just like su does.
Working around the prompting is hard. You can use tools parallel to expect which handle pseudo-ttys for you. However, you are then faced with storing passwords in scripts (not a good idea) or somehow stashing them out of sight.
The tool I use for the job is one I wrote, called asroot. It allows me to control precisely the UID and GID attributes that the child process should have. But it is designed to only allow me to use it - that is, at compile time, the authorized username is specified (of course, that can be changed). However, I can do things like:
asroot -u someone -g theirgrp -C -A othergrp -m 022 -- somecmd arg1 ...
This sets the real and effective UID to 'someone', sets the primary group to 'theirgrp', removes all auxilliary groups, and adds 'othergrp' (so the process belongs to just two groups) and sets the umask to 0222; it then executes 'somecmd' with the arguments given.
For a specific user who needs limited (or not so limited) access to other user accounts, this works well. As a general solution, it is not so hot; sudo is better in most respects, but still requires a password (which asroot does not).
|
Executing shell commands as given UID in Python
|
I need a way to execute the os.system() module as different UID's. It would need to behave similar to the following BASH code (note these are not the exact commands I am executing):
su user1
ls ~
mv file1
su user2
ls ~
mv file1
The target platform is GNU Linux Generic.
Of course I could just pass these to the os.system module, but how to send the password? Of course I could run the script as root, but that's sloppy and insecure.
Preferably I would like to do with without requiring any passwords to be in plain text.
|
[
"I think that's not trivial: you can do that with a shell because each command is launched into its own process, which has its own id. But with python, everything will have the uid of the python interpreted process (of course, assuming you don't launch subprocesses using the subprocess module and co). I don't know a way of changing the user of a process - I don't know if that's even possible - even if it were, you would at least need admin privileges.\nWhat are you trying to do exactly ? This does not sound like the right thing to do for admin purpose, for example. Generally, admin scripts run in a priviledge user - because nobody knows the password of user 2 except user 2 (in theory). Being root means su user always work for a 'normal' user, without requesting password.\n",
"maybe sudo can help you here, otherwise you must be root to execute os.setuid\nalternatively if you want to have fun you can use pexpect to do things\nsomething like this, you can improve over this\np = pexpect.spawn(\"su guest\")\np.logfile = sys.stdout \np.expect('Password:')\np.sendline(\"guest\")\n\n",
"The function you're looking for is called os.seteuid. I'm afraid you probably won't escape executing the script as root, in any case, but I think you can use the capabilities(7) framework to 'fence in' the execution a little, so that it can change users--but not do any of the other things the superuser can.\nAlternatively, you might be able to do this with PAM. But generally speaking, there's no 'neat' way to do this, and David Cournapeau is absolutely right that it's traditional for admin scripts to run with privileges.\n",
"Somewhere along the line, some process or other is going to need an effective UID of 0 (root), because only such a process can set the effective UID to an arbitrary other UID.\nAt the shell, the su command is a SUID root program; it is appropriately privileged (POSIX jargon) and can set the real and effective UID. Similarly, the sudo command can do the same job. With sudo, you can also configure which commands and UID are allowed. The crucial difference is that su requires the target user's password to let you in; sudo requires the password of the user running it.\nThere is, of course, the issue of whether a user should know the passwords of other users. In general, no user should know any other user's password.\nScripting UID changes is hard. You can do:\nsu altuser -c \"commands to execute as altuser\"\nsudo -u altuser commands to execute as altuser\n\nHowever, su will demand a password from the controlling terminal (and will fail if there is no controlling terminal). If you use sudo, it will cache credentials (or can be configured to do so) so you only get asked once for a password - but it will prompt the first time just like su does.\nWorking around the prompting is hard. You can use tools parallel to expect which handle pseudo-ttys for you. However, you are then faced with storing passwords in scripts (not a good idea) or somehow stashing them out of sight.\n\nThe tool I use for the job is one I wrote, called asroot. It allows me to control precisely the UID and GID attributes that the child process should have. But it is designed to only allow me to use it - that is, at compile time, the authorized username is specified (of course, that can be changed). However, I can do things like:\nasroot -u someone -g theirgrp -C -A othergrp -m 022 -- somecmd arg1 ...\n\nThis sets the real and effective UID to 'someone', sets the primary group to 'theirgrp', removes all auxilliary groups, and adds 'othergrp' (so the process belongs to just two groups) and sets the umask to 0222; it then executes 'somecmd' with the arguments given.\nFor a specific user who needs limited (or not so limited) access to other user accounts, this works well. As a general solution, it is not so hot; sudo is better in most respects, but still requires a password (which asroot does not).\n"
] |
[
3,
2,
1,
1
] |
[] |
[] |
[
"linux",
"os.system",
"permissions",
"python"
] |
stackoverflow_0000981052_linux_os.system_permissions_python.txt
|
Q:
How to tractably solve the assignment optimisation task
I'm working on a script that takes the elements from companies and pairs them up with the elements of people. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary ctrPairs).
They're all paired in a 1:1, each company has only one person and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a memoization table (memDict) to avoid recomputing areas that have already been solved.
I believe that I could vastly improve the speed of what's going on here but I'm not really sure how. Areas I'm worried about are marked with #slow?, any advice would be appreciated (the script works for inputs of lists n<15 but it gets incredibly slow for n > ~15)
def getMaxCTR(companies, people):
if(memDict.has_key((companies,people))):
return memDict[(companies,people)] #here's where we return the memoized version if it exists
if(not len(companies) or not len(people)):
return 0
maxCTR = None
remainingCompanies = companies[1:len(companies)] #slow?
for p in people:
remainingPeople = list(people) #slow?
remainingPeople.remove(p) #slow?
ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
if(ctr > maxCTR):
maxCTR = ctr
memDict[(companies,people)] = maxCTR
return maxCTR
A:
To all those who wonder about the use of learning theory, this question is a good illustration. The right question is not about a "fast way to bounce between lists and tuples in python" — the reason for the slowness is something deeper.
What you're trying to solve here is known as the assignment problem: given two lists of n elements each and n×n values (the value of each pair), how to assign them so that the total "value" is maximized (or equivalently, minimized). There are several algorithms for this, such as the Hungarian algorithm (Python implementation), or you could solve it using more general min-cost flow algorithms, or even cast it as a linear program and use an LP solver. Most of these would have a running time of O(n3).
What your algorithm above does is to try each possible way of pairing them. (The memoisation only helps to avoid recomputing answers for pairs of subsets, but you're still looking at all pairs of subsets.) This approach is at least Ω(n222n). For n=16, n3 is 4096 and n222n is 1099511627776. There are constant factors in each algorithm of course, but see the difference? :-) (The approach in the question is still better than the naive O(n!), which would be much worse.) Use one of the O(n^3) algorithms, and I predict it should run in time for up to n=10000 or so, instead of just up to n=15.
"Premature optimization is the root of all evil", as Knuth said, but so is delayed/overdue optimization: you should first carefully consider an appropriate algorithm before implementing it, not pick a bad one and then wonder what parts of it are slow. :-) Even badly implementing a good algorithm in Python would be orders of magnitude faster than fixing all the "slow?" parts of the code above (e.g., by rewriting in C).
A:
i see two issues here:
efficiency: you're recreating the same remainingPeople sublists for each company. it would be better to create all the remainingPeople and all the remainingCompanies once and then do all the combinations.
memoization: you're using tuples instead of lists to use them as dict keys for memoization; but tuple identity is order-sensitive. IOW: (1,2) != (2,1) you better use sets and frozensets for this: frozenset((1,2)) == frozenset((2,1))
A:
This line:
remainingCompanies = companies[1:len(companies)]
Can be replaced with this line:
remainingCompanies = companies[1:]
For a very slight speed increase. That's the only improvement I see.
A:
If you want to get a copy of a tuple as a list you can do
mylist = list(mytuple)
|
How to tractably solve the assignment optimisation task
|
I'm working on a script that takes the elements from companies and pairs them up with the elements of people. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary ctrPairs).
They're all paired in a 1:1, each company has only one person and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a memoization table (memDict) to avoid recomputing areas that have already been solved.
I believe that I could vastly improve the speed of what's going on here but I'm not really sure how. Areas I'm worried about are marked with #slow?, any advice would be appreciated (the script works for inputs of lists n<15 but it gets incredibly slow for n > ~15)
def getMaxCTR(companies, people):
if(memDict.has_key((companies,people))):
return memDict[(companies,people)] #here's where we return the memoized version if it exists
if(not len(companies) or not len(people)):
return 0
maxCTR = None
remainingCompanies = companies[1:len(companies)] #slow?
for p in people:
remainingPeople = list(people) #slow?
remainingPeople.remove(p) #slow?
ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
if(ctr > maxCTR):
maxCTR = ctr
memDict[(companies,people)] = maxCTR
return maxCTR
|
[
"To all those who wonder about the use of learning theory, this question is a good illustration. The right question is not about a \"fast way to bounce between lists and tuples in python\" — the reason for the slowness is something deeper.\nWhat you're trying to solve here is known as the assignment problem: given two lists of n elements each and n×n values (the value of each pair), how to assign them so that the total \"value\" is maximized (or equivalently, minimized). There are several algorithms for this, such as the Hungarian algorithm (Python implementation), or you could solve it using more general min-cost flow algorithms, or even cast it as a linear program and use an LP solver. Most of these would have a running time of O(n3).\nWhat your algorithm above does is to try each possible way of pairing them. (The memoisation only helps to avoid recomputing answers for pairs of subsets, but you're still looking at all pairs of subsets.) This approach is at least Ω(n222n). For n=16, n3 is 4096 and n222n is 1099511627776. There are constant factors in each algorithm of course, but see the difference? :-) (The approach in the question is still better than the naive O(n!), which would be much worse.) Use one of the O(n^3) algorithms, and I predict it should run in time for up to n=10000 or so, instead of just up to n=15. \n\"Premature optimization is the root of all evil\", as Knuth said, but so is delayed/overdue optimization: you should first carefully consider an appropriate algorithm before implementing it, not pick a bad one and then wonder what parts of it are slow. :-) Even badly implementing a good algorithm in Python would be orders of magnitude faster than fixing all the \"slow?\" parts of the code above (e.g., by rewriting in C).\n",
"i see two issues here:\n\nefficiency: you're recreating the same remainingPeople sublists for each company. it would be better to create all the remainingPeople and all the remainingCompanies once and then do all the combinations.\nmemoization: you're using tuples instead of lists to use them as dict keys for memoization; but tuple identity is order-sensitive. IOW: (1,2) != (2,1) you better use sets and frozensets for this: frozenset((1,2)) == frozenset((2,1))\n\n",
"This line:\nremainingCompanies = companies[1:len(companies)]\nCan be replaced with this line:\nremainingCompanies = companies[1:]\n\nFor a very slight speed increase. That's the only improvement I see.\n",
"If you want to get a copy of a tuple as a list you can do\nmylist = list(mytuple)\n"
] |
[
20,
1,
0,
0
] |
[] |
[] |
[
"algorithm",
"dynamic_programming",
"optimization",
"python"
] |
stackoverflow_0000982127_algorithm_dynamic_programming_optimization_python.txt
|
Q:
How can I search and replace in XML with Python?
I am in the middle of making a script for doing translation of xml documents. It's actually pretty cool, the idea is (and it is working) to take an xml file (or a folder of xml files) and open it, parse the xml, get whatever is in between some tags and using the google translate api's translate it and replace the content of the xml files.
As I said, I have this working, but only in fairly strict xml formatted documents, now I have to make it compatible with documents formatted differently. So my idea was:
Parse the xml, find a node, e.g:
<template>lorem lipsum dolor mit amet<think><set name="she">Ada</set></think></template>
Save this as a string, do some regex search and replace on this string. But i sadly have no clue on how to proceed. I want to search to the string (xml node) find text that is inbetween tags, in this case "lorem lipsum dolor mit amet" and "Ada", call a function with those text's as a parameter and then insert the result of the function in the same place as it originated from.
The reason i cant just get the text and rebuild the xml formatting is that there will be differently formatted xml nodes so i need it to be identical...
A:
Don't try to parse XML using regular expressions! XML is not regular and therefore regular expressions are not suited to doing this kind of task.
Use an actual XML parser. Many of these are readily available for Python. A quick search has lead me to this SO question which covers how to use XPath in Python.
A:
ElementTree would be a good choice for this kind of parsing. It is easy to use and lightweight and supports outputting XML after you do operations on it (as simple as calling write()). It comes packaged with Python standard libraries in the latest versions (I believe 2.6+).
|
How can I search and replace in XML with Python?
|
I am in the middle of making a script for doing translation of xml documents. It's actually pretty cool, the idea is (and it is working) to take an xml file (or a folder of xml files) and open it, parse the xml, get whatever is in between some tags and using the google translate api's translate it and replace the content of the xml files.
As I said, I have this working, but only in fairly strict xml formatted documents, now I have to make it compatible with documents formatted differently. So my idea was:
Parse the xml, find a node, e.g:
<template>lorem lipsum dolor mit amet<think><set name="she">Ada</set></think></template>
Save this as a string, do some regex search and replace on this string. But i sadly have no clue on how to proceed. I want to search to the string (xml node) find text that is inbetween tags, in this case "lorem lipsum dolor mit amet" and "Ada", call a function with those text's as a parameter and then insert the result of the function in the same place as it originated from.
The reason i cant just get the text and rebuild the xml formatting is that there will be differently formatted xml nodes so i need it to be identical...
|
[
"Don't try to parse XML using regular expressions! XML is not regular and therefore regular expressions are not suited to doing this kind of task.\nUse an actual XML parser. Many of these are readily available for Python. A quick search has lead me to this SO question which covers how to use XPath in Python.\n",
"ElementTree would be a good choice for this kind of parsing. It is easy to use and lightweight and supports outputting XML after you do operations on it (as simple as calling write()). It comes packaged with Python standard libraries in the latest versions (I believe 2.6+).\n"
] |
[
7,
5
] |
[] |
[] |
[
"python",
"regex",
"xml"
] |
stackoverflow_0000982414_python_regex_xml.txt
|
Q:
Threads in Java and Python
i have few questions about threads in Python and Java...
Is it possible to give priorities to Python threads, as it is in Java?
How can I kill, stop, suspend and interrupt thread in Python?
Thread groups - what are they really for? Does Python support them too?
Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python?
Tnx!
A:
Assuming we're talking about the classic (CPython) implementation:
no, no priorities in Python's threads
you can't do any of these things to a thread in Python
no thread groups in Python
you can use many approaches, such as locks, but the recommended approach is generally to use the Queue module from the standard library (and limit your threads' interactions to what Queue lets you program)
In other words, Python threads are really much less rich than Java's -- not to mention that only one thread per process can in fact run Python code (others may be running C code or waiting).
For anything fancy, i.e. anything beyond Python's limited threading capabilities, it's recommended you use the multiprocessing module from the standard library -- or switch to implementations of Python that let you use richer threading approaches, such as Jython for the JVM or IronPython for .NET.
A:
Regular java thread priorities can't be counted on. You may find a lower priority thread running when a higher priority thread is ready and waiting.
There is something called "realtime java" (see http://www.rtsj.org) which does enforce thread priority, at least for the RealtimeThread class. Regular java.lang.Thread may still not enforce true priority ordering.
A:
I felt the need to debunk the common myths perpetuated here:
Is it possible to give priorities to Python threads, as it is in Java?
Not in the OS sense. But you can use cooperative multitasking and your own custom scheduler to ensure that certain threads use more time. You can also set the timeslices between a thread with this:
http://docs.python.org/library/sys.html#sys.setcheckinterval
How can I kill, stop, suspend and interrupt thread in Python?
Note that you can do it. Its just difficult, and people will wax philosophical about how it is evil. But this is true in any language. You can either use the following API function:
http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc
Or you can use your underlying OS like TerminateThread in windows off the TID. Just be sure to acquire the global lock.
Thread groups - what are they really for? Does Python support them too?
I don't believe so. They are for controlling groups of threads.
Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python?
Read the thread and threading module.
A:
here's an example of how I allow my threads to be halted (only works for threads within loops really, unless you wanted to place an if "self.alive" before every line):
import threading, Queue
class HaltableThread(object.Thread):
def __init__(self):
self.stringQueue = Queue.Queue()
self.alive = True
def run(self):
while self.alive:
try:
data = self.stringQueue.read(0.01) #100ms block until data
except Queue.Empty:
pass
else:
print data
def stop(self):
self.alive = False
A:
Just a sidestep about point 1 here, because Java Thread priorities might not work as one would expect.
From the SCJP guide:
Because thread-scheduling priority behaviour is not guaranteed, use thread priorities as a way to improve the efficiency of your program, but just be sure your program doesn't depend on that behaviour for correctness.
A:
Unfortunately the standard Python package has something called the GIL, or global interpreter lock. This means only one of your threads will ever be running at a time. That being said, simple multithreaded applications are possible and pretty easy to write. The threading module contains basic synchronization primitives like mutexes, sempahores, etc.
There is also an awesome with statement that automates most aspects of lock usages. For an example:
import threading
myLock = threading.Lock()
Then to use the lock:
with myLock:
#lock has now been acquired
print "I have the lock and can now to fun stuff"
print "The lock has been released"
|
Threads in Java and Python
|
i have few questions about threads in Python and Java...
Is it possible to give priorities to Python threads, as it is in Java?
How can I kill, stop, suspend and interrupt thread in Python?
Thread groups - what are they really for? Does Python support them too?
Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python?
Tnx!
|
[
"Assuming we're talking about the classic (CPython) implementation:\n\nno, no priorities in Python's threads\nyou can't do any of these things to a thread in Python\nno thread groups in Python\nyou can use many approaches, such as locks, but the recommended approach is generally to use the Queue module from the standard library (and limit your threads' interactions to what Queue lets you program)\n\nIn other words, Python threads are really much less rich than Java's -- not to mention that only one thread per process can in fact run Python code (others may be running C code or waiting).\nFor anything fancy, i.e. anything beyond Python's limited threading capabilities, it's recommended you use the multiprocessing module from the standard library -- or switch to implementations of Python that let you use richer threading approaches, such as Jython for the JVM or IronPython for .NET.\n",
"Regular java thread priorities can't be counted on. You may find a lower priority thread running when a higher priority thread is ready and waiting. \nThere is something called \"realtime java\" (see http://www.rtsj.org) which does enforce thread priority, at least for the RealtimeThread class. Regular java.lang.Thread may still not enforce true priority ordering.\n",
"I felt the need to debunk the common myths perpetuated here:\n\nIs it possible to give priorities to Python threads, as it is in Java?\n\nNot in the OS sense. But you can use cooperative multitasking and your own custom scheduler to ensure that certain threads use more time. You can also set the timeslices between a thread with this: \nhttp://docs.python.org/library/sys.html#sys.setcheckinterval\n\nHow can I kill, stop, suspend and interrupt thread in Python?\n\nNote that you can do it. Its just difficult, and people will wax philosophical about how it is evil. But this is true in any language. You can either use the following API function:\nhttp://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc\nOr you can use your underlying OS like TerminateThread in windows off the TID. Just be sure to acquire the global lock.\n\nThread groups - what are they really for? Does Python support them too?\n\nI don't believe so. They are for controlling groups of threads.\n\nSynchronization - in Java we use simply keyword synchorinized for a method, object...What about Python?\n\nRead the thread and threading module.\n",
"here's an example of how I allow my threads to be halted (only works for threads within loops really, unless you wanted to place an if \"self.alive\" before every line):\nimport threading, Queue\n\nclass HaltableThread(object.Thread):\n def __init__(self):\n self.stringQueue = Queue.Queue()\n self.alive = True\n def run(self):\n while self.alive:\n try:\n data = self.stringQueue.read(0.01) #100ms block until data\n except Queue.Empty:\n pass\n else:\n print data\n def stop(self):\n self.alive = False\n\n",
"Just a sidestep about point 1 here, because Java Thread priorities might not work as one would expect.\nFrom the SCJP guide:\n\nBecause thread-scheduling priority behaviour is not guaranteed, use thread priorities as a way to improve the efficiency of your program, but just be sure your program doesn't depend on that behaviour for correctness.\n\n",
"Unfortunately the standard Python package has something called the GIL, or global interpreter lock. This means only one of your threads will ever be running at a time. That being said, simple multithreaded applications are possible and pretty easy to write. The threading module contains basic synchronization primitives like mutexes, sempahores, etc. \nThere is also an awesome with statement that automates most aspects of lock usages. For an example:\nimport threading\nmyLock = threading.Lock()\n\nThen to use the lock:\nwith myLock:\n #lock has now been acquired\n print \"I have the lock and can now to fun stuff\"\nprint \"The lock has been released\"\n\n"
] |
[
12,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"java",
"multithreading",
"python"
] |
stackoverflow_0000970909_java_multithreading_python.txt
|
Q:
Django/Python EnvironmentError?
I am getting an error when I try to use syncdb:
python manage.py syncdb
Error message:
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 83, in __init__
raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
EnvironmentError: Could not import settings '/home/simi/workspace/hssn_svn/hssn' (Is it on sys.path? Does ti have syntax errors?): Import by filename is not supported.
I'm a newbie with Django/Python, but I can't figure this error out after having researched online for a while now.
A:
Your trace states:
Import by filename is not supported.
Which might indicate that you try to import (or maybe set the DJANGO_SETTINGS_MODULE) to the full python filename, where it should be a module path: your.module.settings
You could also try to specify your DJANGO_SETTINGS_MODULE directly from command line, like:
$ DJANGO_SETTINGS_MODULE=your.module.settings ./manage.py syncdb
A:
Make sure your settings.py file is in the same directory as manage.py (you will also have to run manage.py from this directory, i.e. ./manage.py syncdb), or make the environment variable DJANGO_SETTINGS_MODULE point to it.
A:
Another thing that gives this error is permissions - very hard to track down.
Solution for me was to move <myproject> to /var/www/<myproject>
and do chown -R root:root /var/www/<myproject>
|
Django/Python EnvironmentError?
|
I am getting an error when I try to use syncdb:
python manage.py syncdb
Error message:
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 83, in __init__
raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
EnvironmentError: Could not import settings '/home/simi/workspace/hssn_svn/hssn' (Is it on sys.path? Does ti have syntax errors?): Import by filename is not supported.
I'm a newbie with Django/Python, but I can't figure this error out after having researched online for a while now.
|
[
"Your trace states:\nImport by filename is not supported.\n\nWhich might indicate that you try to import (or maybe set the DJANGO_SETTINGS_MODULE) to the full python filename, where it should be a module path: your.module.settings\nYou could also try to specify your DJANGO_SETTINGS_MODULE directly from command line, like:\n$ DJANGO_SETTINGS_MODULE=your.module.settings ./manage.py syncdb\n\n",
"Make sure your settings.py file is in the same directory as manage.py (you will also have to run manage.py from this directory, i.e. ./manage.py syncdb), or make the environment variable DJANGO_SETTINGS_MODULE point to it.\n",
"Another thing that gives this error is permissions - very hard to track down.\nSolution for me was to move <myproject> to /var/www/<myproject>\nand do chown -R root:root /var/www/<myproject>\n"
] |
[
12,
1,
1
] |
[] |
[] |
[
"django",
"django_syncdb",
"python"
] |
stackoverflow_0000911085_django_django_syncdb_python.txt
|
Q:
Using sphinx/miktex to generate pdf files that displays UTF8 Japanese (CJK) text in windows
I have documentation in ReSt (UTF8) and I'm using sphinx to generate HTML and latex files.
(No issues with html conversion)
I then want to convert the resulting latex file to PDf. Currently I'm using MiKTeX
2.7's pdflatex.exe command to perfom this conversion. (Converting a source file without Japanese characters produces the expected pdf correctly)
Using the MiKTeX Package Manager I've installed the cjk related packages: cjk-fonts, miktex-cjkutils-bin-2.7, and cjk.
To debug I'm using the following sample:
\documentclass{article}
\usepackage{CJK}
\begin{document}
\begin{CJK}{UTF8}{song}
\noindent Hello World!
\noindent Καλημέρα κόσμε
\noindent こんにちは 世界
\end{CJK}
\end{document}
Running pdflatex.exe on this file produces the following output:
pdflatex jutf8.tex jutf8.pdf
This is pdfTeX, Version 3.1415926-1.40.8-beta-20080627 (MiKTeX 2.7)
entering extended mode
(jutf8.tex
LaTeX2e <2005/12/01>
Babel <v3.8j> and hyphenation patterns for english, dumylang, nohyphenation, ge
rman, ngerman, german-x-2008-06-18, ngerman-x-2008-06-18, french, loaded.
! LaTeX Error: Missing \begin{document}.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.2
サソ\documentclass{article}
?
("C:\Program Files\MiKTeX 2.7\tex\latex\base\article.cls"
Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
("C:\Program Files\MiKTeX 2.7\tex\latex\base\size10.clo")
Overfull \hbox (20.0pt too wide) in paragraph at lines 2--284
[]
[1{D:/Profiles/All Users/Application Data/MiKTeX/2.7/pdftex/config/pdftex.map}]
) ("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.sty"
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\mule\MULEenc.sty")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.enc")) (jutf8.aux)
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.bdg")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.enc")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.chr")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\c70song.fd")Running makemf...
makemf: The cyberb source file could not be found.
Running hbf2gf...
hbf2gf (CJK ver. 4.7.0)
Couldn't find `cyberb.cfg'
maketfm: No creation rule for font cyberb03.
! Font C70/song/m/n/10/03=cyberb03 at 10.0pt not loadable: Metric (TFM) file no
t found.
<to be read again>
relax
l.12 \noindent ホ
ホアホサホキホシホュマ∃ア ホコマ狐πシホオ
How can I get Japanese to display properly in the resulting pdf using MiKTeX/pdflatex.exe?
A:
I would use xelatex (available in MikTeX since 2.7) instead of pdflatex and an OpenType Kanji font. The file text.tex consisting of
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Sazanami Gothic}
\begin{document}
こんにちは 世界
\end{document}
compiles with "xelatex text" to a PDF with this text in Sazanami Gothic font.
|
Using sphinx/miktex to generate pdf files that displays UTF8 Japanese (CJK) text in windows
|
I have documentation in ReSt (UTF8) and I'm using sphinx to generate HTML and latex files.
(No issues with html conversion)
I then want to convert the resulting latex file to PDf. Currently I'm using MiKTeX
2.7's pdflatex.exe command to perfom this conversion. (Converting a source file without Japanese characters produces the expected pdf correctly)
Using the MiKTeX Package Manager I've installed the cjk related packages: cjk-fonts, miktex-cjkutils-bin-2.7, and cjk.
To debug I'm using the following sample:
\documentclass{article}
\usepackage{CJK}
\begin{document}
\begin{CJK}{UTF8}{song}
\noindent Hello World!
\noindent Καλημέρα κόσμε
\noindent こんにちは 世界
\end{CJK}
\end{document}
Running pdflatex.exe on this file produces the following output:
pdflatex jutf8.tex jutf8.pdf
This is pdfTeX, Version 3.1415926-1.40.8-beta-20080627 (MiKTeX 2.7)
entering extended mode
(jutf8.tex
LaTeX2e <2005/12/01>
Babel <v3.8j> and hyphenation patterns for english, dumylang, nohyphenation, ge
rman, ngerman, german-x-2008-06-18, ngerman-x-2008-06-18, french, loaded.
! LaTeX Error: Missing \begin{document}.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.2
サソ\documentclass{article}
?
("C:\Program Files\MiKTeX 2.7\tex\latex\base\article.cls"
Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
("C:\Program Files\MiKTeX 2.7\tex\latex\base\size10.clo")
Overfull \hbox (20.0pt too wide) in paragraph at lines 2--284
[]
[1{D:/Profiles/All Users/Application Data/MiKTeX/2.7/pdftex/config/pdftex.map}]
) ("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.sty"
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\mule\MULEenc.sty")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.enc")) (jutf8.aux)
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.bdg")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.enc")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.chr")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\c70song.fd")Running makemf...
makemf: The cyberb source file could not be found.
Running hbf2gf...
hbf2gf (CJK ver. 4.7.0)
Couldn't find `cyberb.cfg'
maketfm: No creation rule for font cyberb03.
! Font C70/song/m/n/10/03=cyberb03 at 10.0pt not loadable: Metric (TFM) file no
t found.
<to be read again>
relax
l.12 \noindent ホ
ホアホサホキホシホュマ∃ア ホコマ狐πシホオ
How can I get Japanese to display properly in the resulting pdf using MiKTeX/pdflatex.exe?
|
[
"I would use xelatex (available in MikTeX since 2.7) instead of pdflatex and an OpenType Kanji font. The file text.tex consisting of\n\n\\documentclass{article}\n\\usepackage{fontspec}\n\\setmainfont{Sazanami Gothic}\n\n\\begin{document}\nこんにちは 世界\n\\end{document}\n\ncompiles with \"xelatex text\" to a PDF with this text in Sazanami Gothic font.\n"
] |
[
3
] |
[] |
[] |
[
"miktex",
"pdflatex",
"python",
"python_sphinx",
"windows"
] |
stackoverflow_0000758693_miktex_pdflatex_python_python_sphinx_windows.txt
|
Q:
python and sys.argv
if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type python programname something then it will exit.
The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.
A:
BTW you can pass the error message directly to sys.exit:
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
A:
In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:
sys.stderr.write("Usage: " + sys.argv[0])
or
sys.stderr.write("Usage: %s" % sys.argv[0])
Also, you may want to consider using the following syntax of print (for Python earlier than 3.x):
print >>sys.stderr, "Usage:", sys.argv[0]
Using print arguably makes the code easier to read. Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example.
In Python 3.x, you would use the print function:
print("Usage:", sys.argv[0], file=sys.stderr)
Finally, in Python 2.6 and later you can use .format:
print >>sys.stderr, "Usage: {0}".format(sys.argv[0])
A:
I would do it this way:
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <database>" % (argv[0],))
return 1
if not os.path.exists(argv[1]):
sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.
|
python and sys.argv
|
if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type python programname something then it will exit.
The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.
|
[
"BTW you can pass the error message directly to sys.exit:\nif len(sys.argv) < 2:\n sys.exit('Usage: %s database-name' % sys.argv[0])\n\nif not os.path.exists(sys.argv[1]):\n sys.exit('ERROR: Database %s was not found!' % sys.argv[1])\n\n",
"In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:\nsys.stderr.write(\"Usage: \" + sys.argv[0])\n\nor\nsys.stderr.write(\"Usage: %s\" % sys.argv[0])\n\nAlso, you may want to consider using the following syntax of print (for Python earlier than 3.x):\nprint >>sys.stderr, \"Usage:\", sys.argv[0]\n\nUsing print arguably makes the code easier to read. Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example.\nIn Python 3.x, you would use the print function:\nprint(\"Usage:\", sys.argv[0], file=sys.stderr)\n\nFinally, in Python 2.6 and later you can use .format:\nprint >>sys.stderr, \"Usage: {0}\".format(sys.argv[0])\n\n",
"I would do it this way:\nimport sys\n\ndef main(argv):\n if len(argv) < 2:\n sys.stderr.write(\"Usage: %s <database>\" % (argv[0],))\n return 1\n\n if not os.path.exists(argv[1]):\n sys.stderr.write(\"ERROR: Database %r was not found!\" % (argv[1],))\n return 1\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n\nThis allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.\n"
] |
[
99,
34,
32
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000983201_python.txt
|
Q:
How to do a non-blocking URL fetch in Python
I am writing a GUI app in Pyglet that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using urllib.urlretrieve to grab them, but this blocks each time until they are finished, and only grabs one at a time.
I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?
I don't know much about threads, but it looks like the threading module might help? Or perhaps there is some easy way I've overlooked.
A:
You'll probably benefit from threading or multiprocessing modules. You don't actually need to create all those Thread-based classes by yourself, there is a simpler method using Pool.map:
from multiprocessing import Pool
def fetch_url(url):
# Fetch the URL contents and save it anywhere you need and
# return something meaningful (like filename or error code),
# if you wish.
...
pool = Pool(processes=4)
result = pool.map(f, image_url_list)
A:
As you suspected, this is a perfect situation for threading. Here is a short guide I found immensely helpful when doing my own first bit of threading in python.
A:
As you rightly indicated, you could create a number of threads, each of which is responsible for performing urlretrieve operations. This allows the main thread to continue uninterrupted.
Here is a tutorial on threading in python:
http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf
A:
Here's an example of how to use threading.Thread. Just replace the class name with your own and the run function with your own. Note that threading is great for IO restricted applications like your's and can really speed it up. Using pythong threading strictly for computation in standard python doesn't help because only one thread can compute at a time.
import threading, time
class Ping(threading.Thread):
def __init__(self, multiple):
threading.Thread.__init__(self)
self.multiple = multiple
def run(self):
#sleeps 3 seconds then prints 'pong' x times
time.sleep(3)
printString = 'pong' * self.multiple
pingInstance = Ping(3)
pingInstance.start() #your run function will be called with the start function
print "pingInstance is alive? : %d" % pingInstance.isAlive() #will return True, or 1
print "Number of threads alive: %d" % threading.activeCount()
#main thread + class instance
time.sleep(3.5)
print "Number of threads alive: %d" % threading.activeCount()
print "pingInstance is alive?: %d" % pingInstance.isAlive()
#isAlive returns false when your thread reaches the end of it's run function.
#only main thread now
A:
You have these choices:
Threads: easiest but doesn't scale well
Twisted: medium difficulty, scales well but shares CPU due to GIL and being single threaded.
Multiprocessing: hardest. Scales well if you know how to write your own event loop.
I recommend just using threads unless you need an industrial scale fetcher.
A:
You either need to use threads, or an asynchronous networking library such as Twisted. I suspect that using threads might be simpler in your particular use case.
|
How to do a non-blocking URL fetch in Python
|
I am writing a GUI app in Pyglet that has to display tens to hundreds of thumbnails from the Internet. Right now, I am using urllib.urlretrieve to grab them, but this blocks each time until they are finished, and only grabs one at a time.
I would prefer to download them in parallel and have each one display as soon as it's finished, without blocking the GUI at any point. What is the best way to do this?
I don't know much about threads, but it looks like the threading module might help? Or perhaps there is some easy way I've overlooked.
|
[
"You'll probably benefit from threading or multiprocessing modules. You don't actually need to create all those Thread-based classes by yourself, there is a simpler method using Pool.map:\nfrom multiprocessing import Pool\n\ndef fetch_url(url):\n # Fetch the URL contents and save it anywhere you need and\n # return something meaningful (like filename or error code),\n # if you wish.\n ...\n\npool = Pool(processes=4)\nresult = pool.map(f, image_url_list)\n\n",
"As you suspected, this is a perfect situation for threading. Here is a short guide I found immensely helpful when doing my own first bit of threading in python.\n",
"As you rightly indicated, you could create a number of threads, each of which is responsible for performing urlretrieve operations. This allows the main thread to continue uninterrupted. \nHere is a tutorial on threading in python:\nhttp://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf\n",
"Here's an example of how to use threading.Thread. Just replace the class name with your own and the run function with your own. Note that threading is great for IO restricted applications like your's and can really speed it up. Using pythong threading strictly for computation in standard python doesn't help because only one thread can compute at a time.\nimport threading, time\nclass Ping(threading.Thread):\n def __init__(self, multiple):\n threading.Thread.__init__(self)\n self.multiple = multiple\n def run(self):\n #sleeps 3 seconds then prints 'pong' x times\n time.sleep(3)\n printString = 'pong' * self.multiple\n\npingInstance = Ping(3)\npingInstance.start() #your run function will be called with the start function\nprint \"pingInstance is alive? : %d\" % pingInstance.isAlive() #will return True, or 1\nprint \"Number of threads alive: %d\" % threading.activeCount()\n#main thread + class instance\ntime.sleep(3.5)\nprint \"Number of threads alive: %d\" % threading.activeCount()\nprint \"pingInstance is alive?: %d\" % pingInstance.isAlive()\n#isAlive returns false when your thread reaches the end of it's run function.\n#only main thread now\n\n",
"You have these choices:\n\nThreads: easiest but doesn't scale well\nTwisted: medium difficulty, scales well but shares CPU due to GIL and being single threaded.\nMultiprocessing: hardest. Scales well if you know how to write your own event loop.\n\nI recommend just using threads unless you need an industrial scale fetcher.\n",
"You either need to use threads, or an asynchronous networking library such as Twisted. I suspect that using threads might be simpler in your particular use case.\n"
] |
[
3,
2,
2,
2,
1,
0
] |
[] |
[] |
[
"blocking",
"multithreading",
"pyglet",
"python"
] |
stackoverflow_0000983144_blocking_multithreading_pyglet_python.txt
|
Q:
Python JSON encoding
I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.
I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.
Currently I am declaring a list, looping through and another list, and appending one list within another:
import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
So I either:
I don't understand JSON Syntax
I don't understand the Pythons JSON module(s)
I'm using an inappropriate data type.
A:
Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict:
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
A:
I think you are simply exchanging dumps and loads.
>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
The first returns as a (JSON encoded) string its data argument:
>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:
>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True
A:
In simplejson (or the library json in Python 2.6 and later), loads takes a JSON string and returns a Python data structure, dumps takes a Python data structure and returns a JSON string. JSON string can encode Javascript arrays, not just objects, and a Python list corresponds to a JSON string encoding an array. To get a JSON string such as
{"apple":"cat", "banana":"dog"}
the Python object you pass to json.dumps could be:
dict(apple="cat", banana="dog")
though the JSON string is also valid Python syntax for the same dict. I believe the specific string you say you expect is simply invalid JSON syntax, however.
A:
The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.
From www.json.org:
JSON is built on two structures:
A collection of name/value pairs. In
various languages, this is realized as
an object, record, struct, dictionary,
hash table, keyed list, or associative
array. An ordered list of values. In
most languages, this is realized as an
array, vector, list, or sequence.
An object is an unordered set of
name/value pairs. An object begins
with { (left brace) and ends with }
(right brace). Each name is followed
by : (colon) and the name/value pairs
are separated by , (comma).
An array is an ordered collection of
values. An array begins with [ (left
bracket) and ends with ] (right
bracket). Values are separated by ,
(comma).
A:
JSON uses square brackets for lists ( [ "one", "two", "three" ] ) and curly brackets for key/value dictionaries (also called objects in JavaScript, {"one":1, "two":"b"}).
The dump is quite correct, you get a list of three elements, each one is a list of two strings.
if you wanted a dictionary, maybe something like this:
x = simplejson.dumps(dict(data))
>>> {"pear": "fish", "apple": "cat", "banana": "dog"}
your expected string ('{{"apple":{"cat"},{"banana":"dog"}}') isn't valid JSON. A
A:
So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.
simplejson.dumps(data) comes back with
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'
Which is a json array, which is what you want, since you gave this a python array.
If you want to get an "object" type syntax you would instead do
>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
which is javascript will come out as an object.
A:
Try:
import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"
simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon
NB: Based on Paolo's answer.
|
Python JSON encoding
|
I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.
I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.
Currently I am declaring a list, looping through and another list, and appending one list within another:
import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
So I either:
I don't understand JSON Syntax
I don't understand the Pythons JSON module(s)
I'm using an inappropriate data type.
|
[
"Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict:\n>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})\n'{\"pear\": \"fish\", \"apple\": \"cat\", \"banana\": \"dog\"}'\n\n",
"I think you are simply exchanging dumps and loads. \n>>> import json\n>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]\n\nThe first returns as a (JSON encoded) string its data argument:\n>>> encoded_str = json.dumps( data )\n>>> encoded_str\n'[[\"apple\", \"cat\"], [\"banana\", \"dog\"], [\"pear\", \"fish\"]]'\n\nThe second does the opposite, returning the data corresponding to its (JSON encoded) string argument:\n>>> decoded_data = json.loads( encoded_str )\n>>> decoded_data\n[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]\n>>> decoded_data == data\nTrue\n\n",
"In simplejson (or the library json in Python 2.6 and later), loads takes a JSON string and returns a Python data structure, dumps takes a Python data structure and returns a JSON string. JSON string can encode Javascript arrays, not just objects, and a Python list corresponds to a JSON string encoding an array. To get a JSON string such as\n{\"apple\":\"cat\", \"banana\":\"dog\"}\n\nthe Python object you pass to json.dumps could be:\ndict(apple=\"cat\", banana=\"dog\")\n\nthough the JSON string is also valid Python syntax for the same dict. I believe the specific string you say you expect is simply invalid JSON syntax, however.\n",
"The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.\nFrom www.json.org:\n\nJSON is built on two structures:\nA collection of name/value pairs. In\n various languages, this is realized as\n an object, record, struct, dictionary,\n hash table, keyed list, or associative\n array. An ordered list of values. In\n most languages, this is realized as an\n array, vector, list, or sequence. \nAn object is an unordered set of\n name/value pairs. An object begins\n with { (left brace) and ends with }\n (right brace). Each name is followed\n by : (colon) and the name/value pairs\n are separated by , (comma).\nAn array is an ordered collection of\n values. An array begins with [ (left\n bracket) and ends with ] (right\n bracket). Values are separated by ,\n (comma).\n\n",
"JSON uses square brackets for lists ( [ \"one\", \"two\", \"three\" ] ) and curly brackets for key/value dictionaries (also called objects in JavaScript, {\"one\":1, \"two\":\"b\"}).\nThe dump is quite correct, you get a list of three elements, each one is a list of two strings.\nif you wanted a dictionary, maybe something like this:\nx = simplejson.dumps(dict(data))\n>>> {\"pear\": \"fish\", \"apple\": \"cat\", \"banana\": \"dog\"}\n\nyour expected string ('{{\"apple\":{\"cat\"},{\"banana\":\"dog\"}}') isn't valid JSON. A\n",
"So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.\nsimplejson.dumps(data) comes back with \n'[[\"apple\", \"cat\"], [\"banana\", \"dog\"], [\"pear\", \"fish\"]]'\n\nWhich is a json array, which is what you want, since you gave this a python array.\nIf you want to get an \"object\" type syntax you would instead do\n>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}\n>>> simplejson.dumps(data2)\n'{\"pear\": \"fish\", \"apple\": \"cat\", \"banana\": \"dog\"}'\n\nwhich is javascript will come out as an object.\n",
"Try:\nimport simplejson\ndata = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}\ndata_json = \"{'apple': 'cat', 'banana':'dog', 'pear':'fish'}\"\n\nsimplejson.loads(data_json) # outputs data\nsimplejson.dumps(data) # outputs data_joon\n\nNB: Based on Paolo's answer.\n"
] |
[
78,
27,
18,
4,
3,
3,
3
] |
[] |
[] |
[
"encoding",
"json",
"python",
"simplejson",
"types"
] |
stackoverflow_0000983855_encoding_json_python_simplejson_types.txt
|
Q:
Call flatpage from with a view
Can I call a Flatpage from with a view. Say I have some code like:
def myview(request):
if request.subdomain != "www":
return HttpResponseRedirect("http://"+request.subdomain+".mydomain/login/")
else:
call the flatpage here...
A:
You sure can. Just make sure you have the flatpage function included in your view code:
from django.contrib.flatpages.views import flatpage
And stick the following in your else:
return flatpage(request, '/path/to/your/flatpage/')
Or if you'd like to configure the flatpage to use the same URL being called, you can always do it like this:
return flatpage(request, request.path)
I just tested this and it worked just fine. Let me know if it doesn't for you.
|
Call flatpage from with a view
|
Can I call a Flatpage from with a view. Say I have some code like:
def myview(request):
if request.subdomain != "www":
return HttpResponseRedirect("http://"+request.subdomain+".mydomain/login/")
else:
call the flatpage here...
|
[
"You sure can. Just make sure you have the flatpage function included in your view code:\nfrom django.contrib.flatpages.views import flatpage\n\nAnd stick the following in your else:\nreturn flatpage(request, '/path/to/your/flatpage/')\n\nOr if you'd like to configure the flatpage to use the same URL being called, you can always do it like this:\nreturn flatpage(request, request.path)\n\nI just tested this and it worked just fine. Let me know if it doesn't for you.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0000983722_django_python.txt
|
Q:
How to recreate this PHP code in Python?
I've found a PHP script that lets me do what I asked in this SO question. I can use this just fine, but out of curiosity I'd like to recreate the following code in Python.
I can of course use urllib2 to get the page, but I'm at a loss on how to handle the cookies since mechanize (tested with Python 2.5 and 2.6 on Windows and Python 2.5 on Ubuntu...all with latest mechanize version) seems to break on the page. How do I do this in python?
require_once "HTTP/Request.php";
$req = &new HTTP_Request('https://steamcommunity.com');
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("action", "doLogin");
$req->addPostData("goto", "");
$req->addPostData("steamAccountName", ACC_NAME);
$req->addPostData("steamPassword", ACC_PASS);
echo "Login: ";
$res = $req->sendRequest();
if (PEAR::isError($res))
die($res->getMessage());
$cookies = $req->getResponseCookies();
if ( !$cookies )
die("fail\n");
echo "pass\n";
foreach($cookies as $cookie)
$req->addCookie($cookie['name'],$cookie['value']);
A:
Similar to monkut's answer, but a little more concise.
import urllib, urllib2
def steam_login(username,password):
data = urllib.urlencode({
'action': 'doLogin',
'goto': '',
'steamAccountName': username,
'steamPassword': password,
})
request = urllib2.Request('https://steamcommunity.com/',data)
cookie_handler = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookie_handler)
response = opener.open(request)
if not 200 <= response.code < 300:
raise Exception("HTTP error: %d %s" % (response.code,response.msg))
else:
return cookie_handler.cookiejar
It returns the cookie jar, which you can use in other requests. Just pass it to the HTTPCookieProcessor constructor.
monkut's answer installs a global HTTPCookieProcessor, which stores the cookies between requests. My solution does not modify the global state.
A:
I'm not familiar with PHP, but this may get you started.
I'm installing the opener here which will apply it to the urlopen method. If you don't want to 'install' the opener(s) you can use the opener object directly. (opener.open(url, data)).
Refer to:
http://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.install_opener
import urlib2
import urllib
# 1 create handlers
cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling
redirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection
# 2 apply the handler to an opener
opener = urllib2.build_opener(cookieHandler, redirectionHandler)
# 3. Install the openers
urllib2.install_opener(opener)
# prep post data
datalist_tuples = [ ('action', 'doLogin'),
('goto', ''),
('steamAccountName', ACC_NAME),
('steamPassword', ACC_PASS)
]
url = 'https://steamcommunity.com'
post_data = urllib.urlencode(datalist_tuples)
resp_f = urllib2.urlopen(url, post_data)
|
How to recreate this PHP code in Python?
|
I've found a PHP script that lets me do what I asked in this SO question. I can use this just fine, but out of curiosity I'd like to recreate the following code in Python.
I can of course use urllib2 to get the page, but I'm at a loss on how to handle the cookies since mechanize (tested with Python 2.5 and 2.6 on Windows and Python 2.5 on Ubuntu...all with latest mechanize version) seems to break on the page. How do I do this in python?
require_once "HTTP/Request.php";
$req = &new HTTP_Request('https://steamcommunity.com');
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("action", "doLogin");
$req->addPostData("goto", "");
$req->addPostData("steamAccountName", ACC_NAME);
$req->addPostData("steamPassword", ACC_PASS);
echo "Login: ";
$res = $req->sendRequest();
if (PEAR::isError($res))
die($res->getMessage());
$cookies = $req->getResponseCookies();
if ( !$cookies )
die("fail\n");
echo "pass\n";
foreach($cookies as $cookie)
$req->addCookie($cookie['name'],$cookie['value']);
|
[
"Similar to monkut's answer, but a little more concise.\nimport urllib, urllib2\n\ndef steam_login(username,password):\n data = urllib.urlencode({\n 'action': 'doLogin',\n 'goto': '',\n 'steamAccountName': username,\n 'steamPassword': password,\n })\n request = urllib2.Request('https://steamcommunity.com/',data)\n cookie_handler = urllib2.HTTPCookieProcessor()\n opener = urllib2.build_opener(cookie_handler)\n response = opener.open(request)\n if not 200 <= response.code < 300:\n raise Exception(\"HTTP error: %d %s\" % (response.code,response.msg))\n else:\n return cookie_handler.cookiejar\n\nIt returns the cookie jar, which you can use in other requests. Just pass it to the HTTPCookieProcessor constructor.\nmonkut's answer installs a global HTTPCookieProcessor, which stores the cookies between requests. My solution does not modify the global state.\n",
"I'm not familiar with PHP, but this may get you started.\nI'm installing the opener here which will apply it to the urlopen method. If you don't want to 'install' the opener(s) you can use the opener object directly. (opener.open(url, data)).\nRefer to:\nhttp://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.install_opener\nimport urlib2\nimport urllib\n\n# 1 create handlers\ncookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling\nredirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection\n\n# 2 apply the handler to an opener \nopener = urllib2.build_opener(cookieHandler, redirectionHandler)\n\n# 3. Install the openers\nurllib2.install_opener(opener)\n\n# prep post data\ndatalist_tuples = [ ('action', 'doLogin'),\n ('goto', ''),\n ('steamAccountName', ACC_NAME),\n ('steamPassword', ACC_PASS)\n\n ]\nurl = 'https://steamcommunity.com'\npost_data = urllib.urlencode(datalist_tuples)\nresp_f = urllib2.urlopen(url, post_data)\n\n"
] |
[
6,
5
] |
[] |
[] |
[
"automation",
"forms",
"http",
"php",
"python"
] |
stackoverflow_0000984244_automation_forms_http_php_python.txt
|
Q:
Formatting date times provided as strings in Django
In my Django application I get times from a webservice, provided as a string, that I use in my templates:
{{date.string}}
This provides me with a date such as:
2009-06-11 17:02:09+0000
These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:
{{ value|date:"D d M Y" }}
However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?
A:
You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.
Something like:
from datetime import datetime
from django.shortcuts import render_to_response
def my_view(request):
ws_date_as_string = ... get the webservice date
the_date = datetime.strptime(ws_date, "%Y-%m-%d %H:%M:%S+0000")
return render_to_response('my_template.html', {'date':the_date})
As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.
A:
This doesn't deal with the Django tag, but the strptime code is:
d = strptime("2009-06-11 17:02:09+0000", "%Y-%m-%d %H:%M:%S+0000")
Note that you're dropping the time zone info.
|
Formatting date times provided as strings in Django
|
In my Django application I get times from a webservice, provided as a string, that I use in my templates:
{{date.string}}
This provides me with a date such as:
2009-06-11 17:02:09+0000
These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:
{{ value|date:"D d M Y" }}
However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?
|
[
"You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.\nSomething like:\nfrom datetime import datetime\nfrom django.shortcuts import render_to_response\n\ndef my_view(request):\n ws_date_as_string = ... get the webservice date\n the_date = datetime.strptime(ws_date, \"%Y-%m-%d %H:%M:%S+0000\")\n return render_to_response('my_template.html', {'date':the_date})\n\nAs Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.\n",
"This doesn't deal with the Django tag, but the strptime code is:\nd = strptime(\"2009-06-11 17:02:09+0000\", \"%Y-%m-%d %H:%M:%S+0000\")\n\nNote that you're dropping the time zone info.\n"
] |
[
11,
0
] |
[] |
[] |
[
"date",
"django",
"python",
"strptime",
"time"
] |
stackoverflow_0000984412_date_django_python_strptime_time.txt
|
Q:
How would I go about parsing the following log?
I need to parse a log in the following format:
===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.
So i need to keep only the line with the item title and the result for that title and discard everything else.
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?
LE: The result I'm looking for is to discard everything else and get something like:
('This is the item title','Foo')
then
('This is this items title','Bar')
A:
1) Loop through every line in the log
a)If line matches appropriate Regex:
Display/Store Next Line as the item title.
Look for the next line containing "Result
XXXX." and parse out that result for
including in the result set.
EDIT: added a bit more now that I see the result you're looking for.
A:
I know you didn't ask for real code but this is too great an opportunity for a generator-based text muncher to pass up:
# data is a multiline string containing your log, but this
# function could be easily rewritten to accept a file handle.
def get_stats(data):
title = ""
grab_title = False
for line in data.split('\n'):
if line.startswith("====="):
grab_title = True
elif grab_title:
grab_title = False
title = line
elif line.startswith("Test finished."):
start = line.index("Result") + 7
end = line.index("Time") - 2
yield (title, line[start:end])
for d in get_stats(data):
print d
# Returns:
# ('This is the item title', 'Foo')
# ('This is this items title', 'Bar')
# ('This is the title of this item', 'FooBar')
Hopefully this is straightforward enough. Do ask if you have questions on how exactly the above works.
A:
Maybe something like (log.log is your file):
def doOutput(s): # process or store data
print s
s=''
for line in open('log.log').readlines():
if line.startswith('====='):
if len(s):
doOutput(s)
s=''
else:
s+=line
if len(s):
doOutput(s)
A:
I would recommend starting a loop that looks for the "===" in the line. Let that key you off to the Title which is the next line. Set a flag that looks for the results, and if you don't find the results before you hit the next "===", say no results. Else, log the results with the title. Reset your flag and repeat. You could store the results with the Title in a dictionary as well, just store "No Results" when you don't find the results between the Title and the next "===" line.
This looks pretty simple to do based on the output.
A:
Regular expression with group matching seems to do the job in python:
import re
data = """===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8"""
p = re.compile("^=====[^=]*=====\n(.*)$\nInfo: .*\n.*Result ([^\.]*)\.",
re.MULTILINE)
for m in re.finditer(p, data):
print "title:", m.group(1), "result:", m.group(2)er code here
If You need more info about regular expressions check: python docs.
A:
This is sort of a continuation of maciejka's solution (see the comments there). If the data is in the file daniels.log, then we could go through it item by item with itertools.groupby, and apply a multi-line regexp to each item. This should scale fine.
import itertools, re
p = re.compile("Result ([^.]*)\.", re.MULTILINE)
for sep, item in itertools.groupby(file('daniels.log'),
lambda x: x.startswith('===== Item ')):
if not sep:
title = item.next().strip()
m = p.search(''.join(item))
if m:
print (title, m.group(1))
A:
Parsing is not done using regex. If you have a reasonably well structured text (which it looks as you do), you can use faster testing (e.g. line.startswith() or such).
A list of dictionaries seems to be a suitable data type for such key-value pairs. Not sure what else to tell you. This seems pretty trivial.
OK, so the regexp way proved to be more suitable in this case:
import re
re.findall("=\n(.*)\n", s)
is faster than list comprehensions
[item.split('\n', 1)[0] for item in s.split('=\n')]
Here's what I got:
>>> len(s)
337000000
>>> test(get1, s) #list comprehensions
0:00:04.923529
>>> test(get2, s) #re.findall()
0:00:02.737103
Lesson learned.
A:
You could try something like this (in c-like pseudocode, since i don't know python):
string line=getline();
regex boundary="^==== [^=]+ ====$";
regex info="^Info: (.*)$";
regex test_data="Test ([^.]*)\. Result ([^.]*)\. Time ([^.]*)\.$";
regex stats="Stats: (.*)$";
while(!eof())
{
// sanity check
test line against boundary, if they don't match, throw excetion
string title=getline();
while(1)
{
// end the loop if we finished the data
if(eof()) break;
line=getline();
test line against boundary, if they match, break
test line against info, if they match, load the first matched group into "info"
test line against test_data, if they match, load the first matched group into "test_result", load the 2nd matched group into "result", load the 3rd matched group into "time"
test line against stats, if they match, load the first matched group into "statistics"
}
// at this point you can use the variables set above to do whatever with a line
// for example, you want to use title and, if set, test_result/result/time.
}
|
How would I go about parsing the following log?
|
I need to parse a log in the following format:
===== Item 5483/14800 =====
This is the item title
Info: some note
===== Item 5483/14800 (Update 1/3) =====
This is the item title
Info: some other note
===== Item 5483/14800 (Update 2/3) =====
This is the item title
Info: some more notes
===== Item 5483/14800 (Update 3/3) =====
This is the item title
Info: some other note
Test finished. Result Foo. Time 12 secunds.
Stats: CPU 0.5 MEM 5.3
===== Item 5484/14800 =====
This is this items title
Info: some note
Test finished. Result Bar. Time 4 secunds.
Stats: CPU 0.9 MEM 4.7
===== Item 5485/14800 =====
This is the title of this item
Info: some note
Test finished. Result FooBar. Time 7 secunds.
Stats: CPU 2.5 MEM 2.8
I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result.
So i need to keep only the line with the item title and the result for that title and discard everything else.
The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky.
Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this?
LE: The result I'm looking for is to discard everything else and get something like:
('This is the item title','Foo')
then
('This is this items title','Bar')
|
[
"1) Loop through every line in the log\n\n a)If line matches appropriate Regex:\n\n Display/Store Next Line as the item title.\n Look for the next line containing \"Result \n XXXX.\" and parse out that result for \n including in the result set.\n\nEDIT: added a bit more now that I see the result you're looking for.\n",
"I know you didn't ask for real code but this is too great an opportunity for a generator-based text muncher to pass up:\n# data is a multiline string containing your log, but this\n# function could be easily rewritten to accept a file handle.\ndef get_stats(data):\n\n title = \"\"\n grab_title = False\n\n for line in data.split('\\n'):\n if line.startswith(\"=====\"):\n grab_title = True\n elif grab_title:\n grab_title = False\n title = line\n elif line.startswith(\"Test finished.\"):\n start = line.index(\"Result\") + 7\n end = line.index(\"Time\") - 2\n yield (title, line[start:end])\n\n\nfor d in get_stats(data):\n print d\n\n\n# Returns:\n# ('This is the item title', 'Foo')\n# ('This is this items title', 'Bar')\n# ('This is the title of this item', 'FooBar')\n\nHopefully this is straightforward enough. Do ask if you have questions on how exactly the above works.\n",
"Maybe something like (log.log is your file):\ndef doOutput(s): # process or store data\n print s\n\ns=''\nfor line in open('log.log').readlines():\n if line.startswith('====='):\n if len(s):\n doOutput(s)\n s=''\n else:\n s+=line\nif len(s):\n doOutput(s)\n\n",
"I would recommend starting a loop that looks for the \"===\" in the line. Let that key you off to the Title which is the next line. Set a flag that looks for the results, and if you don't find the results before you hit the next \"===\", say no results. Else, log the results with the title. Reset your flag and repeat. You could store the results with the Title in a dictionary as well, just store \"No Results\" when you don't find the results between the Title and the next \"===\" line.\nThis looks pretty simple to do based on the output.\n",
"Regular expression with group matching seems to do the job in python:\nimport re\n\ndata = \"\"\"===== Item 5483/14800 =====\nThis is the item title\nInfo: some note\n===== Item 5483/14800 (Update 1/3) =====\nThis is the item title\nInfo: some other note\n===== Item 5483/14800 (Update 2/3) =====\nThis is the item title\nInfo: some more notes\n===== Item 5483/14800 (Update 3/3) =====\nThis is the item title\nInfo: some other note\nTest finished. Result Foo. Time 12 secunds.\nStats: CPU 0.5 MEM 5.3\n===== Item 5484/14800 =====\nThis is this items title\nInfo: some note\nTest finished. Result Bar. Time 4 secunds.\nStats: CPU 0.9 MEM 4.7\n===== Item 5485/14800 =====\nThis is the title of this item\nInfo: some note\nTest finished. Result FooBar. Time 7 secunds.\nStats: CPU 2.5 MEM 2.8\"\"\"\n\n\np = re.compile(\"^=====[^=]*=====\\n(.*)$\\nInfo: .*\\n.*Result ([^\\.]*)\\.\",\n re.MULTILINE)\nfor m in re.finditer(p, data):\n print \"title:\", m.group(1), \"result:\", m.group(2)er code here\n\nIf You need more info about regular expressions check: python docs.\n",
"This is sort of a continuation of maciejka's solution (see the comments there). If the data is in the file daniels.log, then we could go through it item by item with itertools.groupby, and apply a multi-line regexp to each item. This should scale fine.\nimport itertools, re\n\np = re.compile(\"Result ([^.]*)\\.\", re.MULTILINE)\nfor sep, item in itertools.groupby(file('daniels.log'),\n lambda x: x.startswith('===== Item ')):\n if not sep:\n title = item.next().strip()\n m = p.search(''.join(item))\n if m:\n print (title, m.group(1))\n\n",
"Parsing is not done using regex. If you have a reasonably well structured text (which it looks as you do), you can use faster testing (e.g. line.startswith() or such).\nA list of dictionaries seems to be a suitable data type for such key-value pairs. Not sure what else to tell you. This seems pretty trivial.\n\nOK, so the regexp way proved to be more suitable in this case:\nimport re\nre.findall(\"=\\n(.*)\\n\", s)\n\nis faster than list comprehensions\n[item.split('\\n', 1)[0] for item in s.split('=\\n')]\n\nHere's what I got:\n>>> len(s)\n337000000\n>>> test(get1, s) #list comprehensions\n0:00:04.923529\n>>> test(get2, s) #re.findall()\n0:00:02.737103\n\nLesson learned.\n",
"You could try something like this (in c-like pseudocode, since i don't know python):\nstring line=getline();\nregex boundary=\"^==== [^=]+ ====$\";\nregex info=\"^Info: (.*)$\";\nregex test_data=\"Test ([^.]*)\\. Result ([^.]*)\\. Time ([^.]*)\\.$\";\nregex stats=\"Stats: (.*)$\";\nwhile(!eof())\n{\n // sanity check\n test line against boundary, if they don't match, throw excetion\n\n string title=getline();\n\n while(1)\n { \n // end the loop if we finished the data\n if(eof()) break;\n\n line=getline();\n test line against boundary, if they match, break\n test line against info, if they match, load the first matched group into \"info\"\n test line against test_data, if they match, load the first matched group into \"test_result\", load the 2nd matched group into \"result\", load the 3rd matched group into \"time\"\n test line against stats, if they match, load the first matched group into \"statistics\"\n }\n\n // at this point you can use the variables set above to do whatever with a line\n // for example, you want to use title and, if set, test_result/result/time.\n\n}\n\n"
] |
[
5,
5,
1,
1,
1,
1,
0,
0
] |
[
"Here's some not so good looking perl code that does the job. Perhaps you can find it useful in some way. Quick hack, there are other ways of doing it (I feel that this code needs defending).\n#!/usr/bin/perl -w\n#\n# $Id$\n#\n\nuse strict;\nuse warnings;\n\nmy @ITEMS;\nmy $item;\nmy $state = 0;\n\nopen(FD, \"< data.txt\") or die \"Failed to open file.\";\nwhile (my $line = <FD>) {\n $line =~ s/(\\r|\\n)//g;\n if ($line =~ /^===== Item (\\d+)\\/\\d+/) {\n my $item_number = $1;\n if ($item) {\n # Just to make sure we don't have two lines that seems to be a headline in a row.\n # If we have an item but haven't set the title it means that there are two in a row that matches.\n die \"Something seems to be wrong, better safe than sorry. Line $. : $line\\n\" if (not $item->{title});\n # If we have a new item number add previuos item and create a new.\n if ($item_number != $item->{item_number}) {\n push(@ITEMS, $item);\n $item = {};\n $item->{item_number} = $item_number;\n }\n } else {\n # First entry, don't have an item.\n $item = {}; # Create new item.\n $item->{item_number} = $item_number;\n }\n $state = 1;\n } elsif ($state == 1) {\n die \"Data must start with a headline.\" if (not $item);\n # If we already have a title make sure it matches.\n if ($item->{title}) {\n if ($item->{title} ne $line) {\n die \"Title doesn't match for item \" . $item->{item_number} . \", line $. : $line\\n\";\n }\n } else {\n $item->{title} = $line;\n }\n $state++;\n } elsif (($state == 2) && ($line =~ /^Info:/)) {\n # Just make sure that for state 2 we have a line that match Info.\n $state++;\n } elsif (($state == 3) && ($line =~ /^Test finished\\. Result ([^.]+)\\. Time \\d+ secunds{0,1}\\.$/)) {\n $item->{status} = $1;\n $state++;\n } elsif (($state == 4) && ($line =~ /^Stats:/)) {\n $state++; # After Stats we must have a new item or we should fail.\n } else {\n die \"Invalid data, line $.: $line\\n\";\n }\n}\n# Need to take care of the last item too.\npush(@ITEMS, $item) if ($item);\nclose FD;\n\n# Loop our items and print the info we stored.\nfor $item (@ITEMS) {\n print $item->{item_number} . \" (\" . $item->{status} . \") \" . $item->{title} . \"\\n\";\n}\n\n"
] |
[
-1
] |
[
"parsing",
"python"
] |
stackoverflow_0000977458_parsing_python.txt
|
Q:
PythonCard - Can I launch a CustomDialog Stand Alone?
I have a CustomDialog I made to let the user configure settings. Normally I want this to be launched from a menu item within the main application which works fine.
But during the install, I want to launch just the dialog to let the user configure the settings. Is there a way I can have both?
A:
With a little supporting code you can -- see e.g. wizard.py which launches an almost-stand-alone custom dialog subclass "wizard".
|
PythonCard - Can I launch a CustomDialog Stand Alone?
|
I have a CustomDialog I made to let the user configure settings. Normally I want this to be launched from a menu item within the main application which works fine.
But during the install, I want to launch just the dialog to let the user configure the settings. Is there a way I can have both?
|
[
"With a little supporting code you can -- see e.g. wizard.py which launches an almost-stand-alone custom dialog subclass \"wizard\".\n"
] |
[
1
] |
[] |
[] |
[
"pycard",
"python",
"pythoncard",
"user_interface",
"wxpython"
] |
stackoverflow_0000984506_pycard_python_pythoncard_user_interface_wxpython.txt
|
Q:
How to use standard toolbar icons with WxPython?
I'm designing a simple text editor using WxPython, and I want to put the platform's native icons in the toolbar. It seems that the only way to make toolbars is with custom images, which are not good for portability. Is there some kind of (e.g.) GetSaveIcon()?
A:
I don't think wxPython provides native images on each platform
but just for consistency sake you can use wx.ArtProvider
e.g.
wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN)
|
How to use standard toolbar icons with WxPython?
|
I'm designing a simple text editor using WxPython, and I want to put the platform's native icons in the toolbar. It seems that the only way to make toolbars is with custom images, which are not good for portability. Is there some kind of (e.g.) GetSaveIcon()?
|
[
"I don't think wxPython provides native images on each platform\nbut just for consistency sake you can use wx.ArtProvider\ne.g.\nwx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN)\n"
] |
[
4
] |
[] |
[] |
[
"icons",
"python",
"wxpython"
] |
stackoverflow_0000984816_icons_python_wxpython.txt
|
Q:
Facebook, Django, and Google App Engine
I'm experimenting with app-engine-patch (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution?
A:
I run a system on for social networks and facebook on GAE with back-end in Python, front end in Javascript and Flash. I use mostly client side js libraries to pass data back to the server side datastore. This library for facebook to be exact: http://code.google.com/p/facebookjsapi/
There is a reason for this. Most of what we are doing will be running on its own site, in iframes in different social networks and in widgets etc. But for the most part this has worked very well. It is good because we can swap out our backend at any time or even run it on multiple platforms as it is also using a python rest GAE library but any backend would do with this setup.
A:
Adding the Facebook directory from the PyFacebook install directory to the app-engine-patch application allows you to add 'facebook.djangofb.FacebookMiddleware', to the MIDDLEWARE_CLASSES in settings.py. Then your view can use 'import facebook.djangofb as facebook' and '@facebook.require_login().'
I haven't gone end to end, but when I tried to display the view preceded by '@facebook.require_login()', I was redirected to the Facebook login.
A:
According to this post, you need a slightly modified PyFacebook that you can download from a URL given in said post (I haven't tried it myself, though).
Edit: that link is wrong -- better link and more discussion on this thread.
|
Facebook, Django, and Google App Engine
|
I'm experimenting with app-engine-patch (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution?
|
[
"I run a system on for social networks and facebook on GAE with back-end in Python, front end in Javascript and Flash. I use mostly client side js libraries to pass data back to the server side datastore. This library for facebook to be exact: http://code.google.com/p/facebookjsapi/ \nThere is a reason for this. Most of what we are doing will be running on its own site, in iframes in different social networks and in widgets etc. But for the most part this has worked very well. It is good because we can swap out our backend at any time or even run it on multiple platforms as it is also using a python rest GAE library but any backend would do with this setup.\n",
"Adding the Facebook directory from the PyFacebook install directory to the app-engine-patch application allows you to add 'facebook.djangofb.FacebookMiddleware', to the MIDDLEWARE_CLASSES in settings.py. Then your view can use 'import facebook.djangofb as facebook' and '@facebook.require_login().'\nI haven't gone end to end, but when I tried to display the view preceded by '@facebook.require_login()', I was redirected to the Facebook login.\n",
"According to this post, you need a slightly modified PyFacebook that you can download from a URL given in said post (I haven't tried it myself, though).\nEdit: that link is wrong -- better link and more discussion on this thread.\n"
] |
[
8,
6,
0
] |
[] |
[] |
[
"django",
"facebook",
"google_app_engine",
"python"
] |
stackoverflow_0000984071_django_facebook_google_app_engine_python.txt
|
Q:
During a subprocess call, catch critical windows errors in Python instead of letting the OS handle it by showing nasty error pop-ups
"The application failed to initialize properly ... Click on OK,to terminate the application." is the message from the error pop-up. What is the way to catch these errors in Python code?
A:
Sounds familiar? This will block your subprocess.Popen forever.. until you click the 'OK' button. Add the following code to your module initialization to workaround this issue:
import win32api, win32con
win32api.SetErrorMode(win32con.SEM_FAILCRITICALERRORS |
win32con.SEM_NOOPENFILEERRORBOX)
|
During a subprocess call, catch critical windows errors in Python instead of letting the OS handle it by showing nasty error pop-ups
|
"The application failed to initialize properly ... Click on OK,to terminate the application." is the message from the error pop-up. What is the way to catch these errors in Python code?
|
[
"Sounds familiar? This will block your subprocess.Popen forever.. until you click the 'OK' button. Add the following code to your module initialization to workaround this issue:\nimport win32api, win32con\nwin32api.SetErrorMode(win32con.SEM_FAILCRITICALERRORS |\n win32con.SEM_NOOPENFILEERRORBOX)\n\n"
] |
[
4
] |
[] |
[] |
[
"python",
"subprocess",
"windows"
] |
stackoverflow_0000977275_python_subprocess_windows.txt
|
Q:
How to specify native library search path for python
I have installed lxml which was built using a standalone version of libxml2. Reason for this was that the lxml needed a later version of libxml2 than what was currently installed.
When I use the lxml module how do I tell it (python) where to find the correct version of the libxml2 shared library?
A:
Assuming you're talking about a .so file, it's not up to Python to find it -- it's up to the operating system's dynamic library loaded. For Linux, for example, LD_LIBRARY_PATH is the environment variable you need to set.
|
How to specify native library search path for python
|
I have installed lxml which was built using a standalone version of libxml2. Reason for this was that the lxml needed a later version of libxml2 than what was currently installed.
When I use the lxml module how do I tell it (python) where to find the correct version of the libxml2 shared library?
|
[
"Assuming you're talking about a .so file, it's not up to Python to find it -- it's up to the operating system's dynamic library loaded. For Linux, for example, LD_LIBRARY_PATH is the environment variable you need to set.\n"
] |
[
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000985155_python.txt
|
Q:
disable a block in django
I want to disable a block in development and use it in deployment in google apps in python development. What changes do i need to make in template or main script?
A:
If you've got the middleware django.core.content_processors.debug then you can just do this in your template:
{% block mydebugonly %}
{% if debug %}
<p>Something that will only appear if the DEBUG setting is True.</p>
{% endif %}
{% endblock %}
|
disable a block in django
|
I want to disable a block in development and use it in deployment in google apps in python development. What changes do i need to make in template or main script?
|
[
"If you've got the middleware django.core.content_processors.debug then you can just do this in your template:\n{% block mydebugonly %}\n {% if debug %}\n <p>Something that will only appear if the DEBUG setting is True.</p>\n {% endif %}\n{% endblock %}\n\n"
] |
[
3
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0000985224_django_google_app_engine_python.txt
|
Q:
Format an array of tuples in a nice "table"
Say I have an array of tuples which look like that:
[('url#id1', 'url#predicate1', 'value1'),
('url#id1', 'url#predicate2', 'value2'),
('url#id1', 'url#predicate3', 'value3'),
('url#id2', 'url#predicate1', 'value4'),
('url#id2', 'url#predicate2', 'value5')]
I would like be able to return a nice 2D array to be able to display it "as it" in my page through django.
The table would look like that:
[['', 'predicate1', 'predicate2', 'predicate3'],
['id1', 'value1', 'value2', 'value3'],
['id2', 'value4', 'value5', '']]
You will notice that the 2nd item of each tuple became the table "column's title" and that we now have rows with ids and columns values.
How would you do that? Of course if you have a better idea than using the table example I gave I would be happy to have your thoughts :)
Right now I am generating a dict of dict and display that in django. But as my pairs of keys, values are not always in the same order in my dicts, then it cannot display correctly my data.
Thanks!
A:
Your dict of dict is probably on the right track. While you create that dict of dict, you could also maintain a list of ids and a list of predicates. That way, you can remember the ordering and build the table by looping through those lists.
using the zip function on your initial array wil give you three lists: the list of ids, the list of predicates and the list of values.
to get rid of duplicates, try the reduce function:
list_without_duplicates = reduce(
lambda l, x: (l[-1] != x and l.append(x)) or l, list_with_duplicates, [])
A:
Ok,
At last I came up with that code:
columns = dict()
columnsTitles = []
rows = dict()
colIdxCounter = 1 # Start with 1 because the first col are ids
rowIdxCounter = 1 # Start with 1 because the columns titles
for i in dataset:
if not rows.has_key(i[0]):
rows[i[0]] = rowIdxCounter
rowIdxCounter += 1
if not columns.has_key(i[1]):
columns[i[1]] = colIdxCounter
colIdxCounter += 1
columnsTitles.append(i[1])
toRet = [columnsTitles]
for i in range(len(rows)):
toAppend = []
for j in range(colIdxCounter):
toAppend.append("")
toRet.append(toAppend)
for i in dataset:
toRet[rows[i[0]]][columns[i[1]]] = i[2]
for i in toRet:
print i
Please don't hesitate to comment/improve it :)
|
Format an array of tuples in a nice "table"
|
Say I have an array of tuples which look like that:
[('url#id1', 'url#predicate1', 'value1'),
('url#id1', 'url#predicate2', 'value2'),
('url#id1', 'url#predicate3', 'value3'),
('url#id2', 'url#predicate1', 'value4'),
('url#id2', 'url#predicate2', 'value5')]
I would like be able to return a nice 2D array to be able to display it "as it" in my page through django.
The table would look like that:
[['', 'predicate1', 'predicate2', 'predicate3'],
['id1', 'value1', 'value2', 'value3'],
['id2', 'value4', 'value5', '']]
You will notice that the 2nd item of each tuple became the table "column's title" and that we now have rows with ids and columns values.
How would you do that? Of course if you have a better idea than using the table example I gave I would be happy to have your thoughts :)
Right now I am generating a dict of dict and display that in django. But as my pairs of keys, values are not always in the same order in my dicts, then it cannot display correctly my data.
Thanks!
|
[
"Your dict of dict is probably on the right track. While you create that dict of dict, you could also maintain a list of ids and a list of predicates. That way, you can remember the ordering and build the table by looping through those lists.\nusing the zip function on your initial array wil give you three lists: the list of ids, the list of predicates and the list of values.\nto get rid of duplicates, try the reduce function:\nlist_without_duplicates = reduce(\n lambda l, x: (l[-1] != x and l.append(x)) or l, list_with_duplicates, [])\n\n",
"Ok,\nAt last I came up with that code:\ncolumns = dict()\ncolumnsTitles = []\nrows = dict()\ncolIdxCounter = 1 # Start with 1 because the first col are ids \nrowIdxCounter = 1 # Start with 1 because the columns titles\n\nfor i in dataset:\n if not rows.has_key(i[0]):\n rows[i[0]] = rowIdxCounter\n rowIdxCounter += 1\n if not columns.has_key(i[1]):\n columns[i[1]] = colIdxCounter\n colIdxCounter += 1\n columnsTitles.append(i[1])\n\ntoRet = [columnsTitles]\nfor i in range(len(rows)):\n toAppend = []\n for j in range(colIdxCounter):\n toAppend.append(\"\")\n toRet.append(toAppend)\n\nfor i in dataset:\n toRet[rows[i[0]]][columns[i[1]]] = i[2]\n\nfor i in toRet:\n print i\n\nPlease don't hesitate to comment/improve it :)\n"
] |
[
0,
0
] |
[] |
[] |
[
"algorithm",
"django",
"python"
] |
stackoverflow_0000980000_algorithm_django_python.txt
|
Q:
Is the pickling process deterministic?
Does Pickle always produce the same output for a certain input value? I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories. My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.
A:
I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories.
Right:
>>> pickle.dumps({1: 0, 9: 0}) == pickle.dumps({9: 0, 1: 0})
False
See also: pickle.dumps not suitable for hashing
My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.
There's a number of fundamental problems with this. It's impossible to come up with an object-to-string transformation that maps equality correctly—think of the problem of object identity:
>>> a = object()
>>> b = object()
>>> a == b
False
>>> pickle.dumps(b) == pickle.dumps(a)
True
Depending on your exact requirements, you may be able to transform object hierarchies into ones that you could then hash:
def hashablize(obj):
"""Convert a container hierarchy into one that can be hashed.
Don't use this with recursive structures!
Also, this won't be useful if you pass dictionaries with
keys that don't have a total order.
Actually, maybe you're best off not using this function at all."""
try:
hash(obj)
except TypeError:
if isinstance(obj, dict):
return tuple((k, hashablize(v)) for (k, v) in sorted(obj.iteritems()))
elif hasattr(obj, '__iter__'):
return tuple(hashablize(o) for o in obj)
else:
raise TypeError("Can't hashablize object of type %r" % type(obj))
else:
return obj
A:
What do you mean by same output ? You should normally always get the same output for a roundtrip (pickling -> unpickling), but I don't think the serialized format itself is guaranteed to be the same in every condition. Certainly, it may change between platforms and all that.
Within one run of your program, using pickling for memoization should be fine - I have used this scheme several times without trouble, but that was for quite simple problems. One problem is that this does not cover every useful case (function come to mind: you cannot pickle them, so if your function takes a callable argument, that won't work).
|
Is the pickling process deterministic?
|
Does Pickle always produce the same output for a certain input value? I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories. My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.
|
[
"\nI suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories.\n\nRight:\n>>> pickle.dumps({1: 0, 9: 0}) == pickle.dumps({9: 0, 1: 0})\nFalse\n\nSee also: pickle.dumps not suitable for hashing\n\nMy goal is to create a \"signature\" of function arguments, using Pickle and SHA1, for a memoize implementation.\n\nThere's a number of fundamental problems with this. It's impossible to come up with an object-to-string transformation that maps equality correctly—think of the problem of object identity:\n>>> a = object()\n>>> b = object()\n>>> a == b\nFalse\n>>> pickle.dumps(b) == pickle.dumps(a)\nTrue\n\nDepending on your exact requirements, you may be able to transform object hierarchies into ones that you could then hash:\ndef hashablize(obj):\n \"\"\"Convert a container hierarchy into one that can be hashed.\n \n Don't use this with recursive structures!\n Also, this won't be useful if you pass dictionaries with\n keys that don't have a total order.\n Actually, maybe you're best off not using this function at all.\"\"\"\n try:\n hash(obj)\n except TypeError:\n if isinstance(obj, dict):\n return tuple((k, hashablize(v)) for (k, v) in sorted(obj.iteritems()))\n elif hasattr(obj, '__iter__'):\n return tuple(hashablize(o) for o in obj)\n else:\n raise TypeError(\"Can't hashablize object of type %r\" % type(obj))\n else:\n return obj\n\n",
"What do you mean by same output ? You should normally always get the same output for a roundtrip (pickling -> unpickling), but I don't think the serialized format itself is guaranteed to be the same in every condition. Certainly, it may change between platforms and all that.\nWithin one run of your program, using pickling for memoization should be fine - I have used this scheme several times without trouble, but that was for quite simple problems. One problem is that this does not cover every useful case (function come to mind: you cannot pickle them, so if your function takes a callable argument, that won't work).\n"
] |
[
9,
0
] |
[] |
[] |
[
"memoization",
"pickle",
"python"
] |
stackoverflow_0000985294_memoization_pickle_python.txt
|
Q:
Convert a value into row, column and char
My data structure is initialized as follows:
[[0,0,0,0,0,0,0,0] for x in range(8)]
8 characters, 8 rows, each row has 5 bits for columns, so each integer can be in the range between 0 and 31 inclusive.
I have to convert the number 177 (can be between 0 and 319) into char, row, and column.
Let me try again, this time with a better code example. No bits are set.
Ok, I added the reverse to the problem. Maybe that'll help.
chars = [[0,0,0,0,0,0,0,0] for x in range(8)]
# reverse solution
for char in range(8):
for row in range(8):
for col in range(5):
n = char * 40 + (row * 5 + col)
chars[char][row] = chars[char][row] ^ [0, 1<<4-col][row < col]
for data in range(320):
char = data / 40
col = (data - char * 40) % 5
row = ?
print "Char %g, Row %g, Col %g" % (char, row, col), chars[char][row] & 1<<4-col
A:
Okay, this looks as if you're working with a 1x8 LCD display, where each character is 8 rows of 5 pixels.
So, you have a total of 8 * (8 * 5) = 320 pixels, and you want to map the index of a pixel to a position in the "framebuffer" decribing the display's contents.
I assume pixels are distributed like this (shown for the first char only), your initial loops indicate this is is correct:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
25 26 27 28 29
30 31 32 33 34
35 36 37 38 39
We then have:
# Compute which of the 8 characters the pixel falls in, 0..7:
char = int(number / 40)
# Compute which pixel column the pixel is in, 0..4:
col = number % 5
# Compute which pixel row the pixel is in, 0..7:
row = int((number - char * 40) / 5)
I used explicit int()s to make it clear that the numbers are integers.
Note that you might want to flip the column, since this numbers them from the left.
A:
Are you looking for divmod function?
[Edit: using python operators instead of pseudo language.]
char is between 0 and 319
character = (char % 40)
column = (char / 40) % 5
row = (char / 40) / 5
|
Convert a value into row, column and char
|
My data structure is initialized as follows:
[[0,0,0,0,0,0,0,0] for x in range(8)]
8 characters, 8 rows, each row has 5 bits for columns, so each integer can be in the range between 0 and 31 inclusive.
I have to convert the number 177 (can be between 0 and 319) into char, row, and column.
Let me try again, this time with a better code example. No bits are set.
Ok, I added the reverse to the problem. Maybe that'll help.
chars = [[0,0,0,0,0,0,0,0] for x in range(8)]
# reverse solution
for char in range(8):
for row in range(8):
for col in range(5):
n = char * 40 + (row * 5 + col)
chars[char][row] = chars[char][row] ^ [0, 1<<4-col][row < col]
for data in range(320):
char = data / 40
col = (data - char * 40) % 5
row = ?
print "Char %g, Row %g, Col %g" % (char, row, col), chars[char][row] & 1<<4-col
|
[
"Okay, this looks as if you're working with a 1x8 LCD display, where each character is 8 rows of 5 pixels.\nSo, you have a total of 8 * (8 * 5) = 320 pixels, and you want to map the index of a pixel to a position in the \"framebuffer\" decribing the display's contents.\nI assume pixels are distributed like this (shown for the first char only), your initial loops indicate this is is correct:\n 0 1 2 3 4\n 5 6 7 8 9\n10 11 12 13 14\n15 16 17 18 19\n20 21 22 23 24\n25 26 27 28 29\n30 31 32 33 34\n35 36 37 38 39\n\nWe then have:\n # Compute which of the 8 characters the pixel falls in, 0..7:\n char = int(number / 40)\n\n # Compute which pixel column the pixel is in, 0..4:\n col = number % 5\n\n # Compute which pixel row the pixel is in, 0..7:\n row = int((number - char * 40) / 5)\n\nI used explicit int()s to make it clear that the numbers are integers.\nNote that you might want to flip the column, since this numbers them from the left.\n",
"Are you looking for divmod function?\n[Edit: using python operators instead of pseudo language.]\nchar is between 0 and 319\n\ncharacter = (char % 40)\ncolumn = (char / 40) % 5\nrow = (char / 40) / 5\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"math",
"python"
] |
stackoverflow_0000984888_math_python.txt
|
Q:
Django: How can I change a ModelForm's Many2ManyField (select tag) choices verbose values?
For example:
I have the follow model
class Categories(models.Model):
name = models.CharField(max_length=100,verbose_name="Category Name")
parent_cat = models.ForeignKey('self',verbose_name="Parent Category",null=True,blank=True,related_name="child_cat")
description = models.TextField(verbose_name="Category Description",blank=True)
As one can see, this is a tree-structure table. I also have a ModelForm which consist of a ForeignKey for Categories:
p_category = models.ForeignKey(Categories,verbose_name="Category")
A sample category tree like structure might be as the following:
Brand
Red
Color
Red
Each of them have a row in Categories. However you would noticed 2 distinct "Red" rows, both which represent different things, 1 of a red color, the other of a brand named "Red".
However in the ForeignKey modelform, which is represented by the tag in the form, it would show 2 similar "Red" options. This is where I hope to change the verbose value of the tag to reflect something more relevant.
From:
<option>Red</option>
To:
<option>Color > Red</option>
How can I do this?
A:
I'm not sure if this is the best way, but you could edit the Categories model so it looks like this:
class Categories(models.Model):
name = models.CharField(max_length=100,verbose_name="Category Name")
parent_cat = models.ForeignKey('self',verbose_name="Parent Category",null=True,blank=True,related_name="child_cat")
description = models.TextField(verbose_name="Category Description",blank=True)
def __unicode__(self):
name = ''
if self.parent_cat:
name = self.parent_cat + ' > '
return name + self.name
That should give you what you expect.
|
Django: How can I change a ModelForm's Many2ManyField (select tag) choices verbose values?
|
For example:
I have the follow model
class Categories(models.Model):
name = models.CharField(max_length=100,verbose_name="Category Name")
parent_cat = models.ForeignKey('self',verbose_name="Parent Category",null=True,blank=True,related_name="child_cat")
description = models.TextField(verbose_name="Category Description",blank=True)
As one can see, this is a tree-structure table. I also have a ModelForm which consist of a ForeignKey for Categories:
p_category = models.ForeignKey(Categories,verbose_name="Category")
A sample category tree like structure might be as the following:
Brand
Red
Color
Red
Each of them have a row in Categories. However you would noticed 2 distinct "Red" rows, both which represent different things, 1 of a red color, the other of a brand named "Red".
However in the ForeignKey modelform, which is represented by the tag in the form, it would show 2 similar "Red" options. This is where I hope to change the verbose value of the tag to reflect something more relevant.
From:
<option>Red</option>
To:
<option>Color > Red</option>
How can I do this?
|
[
"I'm not sure if this is the best way, but you could edit the Categories model so it looks like this:\nclass Categories(models.Model):\n name = models.CharField(max_length=100,verbose_name=\"Category Name\")\n parent_cat = models.ForeignKey('self',verbose_name=\"Parent Category\",null=True,blank=True,related_name=\"child_cat\")\n description = models.TextField(verbose_name=\"Category Description\",blank=True)\n\n def __unicode__(self):\n name = ''\n if self.parent_cat:\n name = self.parent_cat + ' > '\n return name + self.name\n\nThat should give you what you expect.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0000985543_django_python.txt
|
Q:
Dynamic Language Features and Meta-Programming Used in Django
Any good summary articles of the dynamic language and meta-programming features of Python that get utilized by Django? Or can we build that out here? Setting this up as a wiki-style entry.
A:
Marty Alchin (Gulopine) has a few articles on various bits of Django internals - including metaclasses and descriptors - on his blog:
http://martyalchin.com/categories/django/
|
Dynamic Language Features and Meta-Programming Used in Django
|
Any good summary articles of the dynamic language and meta-programming features of Python that get utilized by Django? Or can we build that out here? Setting this up as a wiki-style entry.
|
[
"Marty Alchin (Gulopine) has a few articles on various bits of Django internals - including metaclasses and descriptors - on his blog:\nhttp://martyalchin.com/categories/django/\n"
] |
[
2
] |
[] |
[] |
[
"django",
"dynamic_languages",
"metaprogramming",
"python"
] |
stackoverflow_0000984272_django_dynamic_languages_metaprogramming_python.txt
|
Q:
Correct way of handling exceptions in Python?
I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.
I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.
My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.
For your consideration, an example:
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?
I am also interested in proper resource cleanup, even Python can manage that for itself.
Thanks, Tom
A:
Instead of using the try/except's else block, you could simply return when it errors:
def send_message(addr, to, msg):
## Connect to host
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
return False
## Login
try:
server.login(username, password)
except SMTPAuthenticationError:
server.quit()
return False
## Send message
try:
server.sendmail(addr, [to], msg.as_string())
return True
except Exception: # try to avoid catching Exception unless you have too
return False
finally:
server.quit()
That's perfectly readable and Pythonic..
Another way of doing this is, rather than worry about the specific implementation, decide how you want your code to look, for example..
sender = MyMailer("username", "password") # the except SocketError/AuthError could go here
try:
sender.message("addr..", ["to.."], "message...")
except SocketError:
print "Couldn't connect to server"
except AuthError:
print "Invalid username and/or password!"
else:
print "Message sent!"
Then write the code for the message() method, catching any errors you expect, and raising your own custom one, and handle that where it's relevant. Your class may look something like..
class ConnectionError(Exception): pass
class AuthError(Exception): pass
class SendError(Exception): pass
class MyMailer:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
def connect(self):
try:
self.server = smtp.SMTP(self.host)
except smtplib.socket.gaierror:
raise ConnectionError("Error connecting to %s" % (self.host))
def auth(self):
try:
self.server.login(self.username, self.password)
except SMTPAuthenticationError:
raise AuthError("Invalid username (%s) and/or password" % (self.username))
def message(self, addr, to, msg):
try:
server.sendmail(addr, [to], msg.as_string())
except smtplib.something.senderror, errormsg:
raise SendError("Couldn't send message: %s" % (errormsg))
except smtp.socket.timeout:
raise ConnectionError("Socket error while sending message")
A:
In general, you want to use as few try blocks as possible, distinguishing failure conditions by the kinds of exceptions they throw. For instance, here's my refactoring of the code you posted:
try:
server = smtplib.SMTP(host)
server.login(username, password) # Only runs if the previous line didn't throw
server.sendmail(addr, [to], msg.as_string())
return True
except smtplib.socket.gaierror:
pass # Couldn't contact the host
except SMTPAuthenticationError:
pass # Login failed
except SomeSendMailError:
pass # Couldn't send mail
finally:
if server:
server.quit()
return False
Here, we use the fact that smtplib.SMTP(), server.login(), and server.sendmail() all throw different exceptions to flatten the tree of try-catch blocks. In the finally block we test server explicitly to avoid invoking quit() on the nil object.
We could also use three sequential try-catch blocks, returning False in the exception conditions, if there are overlapping exception cases that need to be handled separately:
try:
server = smtplib.SMTP(host)
except smtplib.socket.gaierror:
return False # Couldn't contact the host
try:
server.login(username, password)
except SMTPAuthenticationError:
server.quit()
return False # Login failed
try:
server.sendmail(addr, [to], msg.as_string())
except SomeSendMailError:
server.quit()
return False # Couldn't send mail
return True
This isn't quite as nice, as you have to kill the server in more than one place, but now we can handle specific exception types different ways in different places without maintaining any extra state.
A:
If it was me I would probably do something like the following:
try:
server = smtplib.SMTP(host)
try:
server.login(username, password)
server.sendmail(addr, [to], str(msg))
finally:
server.quit()
except:
debug("sendmail", traceback.format_exc().splitlines()[-1])
return True
All errors are caught and debugged, the return value == True on success, and the server connection is properly cleaned up if the initial connection is made.
A:
Just using one try-block is the way to go. This is exactly what they
are designed for: only execute the next statement if the previous
statement did not throw an exception. As for the resource clean-ups,
maybe you can check the resource if it needs to be cleaned up
(e.g. myfile.is_open(), ...) This does add some extra conditions, but
they will only be executed in the exceptional case. To handle the case
that the same Exception can be raised for different reasons, you
should be able to retrieve the reason from the Exception.
I suggest code like this:
server = None
try:
server = smtplib.SMTP(host) #can throw an exception
server.login(username, password)
server.sendmail(addr, [to], msg.as_string())
server.quit()
return True
except smtplib.socket.gaierror:
pass # do some stuff here
except SMTPAuthenticationError:
pass # do some stuff here
except Exception, msg:
# Exception can have several reasons
if msg=='xxx':
pass # do some stuff here
elif:
pass # do some other stuff here
if server:
server.quit()
return False
It is no uncommon, that error handling code exceeds business code. Correct error handling can be complex.
But to increase maintainability it helps to separate the business code from the error handling code.
A:
I would try something like this:
class Mailer():
def send_message(self):
exception = None
for method in [self.connect,
self.authenticate,
self.send,
self.quit]:
try:
if not method(): break
except Exception, ex:
exception = ex
break
if method == quit and exception == None:
return True
if exception:
self.handle_exception(method, exception)
else:
self.handle_failure(method)
def connect(self):
return True
def authenticate(self):
return True
def send(self):
return True
def quit(self):
return True
def handle_exception(self, method, exception):
print "{name} ({msg}) in {method}.".format(
name=exception.__class__.__name__,
msg=exception,
method=method.__name__)
def handle_failure(self, method):
print "Failure in {0}.".format(method.__name__)
All of the methods (including send_message, really) follow the same protocol: they return True if they succeeded, and unless they actually handle an exception, they don't trap it. This protocol also makes it possible to handle the case where a method needs to indicate that it failed without raising an exception. (If the only way your methods fail is by raising an exception, that simplifies the protocol. If you're having to deal with a lot of non-exception failure states outside of the method that failed, you probably have a design problem that you haven't worked out yet.)
The downside of this approach is that all of the methods have to use the same arguments. I've opted for none, with the expectation that the methods I've stubbed out will end up manipulating class members.
The upside of this approach is considerable, though. First, you can add dozens of methods to the process without send_message getting any more complex.
You can also go crazy and do something like this:
def handle_exception(self, method, exception):
custom_handler_name = "handle_{0}_in_{1}".format(\
exception.__class__.__name__,
method.__name__)
try:
custom_handler = self.__dict__[custom_handler_name]
except KeyError:
print "{name} ({msg}) in {method}.".format(
name=exception.__class__.__name__,
msg=exception,
method=method.__name__)
return
custom_handler()
def handle_AuthenticationError_in_authenticate(self):
print "Your login credentials are questionable."
...though at that point, I might say to myself, "self, you're working the Command pattern pretty hard without creating a Command class. Maybe now is the time."
A:
Why not one big try: block? This way, if any exception is caught, you'll go all the way to the except. And as long as all the exceptions for the different steps are different, you can always tell which part it was that fired the exception.
A:
I like David's answer but if you are stuck on the server exceptions you can also check for server if is None or states. I flattened out the method a bit bit it is still a but unpythonic looking but more readable in the logic at the bottom.
server = None
def server_obtained(host):
try:
server = smtplib.SMTP(host) #can throw an exception
return True
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
return False
def server_login(username, password):
loggedin = False
try:
server.login(username, password)
loggedin = True
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
if(server is not None):
server.quit()
return loggedin
def send_mail(addr, to, msg):
sent = False
try:
server.sendmail(addr, to, msg)
sent = True
except Exception:
return False
finally:
server.quit()
return sent
def do_msg_send():
if(server_obtained(host)):
if(server_login(username, password)):
if(send_mail(addr, [to], msg.as_string())):
return True
return False
|
Correct way of handling exceptions in Python?
|
I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.
I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.
My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.
For your consideration, an example:
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?
I am also interested in proper resource cleanup, even Python can manage that for itself.
Thanks, Tom
|
[
"Instead of using the try/except's else block, you could simply return when it errors:\ndef send_message(addr, to, msg):\n ## Connect to host\n try:\n server = smtplib.SMTP(host) #can throw an exception\n except smtplib.socket.gaierror:\n return False\n\n ## Login\n try:\n server.login(username, password)\n except SMTPAuthenticationError:\n server.quit()\n return False\n\n ## Send message\n try:\n server.sendmail(addr, [to], msg.as_string())\n return True\n except Exception: # try to avoid catching Exception unless you have too\n return False\n finally:\n server.quit()\n\nThat's perfectly readable and Pythonic..\nAnother way of doing this is, rather than worry about the specific implementation, decide how you want your code to look, for example..\nsender = MyMailer(\"username\", \"password\") # the except SocketError/AuthError could go here\ntry:\n sender.message(\"addr..\", [\"to..\"], \"message...\")\nexcept SocketError:\n print \"Couldn't connect to server\"\nexcept AuthError:\n print \"Invalid username and/or password!\"\nelse:\n print \"Message sent!\"\n\nThen write the code for the message() method, catching any errors you expect, and raising your own custom one, and handle that where it's relevant. Your class may look something like..\nclass ConnectionError(Exception): pass\nclass AuthError(Exception): pass\nclass SendError(Exception): pass\n\nclass MyMailer:\n def __init__(self, host, username, password):\n self.host = host\n self.username = username\n self.password = password\n\n def connect(self):\n try:\n self.server = smtp.SMTP(self.host)\n except smtplib.socket.gaierror:\n raise ConnectionError(\"Error connecting to %s\" % (self.host))\n\n def auth(self):\n try:\n self.server.login(self.username, self.password)\n except SMTPAuthenticationError:\n raise AuthError(\"Invalid username (%s) and/or password\" % (self.username))\n\n def message(self, addr, to, msg):\n try:\n server.sendmail(addr, [to], msg.as_string())\n except smtplib.something.senderror, errormsg:\n raise SendError(\"Couldn't send message: %s\" % (errormsg))\n except smtp.socket.timeout:\n raise ConnectionError(\"Socket error while sending message\")\n\n",
"In general, you want to use as few try blocks as possible, distinguishing failure conditions by the kinds of exceptions they throw. For instance, here's my refactoring of the code you posted:\ntry:\n server = smtplib.SMTP(host)\n server.login(username, password) # Only runs if the previous line didn't throw\n server.sendmail(addr, [to], msg.as_string())\n return True\nexcept smtplib.socket.gaierror:\n pass # Couldn't contact the host\nexcept SMTPAuthenticationError:\n pass # Login failed\nexcept SomeSendMailError:\n pass # Couldn't send mail\nfinally:\n if server:\n server.quit()\nreturn False\n\nHere, we use the fact that smtplib.SMTP(), server.login(), and server.sendmail() all throw different exceptions to flatten the tree of try-catch blocks. In the finally block we test server explicitly to avoid invoking quit() on the nil object.\nWe could also use three sequential try-catch blocks, returning False in the exception conditions, if there are overlapping exception cases that need to be handled separately:\ntry:\n server = smtplib.SMTP(host)\nexcept smtplib.socket.gaierror:\n return False # Couldn't contact the host\n\ntry:\n server.login(username, password)\nexcept SMTPAuthenticationError:\n server.quit()\n return False # Login failed\n\ntry:\n server.sendmail(addr, [to], msg.as_string())\nexcept SomeSendMailError:\n server.quit()\n return False # Couldn't send mail\n\nreturn True\n\nThis isn't quite as nice, as you have to kill the server in more than one place, but now we can handle specific exception types different ways in different places without maintaining any extra state.\n",
"If it was me I would probably do something like the following:\ntry:\n server = smtplib.SMTP(host)\n try:\n server.login(username, password)\n server.sendmail(addr, [to], str(msg))\n finally:\n server.quit()\nexcept:\n debug(\"sendmail\", traceback.format_exc().splitlines()[-1])\n return True\n\nAll errors are caught and debugged, the return value == True on success, and the server connection is properly cleaned up if the initial connection is made.\n",
"Just using one try-block is the way to go. This is exactly what they\nare designed for: only execute the next statement if the previous\nstatement did not throw an exception. As for the resource clean-ups,\nmaybe you can check the resource if it needs to be cleaned up\n(e.g. myfile.is_open(), ...) This does add some extra conditions, but\nthey will only be executed in the exceptional case. To handle the case\nthat the same Exception can be raised for different reasons, you\nshould be able to retrieve the reason from the Exception.\nI suggest code like this:\nserver = None\ntry:\n server = smtplib.SMTP(host) #can throw an exception\n server.login(username, password)\n server.sendmail(addr, [to], msg.as_string())\n server.quit()\n return True\nexcept smtplib.socket.gaierror:\n pass # do some stuff here\nexcept SMTPAuthenticationError:\n pass # do some stuff here\nexcept Exception, msg:\n # Exception can have several reasons\n if msg=='xxx':\n pass # do some stuff here\n elif:\n pass # do some other stuff here\n\nif server:\n server.quit()\n\nreturn False\n\nIt is no uncommon, that error handling code exceeds business code. Correct error handling can be complex.\nBut to increase maintainability it helps to separate the business code from the error handling code.\n",
"I would try something like this:\nclass Mailer():\n\n def send_message(self):\n exception = None\n for method in [self.connect, \n self.authenticate, \n self.send, \n self.quit]:\n try:\n if not method(): break\n except Exception, ex:\n exception = ex\n break\n\n if method == quit and exception == None:\n return True\n\n if exception:\n self.handle_exception(method, exception)\n else:\n self.handle_failure(method)\n\n def connect(self):\n return True\n\n def authenticate(self):\n return True\n\n def send(self):\n return True\n\n def quit(self):\n return True\n\n def handle_exception(self, method, exception):\n print \"{name} ({msg}) in {method}.\".format(\n name=exception.__class__.__name__, \n msg=exception,\n method=method.__name__)\n\n def handle_failure(self, method):\n print \"Failure in {0}.\".format(method.__name__)\n\nAll of the methods (including send_message, really) follow the same protocol: they return True if they succeeded, and unless they actually handle an exception, they don't trap it. This protocol also makes it possible to handle the case where a method needs to indicate that it failed without raising an exception. (If the only way your methods fail is by raising an exception, that simplifies the protocol. If you're having to deal with a lot of non-exception failure states outside of the method that failed, you probably have a design problem that you haven't worked out yet.)\nThe downside of this approach is that all of the methods have to use the same arguments. I've opted for none, with the expectation that the methods I've stubbed out will end up manipulating class members.\nThe upside of this approach is considerable, though. First, you can add dozens of methods to the process without send_message getting any more complex. \nYou can also go crazy and do something like this:\ndef handle_exception(self, method, exception):\n custom_handler_name = \"handle_{0}_in_{1}\".format(\\\n exception.__class__.__name__,\n method.__name__)\n try:\n custom_handler = self.__dict__[custom_handler_name]\n except KeyError:\n print \"{name} ({msg}) in {method}.\".format(\n name=exception.__class__.__name__, \n msg=exception,\n method=method.__name__)\n return\n custom_handler()\n\ndef handle_AuthenticationError_in_authenticate(self):\n print \"Your login credentials are questionable.\"\n\n...though at that point, I might say to myself, \"self, you're working the Command pattern pretty hard without creating a Command class. Maybe now is the time.\"\n",
"Why not one big try: block? This way, if any exception is caught, you'll go all the way to the except. And as long as all the exceptions for the different steps are different, you can always tell which part it was that fired the exception.\n",
"I like David's answer but if you are stuck on the server exceptions you can also check for server if is None or states. I flattened out the method a bit bit it is still a but unpythonic looking but more readable in the logic at the bottom.\nserver = None \n\ndef server_obtained(host):\n try:\n server = smtplib.SMTP(host) #can throw an exception\n return True\n except smtplib.socket.gaierror:\n #actually it can throw a lot more, this is just an example\n return False\n\ndef server_login(username, password):\n loggedin = False\n try:\n server.login(username, password)\n loggedin = True\n except SMTPAuthenticationError:\n pass # do some stuff here\n finally:\n #we can only run this when the first try...except was successful\n #else this throws an exception itself!\n if(server is not None):\n server.quit()\n return loggedin\n\ndef send_mail(addr, to, msg):\n sent = False\n try:\n server.sendmail(addr, to, msg)\n sent = True\n except Exception:\n return False\n finally:\n server.quit()\n return sent\n\ndef do_msg_send():\n if(server_obtained(host)):\n if(server_login(username, password)):\n if(send_mail(addr, [to], msg.as_string())):\n return True\n return False \n\n"
] |
[
26,
12,
3,
1,
1,
0,
0
] |
[] |
[] |
[
"exception",
"python"
] |
stackoverflow_0000984526_exception_python.txt
|
Q:
Python and Collective Intelligence
I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)
The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.
This leaves my with the issue of translating the python examples into C#.
Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?
A:
One challenge you'll find is that not only are the algorithms implemented in Python, but the book makes extensive use of Python libraries like BeautifulSoup, Numpy, PIL, and others (see appendix A).
I doubt there are any specifics of the algorithms that you couldn't port to another language, but you'll have trouble working through the exercises. Also, to translate the code, you'll have to learn Python at least a little bit, no?
I suggest you just dive in and learn Python. You can use IronPython if you have any concern about interoperability with your C# projects.
A:
You can do the same things in all Turing-complete languages. Here is an example for rendering a Mandelbrot fractal in SQL. The example shows: Even if you can use any language, the effort will be different.
So my guess is that the code will become much longer since Python is so flexible and open.
A:
I suggest translating them to C#. I have been porting chapter 2 "Recommendations" to VB.Net. Along the way I'm learning Python as a side-effect. Toby does some amazing things with Python lists.
Dealing with the the extra Python libraries is another story. Ndelicious is a close match to pyDelicious, but it is missing a few key features (popular posts!).
A:
Obligatory XKCD: http://xkcd.com/353/
I know you explicitly say you don't want to learn Python (this year), but translating the Python examples to C# will definitely be a much steeper curve. Just dive in!
A:
The book is about algorithms, not the details of programming, and the language of choice is just to make the examples concrete. As the author says, "The code examples in this book are written in Python... but I provide explanations of all the algorithms so that programmers of other languages can follow." (p. xv)
Python is a great language and easy to learn, but I suspect the difficulties in applying ideas from the book will not be in the translating of the code to another language or set of libraries, but in understanding the ideas and modifying the code to suite your needs. I think there are two main reasons to stay with a language you're familiar with: 1) when your code doesn't work, if you're writing in an unfamiliar language, you won't know where to start looking for errors, e.g. if you're like most people you'll even start wondering if it's due to a bug in Python, which it won't be, but you'll wonder and it will distract. 2) There are just natural limits to how much you can remember in a certain length of time; and learning a language at the same time will give you twice as much to remember.
It depends though how well you know C#, and what you lose by leaving it.
A:
Python seems to be to AI programming what LISP was for for many decades. Russel/Norvig's famous book AI: A Modern Approach also provides lots of examples in Python.
|
Python and Collective Intelligence
|
I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)
The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.
This leaves my with the issue of translating the python examples into C#.
Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?
|
[
"One challenge you'll find is that not only are the algorithms implemented in Python, but the book makes extensive use of Python libraries like BeautifulSoup, Numpy, PIL, and others (see appendix A).\nI doubt there are any specifics of the algorithms that you couldn't port to another language, but you'll have trouble working through the exercises. Also, to translate the code, you'll have to learn Python at least a little bit, no? \nI suggest you just dive in and learn Python. You can use IronPython if you have any concern about interoperability with your C# projects.\n",
"You can do the same things in all Turing-complete languages. Here is an example for rendering a Mandelbrot fractal in SQL. The example shows: Even if you can use any language, the effort will be different.\nSo my guess is that the code will become much longer since Python is so flexible and open.\n",
"I suggest translating them to C#. I have been porting chapter 2 \"Recommendations\" to VB.Net. Along the way I'm learning Python as a side-effect. Toby does some amazing things with Python lists.\nDealing with the the extra Python libraries is another story. Ndelicious is a close match to pyDelicious, but it is missing a few key features (popular posts!).\n",
"Obligatory XKCD: http://xkcd.com/353/\nI know you explicitly say you don't want to learn Python (this year), but translating the Python examples to C# will definitely be a much steeper curve. Just dive in!\n",
"The book is about algorithms, not the details of programming, and the language of choice is just to make the examples concrete. As the author says, \"The code examples in this book are written in Python... but I provide explanations of all the algorithms so that programmers of other languages can follow.\" (p. xv)\nPython is a great language and easy to learn, but I suspect the difficulties in applying ideas from the book will not be in the translating of the code to another language or set of libraries, but in understanding the ideas and modifying the code to suite your needs. I think there are two main reasons to stay with a language you're familiar with: 1) when your code doesn't work, if you're writing in an unfamiliar language, you won't know where to start looking for errors, e.g. if you're like most people you'll even start wondering if it's due to a bug in Python, which it won't be, but you'll wonder and it will distract. 2) There are just natural limits to how much you can remember in a certain length of time; and learning a language at the same time will give you twice as much to remember.\nIt depends though how well you know C#, and what you lose by leaving it.\n",
"Python seems to be to AI programming what LISP was for for many decades. Russel/Norvig's famous book AI: A Modern Approach also provides lots of examples in Python.\n"
] |
[
20,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"collective_intelligence",
"python"
] |
stackoverflow_0000863253_collective_intelligence_python.txt
|
Q:
What does this line mean in Python?
Which CPU information this code is trying to retrieve. This code is part of a larger package. I am not a Python programmer, and I want to convert this code to C#.
from ctypes import c_uint, create_string_buffer, CFUNCTYPE, addressof
CPUID = create_string_buffer("\x53\x31\xc0\x40\x0f\xa2\x5b\xc3")
cpuinfo = CFUNCTYPE(c_uint)(addressof(CPUID))
print cpuinfo()
If you are a Python programmer and knows what this code is doing, it will be a great help for me.
A:
It executes the following machine code:
push bx
xor ax, ax
inc ax
cpuid
pop bx
retn
Basically it calls CPUID instruction of the CPU in order to get information about the CPU. Since EAX=1 it gets the processor info and feature bits. The result 32-bit integer is then displayed on the screen, see the wikipedia article or this page to decode the result.
EDIT: Since that's what you're looking for, here's an excellent article about invoking CPUID in a .NET/C# environment (sort of, with P/Invoke)
A:
In addition to DrJokepu's answer. The python code is using the ctypes modules do implement the following C code(/hack):
char *CPUID = "\x53\x31\xc0\x40\x0f\xa2\x5b\xc3"; // x86 code
unsigned int (*cpuid)() = (unsigned int (*)()) CPUID; // CPUID points to first instruction in above code; cast it to a function pointer
printf("%u",cpuid()); // calling cpuid() effectively executes the x86 code.
Also note that this only returns the information in EAX and the x86 code should probably have also pushed/popped the values of ECX and EDX to be safe.
|
What does this line mean in Python?
|
Which CPU information this code is trying to retrieve. This code is part of a larger package. I am not a Python programmer, and I want to convert this code to C#.
from ctypes import c_uint, create_string_buffer, CFUNCTYPE, addressof
CPUID = create_string_buffer("\x53\x31\xc0\x40\x0f\xa2\x5b\xc3")
cpuinfo = CFUNCTYPE(c_uint)(addressof(CPUID))
print cpuinfo()
If you are a Python programmer and knows what this code is doing, it will be a great help for me.
|
[
"It executes the following machine code:\npush bx\nxor ax, ax\ninc ax\ncpuid\npop bx\nretn\n\nBasically it calls CPUID instruction of the CPU in order to get information about the CPU. Since EAX=1 it gets the processor info and feature bits. The result 32-bit integer is then displayed on the screen, see the wikipedia article or this page to decode the result.\nEDIT: Since that's what you're looking for, here's an excellent article about invoking CPUID in a .NET/C# environment (sort of, with P/Invoke)\n",
"In addition to DrJokepu's answer. The python code is using the ctypes modules do implement the following C code(/hack):\nchar *CPUID = \"\\x53\\x31\\xc0\\x40\\x0f\\xa2\\x5b\\xc3\"; // x86 code\nunsigned int (*cpuid)() = (unsigned int (*)()) CPUID; // CPUID points to first instruction in above code; cast it to a function pointer\n\nprintf(\"%u\",cpuid()); // calling cpuid() effectively executes the x86 code.\n\nAlso note that this only returns the information in EAX and the x86 code should probably have also pushed/popped the values of ECX and EDX to be safe.\n"
] |
[
24,
6
] |
[] |
[] |
[
"c#",
"cpu",
"cpuid",
"python",
"windows"
] |
stackoverflow_0000986087_c#_cpu_cpuid_python_windows.txt
|
Q:
I need a beginners guide to setting up windows for python development
I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.
One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.
If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.
My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used.
A:
It's not that hard to set up a Python environment, and I've never had it muck up my .NET work. Basically, install Python --- I'd use 2.6 rather than 3.0, which is not yet broadly accepted --- and add it to your PATH, and you're ready to go with the language. I wouldn't recommend using a Ubuntu VM as your development environment; if you're working on Windows, you might as well develop on Windows, and I've had no significant problems doing so. I go back and forth from Windows to Linux with no trouble.
If you have an editor that you're comfortable with that has basic support for Python, I'd stick with it. If not, I've found Geany to be a nice, light, easy-to-use editor with good Python support, though I use Emacs myself because I know it; other people like SCITE, NotePad++, or any of a slew of others. I'd avoid fancy IDEs for Python, because they don't match the character of the language, and I wouldn't bother with IDLE (included with Python), because it's a royal pain to use.
Suggestions for libraries and frameworks:
Django is the standard web framework, but it's big and you have to work django's way; I prefer CherryPy, which is also actively supported, but is light, gives you great freedom, and contains a nice, solid webserver that can be replaced easily with httpd.
Django includes its own ORM, which is nice enough; there's a standalone one for Python, though, which is even nicer: SQL Alchemy
As far as a testing library goes, pyunit seems to me to be the obvious choice
Good luck, and welcome to a really fun language!
EDIT summary: I originally recommended Karrigell, but can't any more: since the 3.0 release, it's been continuously broken, and the community is not large enough to solve the problems. CherryPy is a good substitute if you like a light, simple framework that doesn't get in your way, so I've changed the above to suggest it instead.
A:
Well, if you're thinking of setting up an Ubuntu VM anyway, you might as well make that your development environment. Then you can install Apache and MySQL or Postgres on that VM just via the standard packaging tools (apt-get install), and there's no danger of polluting your Windows environment.
You can either do the actual development on your Windows machine via your favourite IDE, using the VM as a networked drive and saving the code there, or you can just use the VM as a full desktop environment and do everything there, which is what I would recommend.
A:
Install the pre-configured ActivePython release from activestate.
Among other features, it includes the PythonWin IDE (Windows only) which makes it easy to explore Python interactively.
The recommended reference is Dive Into Python, mentioned many times on similar SO discussions.
A:
You should install python 2.4, python 2.5, python 2.6 and python 3.0, and add to your path the one you use more often (Add c:\Pythonxx\ and c:\Pythonxx\Scripts).
For every python 2.x, install easy_install; Download ez_setup.py and then from the cmd:
c:\Python2x\python.exe x:\path\to\ez_setup.py
c:\Python2x\Scripts\easy_install virtualenv
Then each time you start a new project create a new virtual environment to isolate the specific package you needs for your project:
mkdir <project name>
cd <project name>
c:\Python2x\Scripts\virtualenv --no-site-packages .\v
It creates a copy of python and its libraries in .v\Scripts and .\v\Lib. Every third party packages you install in that environment will be put into .\v\Lib\site-packages. The -no-site-packages don't give access to the global site package, so you can be sure all your dependencies are in .\v\Lib\site-packages.
To activate the virtual environment:
.\v\Scripts\activate
For the frameworks, there are many. Django is great and very well documented but you should probably look at Pylons first for its documentions on unicode, packaging, deployment and testing, and for its better WSGI support.
For the IDE, Python comes with IDLE which is enough for learning, however you might want to look at Eclipse+PyDev, Komodo or Wingware Python IDE. Netbean 6.5 has beta support for python that looks promising (See top 5 python IDE).
For the webserver, you don't need any; Python has its own and all web framework come with their own. You might want to install MySql or ProgreSql; it's often better to develop on the same DB you will use for production.
Also, when you have learnt Python, look at Foundations of Agile Python Development or Expert Python Programming.
A:
Using Python on Windows
SO: Python tutorial for total beginners?
A:
Take a look at Pylons, read about WSGI and Paste.
There's nice introductory Google tech talk about them: ReUsable Web Components with Python and Future Python Web Development.
Here's my answer to similar question:
Django vs other Python web frameworks?
A:
Environment?
Here is the simplest solution:
Install Active Python 2.6. Its the Python itself, but comes with some extra handy useful stuff, like DiveintoPython chm.
Use Komodo Edit 5. It is among the good free editor you can use for Python.
Use IDLE. Its the best simplest short snippet editor, with syntax highlighting and auto complete unmatched by most other IDEs. It comes bundled with python.
Use Ipython. Its a shell that does syntax highlighting and auto complete, bash functions, pretty print, logging, history and many such things.
Install easy_install and/or pip for installing various 3rd party apps easily.
Coming from Visual Studio and .Net it will sound a lot different, but its an entirely different world.
For the framework, django works the best. Walk thro the tutorial and you will be impressed enough. The documentation rocks. The community, you have to see for yourself, to know how wonderful it is!!
A:
NOTE: I included a lot of links to frameworks, projects and what-not, but as a new user I was limited to 1 link per answer. If someone else with enough reputation to edit wants/can edit them into this answer instead of the footnotes, I'd be grateful.
There are some Python IDE's such as Wing IDE[1], I believe some people use Eclipse[2] with a python plugin[3] as well. A lot of people in the #python channel of FreeNode seem to prefer vim, emacs, nano and similar text editors in favor of IDE's. My personal preffered editor is Vim, but if you've mostly done .NET development on windows, presumably with the usual Visual X IDE's, vim and emacs will probably cause you culture shock and you'd be better of using an IDE.
Nearly all python web frameworks* support the WSGI standard[4], most of the large web servers have some sort of plugin to support WSGI, the others support WSGI via fast cgi or plain cgi.
The Zope[5] and Django[6] frameworks have their own ORM's, of other ORM's the two most well known appear to be SQL Alchemy[7] and SQL Object[8]. I only have experience with the former, but both support all possible sane database choices, including SQLite which is installed together with Python and hence perfectly suited to testing and experimenting without polluting your .NET environment with 3rd part web servers and database servers.
The builtin unittest[9] and pyunit[10] frameworks seem to be the preffered solutions for unit testing, but I don't have much experience with these.
bpython[11] and ipython[12] offer enhanced interactive python shells which can greatly help speed up and testing small bits of code and hence worth looking in to.
As for a list of well known and often used web frameworks, look into the following frameworks**:
Twisted[13] is a generic networking framework, which supports almost every single protocol under the sun.
Pylons[14] is light-weight framework aimed at being as flexible as possible and leaving all the choices about what ORM, templating language and what-not to you.
CherryPy[15] tries to provide an interface to expose Python objects to the web.
Django[6] attempts to be an all-in-one solution, builtin template system, ORM, admin pages and internationalization. While the previous frameworks have more DIY wiring together various frameworks work involved with them.
Zope[5] is aimed to be suitable for large enterprise applications, I've heard nothing but good things about it, but consensus seems to be that for smaller you're probably better off with one of the simpler and smaller frameworks.
TurboGears[16] is the framework I know the least about, but it seems to be mostly competition for Django.
This is everything I can think of right now, I'll edit and add stuff if I can think of it. I hope this helps you some in the wonderful world of python.
* - The main exception would be Apache's mod_python, which you should avoid for exactly that reason, use mod_wsgi instead.
** - Word of warning, I have not personally used these frameworks this is just a very short impression I have gotten from talking to other people about each framework, it may be wildly inaccurate. (If anyone has any corrections, do comment and I'll try to edit and fix this answer).
(The http:// is missing since they're recognized as links otherwise)
[1] www.wingware.com/
[2] www.eclipse.org/
[3] pydev.sourceforge.net/
[4] wsgi.org/wsgi/
[5] www.zope.org/
[6] www.djangoproject.com/
[7] www.sqlalchemy.org/
[8] www.sqlobject.org/
[9] docs.python.org/library/unittest.html
[10] pyunit.sourceforge.net/pyunit.html
[11] www.bpython-interpreter.org/
[12] ipython.scipy.org/
[13] twistedmatrix.com/trac/
[14] pylonshq.com/
[15] www.cherrypy.org/
[16] turbogears.org/
A:
Python has build in SQL like database and web server, so you wouldn't need to install any third party apps. Remember Python comes with batteries included.
A:
If you've worked with Eclipse before you could give Pydev a try
|
I need a beginners guide to setting up windows for python development
|
I currently work with .NET exclusively and would like to have a go at python. To this end I need to set up a python development environment. I guide to this would be handy. I guess I would be doing web development so will need a web server and probably a database. I also need pointers to popular ORM's, an MVC framework, and a testing library.
One of my main criteria with all this is that I want to understand how it works, and I want it to be as isolated as possible. This is important as i am wary of polluting what is a working .NET environment with 3rd party web and database servers. I am perfectly happy using SQLite to start with if this is possible.
If I get on well with this I am also likely to want to set up automated build and ci server (On a virtual machine, probably ubuntu). Any suggestions for these would be useful.
My ultimate aim if i like python is to have similar sorts of tools that i have available with .NET and to really understand the build and deployment of it all. To start with I will settle for a simple development environment that is as isolated as possible and will be easy to remove if I don't like it. I don't want to use IronPython as I want the full experience of developing a python solution using the tools and frameworks that are generally used.
|
[
"It's not that hard to set up a Python environment, and I've never had it muck up my .NET work. Basically, install Python --- I'd use 2.6 rather than 3.0, which is not yet broadly accepted --- and add it to your PATH, and you're ready to go with the language. I wouldn't recommend using a Ubuntu VM as your development environment; if you're working on Windows, you might as well develop on Windows, and I've had no significant problems doing so. I go back and forth from Windows to Linux with no trouble. \nIf you have an editor that you're comfortable with that has basic support for Python, I'd stick with it. If not, I've found Geany to be a nice, light, easy-to-use editor with good Python support, though I use Emacs myself because I know it; other people like SCITE, NotePad++, or any of a slew of others. I'd avoid fancy IDEs for Python, because they don't match the character of the language, and I wouldn't bother with IDLE (included with Python), because it's a royal pain to use.\nSuggestions for libraries and frameworks:\n\nDjango is the standard web framework, but it's big and you have to work django's way; I prefer CherryPy, which is also actively supported, but is light, gives you great freedom, and contains a nice, solid webserver that can be replaced easily with httpd.\nDjango includes its own ORM, which is nice enough; there's a standalone one for Python, though, which is even nicer: SQL Alchemy\nAs far as a testing library goes, pyunit seems to me to be the obvious choice\n\nGood luck, and welcome to a really fun language!\nEDIT summary: I originally recommended Karrigell, but can't any more: since the 3.0 release, it's been continuously broken, and the community is not large enough to solve the problems. CherryPy is a good substitute if you like a light, simple framework that doesn't get in your way, so I've changed the above to suggest it instead.\n",
"Well, if you're thinking of setting up an Ubuntu VM anyway, you might as well make that your development environment. Then you can install Apache and MySQL or Postgres on that VM just via the standard packaging tools (apt-get install), and there's no danger of polluting your Windows environment.\nYou can either do the actual development on your Windows machine via your favourite IDE, using the VM as a networked drive and saving the code there, or you can just use the VM as a full desktop environment and do everything there, which is what I would recommend.\n",
"Install the pre-configured ActivePython release from activestate.\nAmong other features, it includes the PythonWin IDE (Windows only) which makes it easy to explore Python interactively.\nThe recommended reference is Dive Into Python, mentioned many times on similar SO discussions.\n",
"You should install python 2.4, python 2.5, python 2.6 and python 3.0, and add to your path the one you use more often (Add c:\\Pythonxx\\ and c:\\Pythonxx\\Scripts).\nFor every python 2.x, install easy_install; Download ez_setup.py and then from the cmd:\nc:\\Python2x\\python.exe x:\\path\\to\\ez_setup.py\nc:\\Python2x\\Scripts\\easy_install virtualenv\n\nThen each time you start a new project create a new virtual environment to isolate the specific package you needs for your project:\nmkdir <project name>\ncd <project name>\nc:\\Python2x\\Scripts\\virtualenv --no-site-packages .\\v\n\nIt creates a copy of python and its libraries in .v\\Scripts and .\\v\\Lib. Every third party packages you install in that environment will be put into .\\v\\Lib\\site-packages. The -no-site-packages don't give access to the global site package, so you can be sure all your dependencies are in .\\v\\Lib\\site-packages.\nTo activate the virtual environment:\n.\\v\\Scripts\\activate\n\nFor the frameworks, there are many. Django is great and very well documented but you should probably look at Pylons first for its documentions on unicode, packaging, deployment and testing, and for its better WSGI support.\nFor the IDE, Python comes with IDLE which is enough for learning, however you might want to look at Eclipse+PyDev, Komodo or Wingware Python IDE. Netbean 6.5 has beta support for python that looks promising (See top 5 python IDE).\nFor the webserver, you don't need any; Python has its own and all web framework come with their own. You might want to install MySql or ProgreSql; it's often better to develop on the same DB you will use for production.\nAlso, when you have learnt Python, look at Foundations of Agile Python Development or Expert Python Programming.\n",
"\nUsing Python on Windows\nSO: Python tutorial for total beginners?\n\n",
"Take a look at Pylons, read about WSGI and Paste.\nThere's nice introductory Google tech talk about them: ReUsable Web Components with Python and Future Python Web Development.\nHere's my answer to similar question:\nDjango vs other Python web frameworks?\n",
"Environment?\nHere is the simplest solution:\n\nInstall Active Python 2.6. Its the Python itself, but comes with some extra handy useful stuff, like DiveintoPython chm.\nUse Komodo Edit 5. It is among the good free editor you can use for Python.\nUse IDLE. Its the best simplest short snippet editor, with syntax highlighting and auto complete unmatched by most other IDEs. It comes bundled with python.\nUse Ipython. Its a shell that does syntax highlighting and auto complete, bash functions, pretty print, logging, history and many such things.\nInstall easy_install and/or pip for installing various 3rd party apps easily.\n\nComing from Visual Studio and .Net it will sound a lot different, but its an entirely different world.\nFor the framework, django works the best. Walk thro the tutorial and you will be impressed enough. The documentation rocks. The community, you have to see for yourself, to know how wonderful it is!!\n",
"NOTE: I included a lot of links to frameworks, projects and what-not, but as a new user I was limited to 1 link per answer. If someone else with enough reputation to edit wants/can edit them into this answer instead of the footnotes, I'd be grateful.\nThere are some Python IDE's such as Wing IDE[1], I believe some people use Eclipse[2] with a python plugin[3] as well. A lot of people in the #python channel of FreeNode seem to prefer vim, emacs, nano and similar text editors in favor of IDE's. My personal preffered editor is Vim, but if you've mostly done .NET development on windows, presumably with the usual Visual X IDE's, vim and emacs will probably cause you culture shock and you'd be better of using an IDE.\nNearly all python web frameworks* support the WSGI standard[4], most of the large web servers have some sort of plugin to support WSGI, the others support WSGI via fast cgi or plain cgi.\nThe Zope[5] and Django[6] frameworks have their own ORM's, of other ORM's the two most well known appear to be SQL Alchemy[7] and SQL Object[8]. I only have experience with the former, but both support all possible sane database choices, including SQLite which is installed together with Python and hence perfectly suited to testing and experimenting without polluting your .NET environment with 3rd part web servers and database servers.\nThe builtin unittest[9] and pyunit[10] frameworks seem to be the preffered solutions for unit testing, but I don't have much experience with these.\nbpython[11] and ipython[12] offer enhanced interactive python shells which can greatly help speed up and testing small bits of code and hence worth looking in to.\nAs for a list of well known and often used web frameworks, look into the following frameworks**:\n\nTwisted[13] is a generic networking framework, which supports almost every single protocol under the sun.\nPylons[14] is light-weight framework aimed at being as flexible as possible and leaving all the choices about what ORM, templating language and what-not to you.\nCherryPy[15] tries to provide an interface to expose Python objects to the web. \nDjango[6] attempts to be an all-in-one solution, builtin template system, ORM, admin pages and internationalization. While the previous frameworks have more DIY wiring together various frameworks work involved with them.\nZope[5] is aimed to be suitable for large enterprise applications, I've heard nothing but good things about it, but consensus seems to be that for smaller you're probably better off with one of the simpler and smaller frameworks.\nTurboGears[16] is the framework I know the least about, but it seems to be mostly competition for Django.\n\nThis is everything I can think of right now, I'll edit and add stuff if I can think of it. I hope this helps you some in the wonderful world of python.\n\n* - The main exception would be Apache's mod_python, which you should avoid for exactly that reason, use mod_wsgi instead.\n** - Word of warning, I have not personally used these frameworks this is just a very short impression I have gotten from talking to other people about each framework, it may be wildly inaccurate. (If anyone has any corrections, do comment and I'll try to edit and fix this answer).\n(The http:// is missing since they're recognized as links otherwise)\n[1] www.wingware.com/\n[2] www.eclipse.org/\n[3] pydev.sourceforge.net/\n[4] wsgi.org/wsgi/\n[5] www.zope.org/\n[6] www.djangoproject.com/\n[7] www.sqlalchemy.org/\n[8] www.sqlobject.org/\n[9] docs.python.org/library/unittest.html\n[10] pyunit.sourceforge.net/pyunit.html\n[11] www.bpython-interpreter.org/\n[12] ipython.scipy.org/\n[13] twistedmatrix.com/trac/\n[14] pylonshq.com/\n[15] www.cherrypy.org/\n[16] turbogears.org/\n",
"Python has build in SQL like database and web server, so you wouldn't need to install any third party apps. Remember Python comes with batteries included.\n",
"If you've worked with Eclipse before you could give Pydev a try\n"
] |
[
5,
3,
3,
3,
2,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"development_environment",
"python",
"windows"
] |
stackoverflow_0000959479_development_environment_python_windows.txt
|
Q:
Finding PI digits using Monte Carlo
I have tried many algorithms for finding π using Monte Carlo.
One of the solutions (in Python) is this:
def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2: PI result", 4.0 * float(hits) / n_points
The sad part is that even with 1000000000 the precision is VERY bad (3.141...).
Is this the maximum precision this method can offer?
The reason I choose Monte Carlo was that it's very easy to break it in parallel parts.
Is there another algorithm for π that is easy to break into pieces and calculate?
A:
This is a classic example of Monte Carlo. But if you're trying to break the calculation of pi into parallel parts, why not just use an infinite series and let each core take a range, then sum the results as you go?
http://mathworld.wolfram.com/PiFormulas.html
A:
Your fractional error goes by sqrt(N)/N = 1/sqrt(N), So this is a very inefficient way to get a precise estimate. This limit is set by the statistical nature of the measurement and can't be beaten.
You should be able to get about floor(log_10(N))/2-1 digits of good precision for N throws. Maybe -2 just to be safe...
Even at that it assumes that you are using a real RNG or a good enough PRNG.
A:
Use a quasi random number generator (http://www.nag.co.uk/IndustryArticles/introduction_to_quasi_random_numbers.pdf) instead of a standard pseudo RNG. Quasi random numbers cover the integration area (what you're doing is a MC integration) more evenly than pseudo random numbers, giving better convergence.
|
Finding PI digits using Monte Carlo
|
I have tried many algorithms for finding π using Monte Carlo.
One of the solutions (in Python) is this:
def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2: PI result", 4.0 * float(hits) / n_points
The sad part is that even with 1000000000 the precision is VERY bad (3.141...).
Is this the maximum precision this method can offer?
The reason I choose Monte Carlo was that it's very easy to break it in parallel parts.
Is there another algorithm for π that is easy to break into pieces and calculate?
|
[
"This is a classic example of Monte Carlo. But if you're trying to break the calculation of pi into parallel parts, why not just use an infinite series and let each core take a range, then sum the results as you go?\nhttp://mathworld.wolfram.com/PiFormulas.html\n",
"Your fractional error goes by sqrt(N)/N = 1/sqrt(N), So this is a very inefficient way to get a precise estimate. This limit is set by the statistical nature of the measurement and can't be beaten.\nYou should be able to get about floor(log_10(N))/2-1 digits of good precision for N throws. Maybe -2 just to be safe...\nEven at that it assumes that you are using a real RNG or a good enough PRNG.\n",
"Use a quasi random number generator (http://www.nag.co.uk/IndustryArticles/introduction_to_quasi_random_numbers.pdf) instead of a standard pseudo RNG. Quasi random numbers cover the integration area (what you're doing is a MC integration) more evenly than pseudo random numbers, giving better convergence.\n"
] |
[
14,
8,
4
] |
[] |
[] |
[
"montecarlo",
"pi",
"python",
"statistics"
] |
stackoverflow_0000982381_montecarlo_pi_python_statistics.txt
|
Q:
Page isn't always rendered
In Google App Engine, I have the following code which shows a simple HTML page.
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
class IndexHandler(webapp.RequestHandler):
def get(self):
template_values = { }
path = os.path.join(os.path.dirname(__file__), '../templates/index.html')
self.response.out.write(template.render(path, template_values))
The issue is that the page isn't always rendered. The index.html is a simple "Hello World!". After a couple of page refresh the page is displayed properly (i.e. the index.html file is found...). I tried to call flush at the end, but it didn't help. I am able to repro this with the SDK and on their server.
Am I missing something? Does someone have an idea of what is going on?
Thanks
A:
Your handler script (the one referenced by app.yaml) has a main() function, but needs this stanza at the end:
if __name__ == '__main__':
main()
What's happening is that the first time your script is run in a given interpreter, it interprets your main script, which does nothing (thus returning a blank response). On subsequent invocations, the interpreter simply executes your main() (a documented optimization), which generates the page as expected. Adding the stanza above will cause it to execute main on initial import, too.
A:
Can't reproduce -- with directory changed to ./templates (don't have a ../templates in my setup), and the usual main function added, and this script assigned in app.yaml to some arbitrary URL, it serves successfully "Hello World" every time. Guess we need more info to help -- log entries (maybe add logging.info calls here?), app.yaml, where's main, etc, etc...
|
Page isn't always rendered
|
In Google App Engine, I have the following code which shows a simple HTML page.
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
class IndexHandler(webapp.RequestHandler):
def get(self):
template_values = { }
path = os.path.join(os.path.dirname(__file__), '../templates/index.html')
self.response.out.write(template.render(path, template_values))
The issue is that the page isn't always rendered. The index.html is a simple "Hello World!". After a couple of page refresh the page is displayed properly (i.e. the index.html file is found...). I tried to call flush at the end, but it didn't help. I am able to repro this with the SDK and on their server.
Am I missing something? Does someone have an idea of what is going on?
Thanks
|
[
"Your handler script (the one referenced by app.yaml) has a main() function, but needs this stanza at the end:\nif __name__ == '__main__':\n main()\n\nWhat's happening is that the first time your script is run in a given interpreter, it interprets your main script, which does nothing (thus returning a blank response). On subsequent invocations, the interpreter simply executes your main() (a documented optimization), which generates the page as expected. Adding the stanza above will cause it to execute main on initial import, too.\n",
"Can't reproduce -- with directory changed to ./templates (don't have a ../templates in my setup), and the usual main function added, and this script assigned in app.yaml to some arbitrary URL, it serves successfully \"Hello World\" every time. Guess we need more info to help -- log entries (maybe add logging.info calls here?), app.yaml, where's main, etc, etc...\n"
] |
[
3,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0000985017_google_app_engine_python.txt
|
Q:
Python shortcuts
Python is filled with little neat shortcuts.
For example:
self.data = map(lambda x: list(x), data)
and (although not so pretty)
tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
among countless others.
In the irc channel, they said "too many to know them all".
I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.
A:
self.data = map(lambda x: list(x), data)
is dreck -- use
self.data = map(list, data)
if you're a map fanatic (list comprehensions are generally preferred these days). More generally, lambda x: somecallable(x) can always be productively changed to just somecallable, in every context, with nothing but good effect.
As for shortcuts in general, my wife and I did our best to list the most important and useful one in the early part of the Python Cookbook's second edition -- could be a start.
A:
Alex Martelli provided an even shorter version of your first example. I shall provide a (slightly) shorter version of your second:
tuple(t[0] for t in self.result if t[0] not in ('mysql', 'information_schema'))
Obviously the in operator becomes more advantageous the more values you're testing for.
I would also like to stress that shortening and refactoring is good only to the extent that it improves clarity and readability. (Unless you are code-golfing. ;)
A:
I'm not sure if this is a shortcut, but I love it:
>>> class Enum(object):
def __init__(self, *keys):
self.keys = keys
self.__dict__.update(zip(keys, range(len(keys))))
def value(self, key):
return self.keys.index(key)
>>> colors = Enum("Red", "Blue", "Green", "Yellow", "Purple")
>>> colors.keys
('Red', 'Blue', 'Green', 'Yellow', 'Purple')
>>> colors.Green
2
(I don't know who came up with this, but it wasn't me.)
A:
I always liked the "unzip" idiom:
>>> zipped = [('a', 1), ('b', 2), ('c', 3)]
>>> zip(*zipped)
[('a', 'b', 'c'), (1, 2, 3)]
>>>
>>> l,n = zip(*zipped)
>>> l
('a', 'b', 'c')
>>> n
(1, 2, 3)
|
Python shortcuts
|
Python is filled with little neat shortcuts.
For example:
self.data = map(lambda x: list(x), data)
and (although not so pretty)
tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
among countless others.
In the irc channel, they said "too many to know them all".
I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.
|
[
"self.data = map(lambda x: list(x), data)\n\nis dreck -- use\nself.data = map(list, data)\n\nif you're a map fanatic (list comprehensions are generally preferred these days). More generally, lambda x: somecallable(x) can always be productively changed to just somecallable, in every context, with nothing but good effect.\nAs for shortcuts in general, my wife and I did our best to list the most important and useful one in the early part of the Python Cookbook's second edition -- could be a start.\n",
"Alex Martelli provided an even shorter version of your first example. I shall provide a (slightly) shorter version of your second:\ntuple(t[0] for t in self.result if t[0] not in ('mysql', 'information_schema'))\n\nObviously the in operator becomes more advantageous the more values you're testing for.\nI would also like to stress that shortening and refactoring is good only to the extent that it improves clarity and readability. (Unless you are code-golfing. ;)\n",
"I'm not sure if this is a shortcut, but I love it:\n>>> class Enum(object):\n def __init__(self, *keys):\n self.keys = keys\n self.__dict__.update(zip(keys, range(len(keys))))\n def value(self, key):\n return self.keys.index(key) \n\n>>> colors = Enum(\"Red\", \"Blue\", \"Green\", \"Yellow\", \"Purple\")\n>>> colors.keys\n('Red', 'Blue', 'Green', 'Yellow', 'Purple')\n>>> colors.Green\n2\n\n(I don't know who came up with this, but it wasn't me.)\n",
"I always liked the \"unzip\" idiom:\n>>> zipped = [('a', 1), ('b', 2), ('c', 3)]\n>>> zip(*zipped)\n[('a', 'b', 'c'), (1, 2, 3)]\n>>> \n>>> l,n = zip(*zipped)\n>>> l\n('a', 'b', 'c')\n>>> n\n(1, 2, 3)\n\n"
] |
[
11,
3,
3,
1
] |
[] |
[] |
[
"python",
"refactoring",
"shortcut"
] |
stackoverflow_0000985026_python_refactoring_shortcut.txt
|
Q:
Stomp Broadcast with Rabbitmq and Python
Im trying to move a system from using morbid to rabbitmq, but I cannot seem to get the same broadcast behaviour morbid supplied by default. By broadcast I mean that when a message is added to the queue, every consumer recieves it. With rabbit, when a message is added they are distributed round robin style to every listener.
Can anyone tell me how to achieve the same kind of message distribution?
The stomp library used below is http://code.google.com/p/stomppy/
Failing being able to do with with stomp, even a amqplib example would really help.
My code at present looks like this
The Consumer
import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demoqueue', ack='auto')
while True:
pass
conn.disconnect()
And the sender looks like this
import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demotopic', ack='auto')
while True:
pass
conn.disconnect()
A:
Apparently you can't do with directly with STOMP; there is a mailing list thread that shows all the hoops you have to jump through to get broadcast working with stomp (it involves some lower-level AMPQ stuff).
A:
I finally figured out how to do it by creating an exchange for each "recieving group", im not sure how well rabbit will do with thousands of exchanges, so you might want to figure test this heavily before trying it in production
In the sending code:
conn.send(str(i), exchange=exchange, destination='')
The blank destination is required, all I care about is sending to that exchange
To recieve
import stomp
import sys
from amqplib import client_0_8 as amqp
#read in the exchange name so I can set up multiple recievers for different exchanges to tset
exchange = sys.argv[1]
conn = amqp.Connection(host="localhost:5672", userid="username", password="password",
virtual_host="/", insist=False)
chan = conn.channel()
chan.access_request('/', active=True, write=True, read=True)
#declare my exchange
chan.exchange_declare(exchange, 'topic')
#not passing a queue name means I get a new unique one back
qname,_,_ = chan.queue_declare()
#bind the queue to the exchange
chan.queue_bind(qname, exchange=exchange)
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'browser', 'browser')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="username", password="password")
headers = {}
#subscribe to the queue
conn.subscribe(destination=qname, ack='auto')
while True:
pass
conn.disconnect()
|
Stomp Broadcast with Rabbitmq and Python
|
Im trying to move a system from using morbid to rabbitmq, but I cannot seem to get the same broadcast behaviour morbid supplied by default. By broadcast I mean that when a message is added to the queue, every consumer recieves it. With rabbit, when a message is added they are distributed round robin style to every listener.
Can anyone tell me how to achieve the same kind of message distribution?
The stomp library used below is http://code.google.com/p/stomppy/
Failing being able to do with with stomp, even a amqplib example would really help.
My code at present looks like this
The Consumer
import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demoqueue', ack='auto')
while True:
pass
conn.disconnect()
And the sender looks like this
import stomp
class MyListener(object):
def on_error(self, headers, message):
print 'recieved an error %s' % message
def on_message(self, headers, message):
print 'recieved a message %s' % message
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'user', 'password')
conn.set_listener('', MyListener())
conn.start()
conn.connect(username="user", password="password")
headers = {}
conn.subscribe(destination='/topic/demotopic', ack='auto')
while True:
pass
conn.disconnect()
|
[
"Apparently you can't do with directly with STOMP; there is a mailing list thread that shows all the hoops you have to jump through to get broadcast working with stomp (it involves some lower-level AMPQ stuff).\n",
"I finally figured out how to do it by creating an exchange for each \"recieving group\", im not sure how well rabbit will do with thousands of exchanges, so you might want to figure test this heavily before trying it in production\nIn the sending code:\nconn.send(str(i), exchange=exchange, destination='')\n\nThe blank destination is required, all I care about is sending to that exchange\nTo recieve\nimport stomp\nimport sys\nfrom amqplib import client_0_8 as amqp\n#read in the exchange name so I can set up multiple recievers for different exchanges to tset\nexchange = sys.argv[1]\nconn = amqp.Connection(host=\"localhost:5672\", userid=\"username\", password=\"password\",\n virtual_host=\"/\", insist=False)\n\nchan = conn.channel()\n\nchan.access_request('/', active=True, write=True, read=True)\n\n#declare my exchange\nchan.exchange_declare(exchange, 'topic')\n#not passing a queue name means I get a new unique one back\nqname,_,_ = chan.queue_declare()\n#bind the queue to the exchange\nchan.queue_bind(qname, exchange=exchange)\n\nclass MyListener(object):\n def on_error(self, headers, message):\n print 'recieved an error %s' % message\n\n def on_message(self, headers, message):\n print 'recieved a message %s' % message\n\nconn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'browser', 'browser')\nconn.set_listener('', MyListener())\nconn.start()\nconn.connect(username=\"username\", password=\"password\")\nheaders = {}\n\n#subscribe to the queue\nconn.subscribe(destination=qname, ack='auto')\n\nwhile True:\n pass\nconn.disconnect()\n\n"
] |
[
3,
3
] |
[] |
[] |
[
"broadcast",
"python",
"rabbitmq",
"stomp"
] |
stackoverflow_0000981291_broadcast_python_rabbitmq_stomp.txt
|
Q:
How to make a singleton class with Python Flup fastcgi server?
I use flup as fastcgi server for Django.
Please explain to me how can I use singleton?
I'm not sure I understand threading models for Flup well.
A:
If you use a forked server, you will not be able to have a singleton at all (at least no singleton that lifes longer than your actual context).
With a threaded server, it should be possibe (but I am not so much in Django and Web servers!).
Have you tried such a code (as an additional module):
# Singleton module
_my_singleton = None
def getSingleton():
if _my_singleton == None:
_my_singleton = ...
return _my_singleton
At the tree dots ("...") you have to add coding to create your singleton object, of course.
This is no productive code yet, but you can use it to check if singletons will work at all with your framework. For singletons are only possible with some kind of "global storage" at hand. Forked servers make this more difficult.
In the case, that "normal global storage" does not work, there is a different possibility available. You could store your singleton on the file system, using Pythons serialization facilites. But of course, this would be much more overhead in deed!
|
How to make a singleton class with Python Flup fastcgi server?
|
I use flup as fastcgi server for Django.
Please explain to me how can I use singleton?
I'm not sure I understand threading models for Flup well.
|
[
"If you use a forked server, you will not be able to have a singleton at all (at least no singleton that lifes longer than your actual context).\nWith a threaded server, it should be possibe (but I am not so much in Django and Web servers!).\nHave you tried such a code (as an additional module):\n# Singleton module\n_my_singleton = None\n\ndef getSingleton():\n if _my_singleton == None:\n _my_singleton = ...\n return _my_singleton\n\nAt the tree dots (\"...\") you have to add coding to create your singleton object, of course.\nThis is no productive code yet, but you can use it to check if singletons will work at all with your framework. For singletons are only possible with some kind of \"global storage\" at hand. Forked servers make this more difficult.\nIn the case, that \"normal global storage\" does not work, there is a different possibility available. You could store your singleton on the file system, using Pythons serialization facilites. But of course, this would be much more overhead in deed!\n"
] |
[
0
] |
[] |
[] |
[
"django",
"flup",
"python"
] |
stackoverflow_0000650518_django_flup_python.txt
|
Q:
Python thread exit code
Is there a way to tell if a thread has exited normally or because of an exception?
A:
As mentioned, a wrapper around the Thread class could catch that state. Here's an example.
>>> from threading import Thread
>>> class MyThread(Thread):
def run(self):
try:
Thread.run(self)
except Exception as err:
self.err = err
pass # or raise err
else:
self.err = None
>>> mt = MyThread(target=divmod, args=(3, 2))
>>> mt.start()
>>> mt.join()
>>> mt.err
>>> mt = MyThread(target=divmod, args=(3, 0))
>>> mt.start()
>>> mt.join()
>>> mt.err
ZeroDivisionError('integer division or modulo by zero',)
A:
You could set some global variable to 0 if success, or non-zero if there was an exception. This is a pretty standard convention.
However, you'll need to protect this variable with a mutex or semaphore. Or you could make sure that only one thread will ever write to it and all others would just read it.
A:
Have your thread function catch exceptions. (You can do this with a simple wrapper function that just calls the old thread function inside a try...except or try...except...else block). Then the question just becomes "how to pass information from one thread to another", and I guess you already know how to do that.
|
Python thread exit code
|
Is there a way to tell if a thread has exited normally or because of an exception?
|
[
"As mentioned, a wrapper around the Thread class could catch that state. Here's an example.\n>>> from threading import Thread\n>>> class MyThread(Thread):\n def run(self):\n try:\n Thread.run(self)\n except Exception as err:\n self.err = err\n pass # or raise err\n else:\n self.err = None\n\n\n>>> mt = MyThread(target=divmod, args=(3, 2))\n>>> mt.start()\n>>> mt.join()\n>>> mt.err\n>>> mt = MyThread(target=divmod, args=(3, 0))\n>>> mt.start()\n>>> mt.join()\n>>> mt.err\nZeroDivisionError('integer division or modulo by zero',)\n\n",
"You could set some global variable to 0 if success, or non-zero if there was an exception. This is a pretty standard convention.\nHowever, you'll need to protect this variable with a mutex or semaphore. Or you could make sure that only one thread will ever write to it and all others would just read it.\n",
"Have your thread function catch exceptions. (You can do this with a simple wrapper function that just calls the old thread function inside a try...except or try...except...else block). Then the question just becomes \"how to pass information from one thread to another\", and I guess you already know how to do that.\n"
] |
[
20,
0,
0
] |
[] |
[] |
[
"exit_code",
"multithreading",
"python"
] |
stackoverflow_0000986616_exit_code_multithreading_python.txt
|
Q:
adding a **kwarg to a class
class StatusForm(ModelForm):
bases = forms.ModelMultipleChoiceField(
queryset=Base.objects.all(), #this should get overwritten
widget=forms.SelectMultiple,
)
class Meta:
model = HiringStatus
exclude = ('company', 'date')
def __init__(self, *args, **kwargs):
super(StatusForm, self).__init__(*args, **kwargs)
if kwargs.has_key('bases_queryset'):
self.fields['bases'].queryset = kwargs['bases_queryset']
I want to add an option to this form that allows me to create a form like so:
form = StatusForm(bases_queryset=Base.objects.filter([...])
But I somehow need to "add" that keyword argument to the class so it will be recognized. They way it is now, I just get this error:
__init__() got an unexpected keyword argument 'bases_queryset'
A:
That's because you're unpacking kwargs to the super constructor.
Try to put this before calling super:
if kwargs.has_key('bases_queryset'):
bases_queryset = kwargs['bases_queryset']
del kwargs['bases_queryset']
but it's not an ideal solution...
A:
As @Keeper indicates, you must not pass your "new" keyword arguments to the superclass. Best may be to do, before you call super's __init__:
bqs = kwargs.pop('bases_queryset', None)
and after that __init__ call, check if bqs is not None: instead of using has_key (and use bqs instead of kwargs['bases_queryset'], of course).
An interesting alternative approach is to make a "selective call" higher-order function. It's a bit of a mess if you have both positional and named arguments (that's always a bit messy to metaprogram around;-), so for simplicity of exposition assume the function you want to selectively call only has "normal" named arguments (i.e. no **k either). Now:
import inspect
def selective_call(func, **kwargs):
names, _, _, _ = inspect.getargspec(func)
usable_kwargs = dict((k,kwargs[k]) for k in names if k in kwargs)
return func(**usable_kwargs)
with this approach, in your __init__, instead of calling super's __init__ directly, you'd call
selective_call(super_init, **kwargs) and let this higher-order function do the needed "pruning". (Of course, you will need to make it messier to handle both positional and named args, ah well...!-)
|
adding a **kwarg to a class
|
class StatusForm(ModelForm):
bases = forms.ModelMultipleChoiceField(
queryset=Base.objects.all(), #this should get overwritten
widget=forms.SelectMultiple,
)
class Meta:
model = HiringStatus
exclude = ('company', 'date')
def __init__(self, *args, **kwargs):
super(StatusForm, self).__init__(*args, **kwargs)
if kwargs.has_key('bases_queryset'):
self.fields['bases'].queryset = kwargs['bases_queryset']
I want to add an option to this form that allows me to create a form like so:
form = StatusForm(bases_queryset=Base.objects.filter([...])
But I somehow need to "add" that keyword argument to the class so it will be recognized. They way it is now, I just get this error:
__init__() got an unexpected keyword argument 'bases_queryset'
|
[
"That's because you're unpacking kwargs to the super constructor.\nTry to put this before calling super:\nif kwargs.has_key('bases_queryset'):\n bases_queryset = kwargs['bases_queryset']\n del kwargs['bases_queryset']\n\nbut it's not an ideal solution...\n",
"As @Keeper indicates, you must not pass your \"new\" keyword arguments to the superclass. Best may be to do, before you call super's __init__:\nbqs = kwargs.pop('bases_queryset', None)\n\nand after that __init__ call, check if bqs is not None: instead of using has_key (and use bqs instead of kwargs['bases_queryset'], of course).\nAn interesting alternative approach is to make a \"selective call\" higher-order function. It's a bit of a mess if you have both positional and named arguments (that's always a bit messy to metaprogram around;-), so for simplicity of exposition assume the function you want to selectively call only has \"normal\" named arguments (i.e. no **k either). Now:\nimport inspect\n\ndef selective_call(func, **kwargs):\n names, _, _, _ = inspect.getargspec(func)\n usable_kwargs = dict((k,kwargs[k]) for k in names if k in kwargs)\n return func(**usable_kwargs)\n\nwith this approach, in your __init__, instead of calling super's __init__ directly, you'd call\nselective_call(super_init, **kwargs) and let this higher-order function do the needed \"pruning\". (Of course, you will need to make it messier to handle both positional and named args, ah well...!-)\n"
] |
[
11,
11
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0000987237_django_python.txt
|
Q:
Django : Timestamp string custom field
I'm trying to create a custom timestamp field.
class TimestampKey(models.CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
import time
kwargs['unique'] = True
kwargs['max_length'] = 20
kwargs['auto_created'] = True
kwargs['editable']=False
super(TimestampKey, self).__init__(*args, **kwargs)
def to_python(self, value) :
return value
def get_db_prep_value(self, value) :
try:
import time
t = time.localtime()
value = reduce(lambda a,b:str(a)+str(b),t)
except ValueError:
value = {}
return value
class Table1(models.Model):
f = TimestampKey(primary_key=True)
n = ....
It stores the value with appropriate timestamp in the db. But it doesnt populate the field 'f' in the object.
Eg:
t1 = Table1(n="some value")
t1.f -> blank
t1.save()
t1.f -> blank.
This is the problem. Am I missing something so that it doesnt populate the filed?
Please shed some light on this.
Thanks.
A:
Is it wise to use a timestamp as your primary key? If your database uses ISO 8601 or really any time format in which second is the smallest time interval... Well, anyway, my point is that you have no guarantee, especially if this is going to be a web-facing application that two entries are going to resolve within the minimum time interval. That is, if the smallest time interval is a second, as in ISO 8601, if you get two requests to save in the same second, you're going to get an error condition. Why not stick to automatically incrementing integer keys and just make the timestamp its own field?
A:
The get_db_prep_value method only prepares a value for the database, but doesn't send the prepared value back to the Python object in any way. For that you would need the pre_save method, I think.
Fortunately, there's already an "auto_now" option on DateField and DateTimeField that does what you want, using pre_save. Try:
class Table1(models.Model):
f = models.DateTimeField(auto_now=True)
(If you must write your own pre_save, look at how auto_now modifies the actual model instance in /django/db/models/fields/__init__.py on lines 486-492:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.datetime.now()
setattr(model_instance, self.attname, value)
return value
else:
return super(DateField, self).pre_save(model_instance, add)
)
|
Django : Timestamp string custom field
|
I'm trying to create a custom timestamp field.
class TimestampKey(models.CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
import time
kwargs['unique'] = True
kwargs['max_length'] = 20
kwargs['auto_created'] = True
kwargs['editable']=False
super(TimestampKey, self).__init__(*args, **kwargs)
def to_python(self, value) :
return value
def get_db_prep_value(self, value) :
try:
import time
t = time.localtime()
value = reduce(lambda a,b:str(a)+str(b),t)
except ValueError:
value = {}
return value
class Table1(models.Model):
f = TimestampKey(primary_key=True)
n = ....
It stores the value with appropriate timestamp in the db. But it doesnt populate the field 'f' in the object.
Eg:
t1 = Table1(n="some value")
t1.f -> blank
t1.save()
t1.f -> blank.
This is the problem. Am I missing something so that it doesnt populate the filed?
Please shed some light on this.
Thanks.
|
[
"Is it wise to use a timestamp as your primary key? If your database uses ISO 8601 or really any time format in which second is the smallest time interval... Well, anyway, my point is that you have no guarantee, especially if this is going to be a web-facing application that two entries are going to resolve within the minimum time interval. That is, if the smallest time interval is a second, as in ISO 8601, if you get two requests to save in the same second, you're going to get an error condition. Why not stick to automatically incrementing integer keys and just make the timestamp its own field?\n",
"The get_db_prep_value method only prepares a value for the database, but doesn't send the prepared value back to the Python object in any way. For that you would need the pre_save method, I think.\nFortunately, there's already an \"auto_now\" option on DateField and DateTimeField that does what you want, using pre_save. Try:\nclass Table1(models.Model):\n f = models.DateTimeField(auto_now=True)\n\n(If you must write your own pre_save, look at how auto_now modifies the actual model instance in /django/db/models/fields/__init__.py on lines 486-492:\ndef pre_save(self, model_instance, add):\n if self.auto_now or (self.auto_now_add and add):\n value = datetime.datetime.now()\n setattr(model_instance, self.attname, value)\n return value\n else:\n return super(DateField, self).pre_save(model_instance, add)\n\n)\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0000984460_django_django_models_python.txt
|
Q:
How do I get a value node moved up to be an attribute of its parent node?
What do I need to change so the Name node under FieldRef is an attribute of FieldRef, and not a child node?
Suds currently generates the following soap:
<ns0:query>
<ns0:Where>
<ns0:Eq>
<ns0:FieldRef>
<ns0:Name>_ows_ID</ns0:Name>
</ns0:FieldRef>
<ns0:Value>66</ns0:Value>
</ns0:Eq>
</ns0:Where>
</ns0:query>
What I need is this:
<ns0:query>
<ns0:Where>
<ns0:Eq>
<ns0:FieldRef Name="_ows_ID">
</ns0:FieldRef>
<ns0:Value>66</ns0:Value>
</ns0:Eq>
</ns0:Where>
</ns0:query>
The first xml structure is generated by suds from the below code.
q = c.factory.create('GetListItems.query')
q['Where']=InstFactory.object('Where')
q['Where']['Eq']=InstFactory.object('Eq')
q['Where']['Eq']['FieldRef']=InstFactory.object('FieldRef')
q['Where']['Eq']['FieldRef'].Name='_ows_ID'
q['Where']['Eq']['Value']='66'
and print(q) results in
(query){
Where =
(Where){
Eq =
(Eq){
FieldRef =
(FieldRef){
Name = "_ows_ID"
}
Value = "66"
}
}
}
Here's the code that makes the WS call that creates the soap request
c = client.Client(url='https://community.site.edu/_vti_bin/Lists.asmx?WSDL',
transport=WindowsHttpAuthenticated(username='domain\user',
password='password')
)
ll= c.service.GetListItems(listName="{BD59F6D9-AB4B-474D-BCC7-E4B4BEA7EB27}",
viewName="{407A6AB9-97CF-4E1F-8544-7DD67CEA997B}",
query=q
)
A:
from suds.sax.element import Element
#create the nodes
q = Element('query')
where=Element('Where')
eq=Element('Eq')
fieldref=Element('FieldRef')
fieldref.set('Name', '_ows_ID')
value=Element('Value')
value.setText('66')
#append them
eq.append(fieldref)
eq.append(value)
where.append(eq)
q.append(where)
https://fedorahosted.org/suds/wiki/TipsAndTricks
Including Literal XML
To include literal (not escaped) XML
as a parameter value of object
attribute, you need to set the value
of the parameter of the object
attribute to be a sax Element. The
marshaller is designed to simply
attach and append content that is
already XML.
For example, you want to pass the
following XML as a parameter:
<query> <name>Elmer Fudd</name>
<age unit="years">33</age>
<job>Wabbit Hunter</job> </query>
The can be done as follows:
from suds.sax.element import Element
query = Element('query')
name = Element('name').setText('Elmer Fudd')
age = Element('age').setText('33')
age.set('units', 'years')
job = Element('job').setText('Wabbit Hunter')
query.append(name)
query.append(age)
query.append(job)
client.service.runQuery(query)
|
How do I get a value node moved up to be an attribute of its parent node?
|
What do I need to change so the Name node under FieldRef is an attribute of FieldRef, and not a child node?
Suds currently generates the following soap:
<ns0:query>
<ns0:Where>
<ns0:Eq>
<ns0:FieldRef>
<ns0:Name>_ows_ID</ns0:Name>
</ns0:FieldRef>
<ns0:Value>66</ns0:Value>
</ns0:Eq>
</ns0:Where>
</ns0:query>
What I need is this:
<ns0:query>
<ns0:Where>
<ns0:Eq>
<ns0:FieldRef Name="_ows_ID">
</ns0:FieldRef>
<ns0:Value>66</ns0:Value>
</ns0:Eq>
</ns0:Where>
</ns0:query>
The first xml structure is generated by suds from the below code.
q = c.factory.create('GetListItems.query')
q['Where']=InstFactory.object('Where')
q['Where']['Eq']=InstFactory.object('Eq')
q['Where']['Eq']['FieldRef']=InstFactory.object('FieldRef')
q['Where']['Eq']['FieldRef'].Name='_ows_ID'
q['Where']['Eq']['Value']='66'
and print(q) results in
(query){
Where =
(Where){
Eq =
(Eq){
FieldRef =
(FieldRef){
Name = "_ows_ID"
}
Value = "66"
}
}
}
Here's the code that makes the WS call that creates the soap request
c = client.Client(url='https://community.site.edu/_vti_bin/Lists.asmx?WSDL',
transport=WindowsHttpAuthenticated(username='domain\user',
password='password')
)
ll= c.service.GetListItems(listName="{BD59F6D9-AB4B-474D-BCC7-E4B4BEA7EB27}",
viewName="{407A6AB9-97CF-4E1F-8544-7DD67CEA997B}",
query=q
)
|
[
"from suds.sax.element import Element\n#create the nodes\nq = Element('query')\nwhere=Element('Where')\neq=Element('Eq')\nfieldref=Element('FieldRef')\nfieldref.set('Name', '_ows_ID')\nvalue=Element('Value')\nvalue.setText('66')\n\n#append them\neq.append(fieldref)\neq.append(value)\nwhere.append(eq)\nq.append(where)\n\nhttps://fedorahosted.org/suds/wiki/TipsAndTricks\n\nIncluding Literal XML\nTo include literal (not escaped) XML\n as a parameter value of object\n attribute, you need to set the value\n of the parameter of the object\n attribute to be a sax Element. The\n marshaller is designed to simply\n attach and append content that is\n already XML.\nFor example, you want to pass the\n following XML as a parameter:\n<query> <name>Elmer Fudd</name>\n<age unit=\"years\">33</age>\n<job>Wabbit Hunter</job> </query>\nThe can be done as follows:\nfrom suds.sax.element import Element\nquery = Element('query')\nname = Element('name').setText('Elmer Fudd')\nage = Element('age').setText('33')\nage.set('units', 'years')\njob = Element('job').setText('Wabbit Hunter')\nquery.append(name)\nquery.append(age)\nquery.append(job)\nclient.service.runQuery(query)\n\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"soap",
"suds"
] |
stackoverflow_0000986925_python_soap_suds.txt
|
Q:
One stop resource for : Will it play in App Engine/Python?
Information on frameworks, languages, and libraries for GAE/J is maintained at
: http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine
Is there a similar page for GAE/Py?
A:
From http://code.google.com/appengine/docs/python/overview.html
The Python runtime environment uses Python 2.5.2.
All code for the Python runtime environment must be pure Python, and not include any C extensions or other code that must be compiled.
The environment includes the Python standard library. Some modules have been disabled because their core functions are not supported by App Engine, such as networking or writing to the filesystem. In addition, the os module is available, but with unsupported features disabled. An attempt to import an unsupported module or use an unsupported feature will raise an exception.
A few modules from the standard library have been replaced or customized to work with App Engine. For example:
* cPickle is aliased to pickle. Features specific to cPickle are not supported.
* marshal is empty. An import will succeed, but using it will not.
* These modules are similarly empty: imp, ftplib, select, socket
* tempfile is disabled, except for TemporaryFile which is aliased to StringIO.
* logging is available and its use is highly encouraged! See below.
In addition to the Python standard library and the App Engine libraries, the runtime environment includes the following third-party libraries:
* Django 0.96.1
* WebOb 0.9
* PyYAML 3.05
You can include other pure Python libraries with your application by putting the code in your application directory. If you make a symbolic link to a module's directory in your application directory, appcfg.py will follow the link and include the module in your app.
The Python module include path includes your application's root directory (the directory containing the app.yaml file). Modules you create in your application's root directory are available using a path from the root. Don't forget to create init.py files in sub-directories, so Python will recognize the sub-directories as packages.
|
One stop resource for : Will it play in App Engine/Python?
|
Information on frameworks, languages, and libraries for GAE/J is maintained at
: http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine
Is there a similar page for GAE/Py?
|
[
"From http://code.google.com/appengine/docs/python/overview.html\nThe Python runtime environment uses Python 2.5.2.\nAll code for the Python runtime environment must be pure Python, and not include any C extensions or other code that must be compiled.\nThe environment includes the Python standard library. Some modules have been disabled because their core functions are not supported by App Engine, such as networking or writing to the filesystem. In addition, the os module is available, but with unsupported features disabled. An attempt to import an unsupported module or use an unsupported feature will raise an exception.\nA few modules from the standard library have been replaced or customized to work with App Engine. For example:\n* cPickle is aliased to pickle. Features specific to cPickle are not supported.\n* marshal is empty. An import will succeed, but using it will not.\n* These modules are similarly empty: imp, ftplib, select, socket\n* tempfile is disabled, except for TemporaryFile which is aliased to StringIO.\n* logging is available and its use is highly encouraged! See below.\n\nIn addition to the Python standard library and the App Engine libraries, the runtime environment includes the following third-party libraries:\n* Django 0.96.1\n* WebOb 0.9\n* PyYAML 3.05\n\nYou can include other pure Python libraries with your application by putting the code in your application directory. If you make a symbolic link to a module's directory in your application directory, appcfg.py will follow the link and include the module in your app.\nThe Python module include path includes your application's root directory (the directory containing the app.yaml file). Modules you create in your application's root directory are available using a path from the root. Don't forget to create init.py files in sub-directories, so Python will recognize the sub-directories as packages.\n"
] |
[
4
] |
[] |
[] |
[
"frameworks",
"google_app_engine",
"python"
] |
stackoverflow_0000986516_frameworks_google_app_engine_python.txt
|
Q:
How can I change a user agent string programmatically?
I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server.
How can I do this in Python?
A:
Why not use an existing proxy such as Charles HTTP Proxy? It has the ability to rewrite headers and do all sorts of cool stuff to requests and responses.
A:
This is a list of HTTP proxies in python.
|
How can I change a user agent string programmatically?
|
I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server.
How can I do this in Python?
|
[
"Why not use an existing proxy such as Charles HTTP Proxy? It has the ability to rewrite headers and do all sorts of cool stuff to requests and responses.\n",
"This is a list of HTTP proxies in python.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000987802_python.txt
|
Q:
orbited twisted installation problems
i am geting folloing error when i am trying to start orbited server
C:\Python26\Scripts>orbited
Traceback (most recent call last):
File "C:\Python26\Scripts\orbited-script.py", line 8, in <module>
load_entry_point('orbited==0.7.9', 'console_scripts', 'orbited')()
File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\start.py",
line 84, in main
install = _import('twisted.internet.%sreactor.install' % reactor_name)
File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\start.py",
line 13, in _import
return reduce(getattr, name.split('.')[1:], __import__(module_import))
File "C:\Python26\lib\site-packages\twisted\internet\selectreactor.py", line 2
1, in <module>
from twisted.internet import posixbase
File "C:\Python26\lib\site-packages\twisted\internet\posixbase.py", line 25, i
n <module>
from twisted.internet import tcp, udp
File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 78, in <mod
ule>
from twisted.internet import defer, base, address
File "C:\Python26\lib\site-packages\twisted\internet\defer.py", line 17, in <m
odule>
from twisted.python import log, failure, lockfile
File "C:\Python26\lib\site-packages\twisted\python\lockfile.py", line 28, in <
module>
from win32api import OpenProcess
ImportError: No module named win32api
C:\Python26\Scripts>
i am using windows vista. i seacrche on net and found that i sholld copy 2 file in system32 , when i tried to do so i found that those files were already present there. But am still geting the errror.
how wold i install win32api on vista?
A:
I'd start by installing the win32 extensions. If you have done so already, this is probably a path issue.
|
orbited twisted installation problems
|
i am geting folloing error when i am trying to start orbited server
C:\Python26\Scripts>orbited
Traceback (most recent call last):
File "C:\Python26\Scripts\orbited-script.py", line 8, in <module>
load_entry_point('orbited==0.7.9', 'console_scripts', 'orbited')()
File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\start.py",
line 84, in main
install = _import('twisted.internet.%sreactor.install' % reactor_name)
File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\start.py",
line 13, in _import
return reduce(getattr, name.split('.')[1:], __import__(module_import))
File "C:\Python26\lib\site-packages\twisted\internet\selectreactor.py", line 2
1, in <module>
from twisted.internet import posixbase
File "C:\Python26\lib\site-packages\twisted\internet\posixbase.py", line 25, i
n <module>
from twisted.internet import tcp, udp
File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 78, in <mod
ule>
from twisted.internet import defer, base, address
File "C:\Python26\lib\site-packages\twisted\internet\defer.py", line 17, in <m
odule>
from twisted.python import log, failure, lockfile
File "C:\Python26\lib\site-packages\twisted\python\lockfile.py", line 28, in <
module>
from win32api import OpenProcess
ImportError: No module named win32api
C:\Python26\Scripts>
i am using windows vista. i seacrche on net and found that i sholld copy 2 file in system32 , when i tried to do so i found that those files were already present there. But am still geting the errror.
how wold i install win32api on vista?
|
[
"I'd start by installing the win32 extensions. If you have done so already, this is probably a path issue.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"twisted"
] |
stackoverflow_0000987632_python_twisted.txt
|
Q:
How do I operate on the actual object, not a copy, in a python for loop?
let's say I have a list
a = [1,2,3]
I'd like to increment every item of that list in place. I want to do something as syntactically easy as
for item in a:
item += 1
but in that example python uses just the value of item, not its actual reference, so when I'm finished with that loop a still returns [1,2,3] instead of [2,3,4]. I know I could do something like
a = map(lambda x:x+1, a)
but that doesn't really fit into my current code and I'd hate to have to rewrite it :-\
A:
Here ya go:
# Your for loop should be rewritten as follows:
for index in xrange(len(a)):
a[index] += 1
Incidentally, item IS a reference to the item in a, but of course you can't assign a new value to an integer. For any mutable type, your code would work just fine:
>>> a = [[1], [2], [3], [4]]
>>> for item in a: item += [1]
>>> a
[[1,1], [2,1], [3,1], [4,1]]
A:
In python integers (and floats, and strings, and tuples) are immutable so you have the actual object (and not a copy), you just can't change it.
What's happening is that in the line: item += 1 you are creating a new integer (with a value of item + 1) and binding the name item to it.
What you want to do, is change the integer that a[index] points to which is why the line a[index] += 1 works. You're still creating a new integer, but then you're updating the list to point to it.
As a side note:
for index,item in enumerate(a):
a[index] = item + 1
... is slightly more idiomatic than the answer posted by Triptych.
A:
Instead of your map-based solution, here's a list-comprehension-based solution
a = [item + 1 for item in a]
|
How do I operate on the actual object, not a copy, in a python for loop?
|
let's say I have a list
a = [1,2,3]
I'd like to increment every item of that list in place. I want to do something as syntactically easy as
for item in a:
item += 1
but in that example python uses just the value of item, not its actual reference, so when I'm finished with that loop a still returns [1,2,3] instead of [2,3,4]. I know I could do something like
a = map(lambda x:x+1, a)
but that doesn't really fit into my current code and I'd hate to have to rewrite it :-\
|
[
"Here ya go:\n# Your for loop should be rewritten as follows:\nfor index in xrange(len(a)):\n a[index] += 1\n\nIncidentally, item IS a reference to the item in a, but of course you can't assign a new value to an integer. For any mutable type, your code would work just fine:\n>>> a = [[1], [2], [3], [4]]\n>>> for item in a: item += [1]\n>>> a\n[[1,1], [2,1], [3,1], [4,1]]\n\n",
"In python integers (and floats, and strings, and tuples) are immutable so you have the actual object (and not a copy), you just can't change it.\nWhat's happening is that in the line: item += 1 you are creating a new integer (with a value of item + 1) and binding the name item to it.\nWhat you want to do, is change the integer that a[index] points to which is why the line a[index] += 1 works. You're still creating a new integer, but then you're updating the list to point to it.\nAs a side note:\nfor index,item in enumerate(a):\n a[index] = item + 1\n\n... is slightly more idiomatic than the answer posted by Triptych.\n",
"Instead of your map-based solution, here's a list-comprehension-based solution\na = [item + 1 for item in a]\n\n"
] |
[
26,
17,
9
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000988155_python.txt
|
Q:
Efficient Tuple List Comparisons
I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.
I have a large list of four element tuples in the format:
(ID number, Type, Start Index, End Index)
Previously in the code, I have searched through thousands of blocks of text for two specific types of substrings. These tuples store in which large chunk of text the substring was found, which of the two types of substrings it is, and the start and end index of this substring.
The final goal is to look through this list to find all instances where a type 1 substring occurs before a type 2 substring in a block of text with the same ID. Then I would like to store these objects in the format (ID, Type 1, Start, End, Type2, Start, End).
I've tried to mess around with a bunch of stuff that was super inefficient. I have the list sorted by ID then Start Index, and if been trying varying ways of popping the items off the list for comparisons. I have to imagine there is a more elegant solution. Any brilliant people out there wish to assist my tired brain???
Thanks in advance
A:
Solution:
result = [(l1 + l2[1:])
for l1 in list1
for l2 in list2
if (l1[0] == l2[0] and l1[3] < l2[2])
]
... with test code:
list1 = [(1, 'Type1', 20, 30,),
(2, 'Type1', 20, 30,),
(3, 'Type1', 20, 30,),
(4, 'Type1', 20, 30,),
(5, 'Type1', 20, 30,),
(6, 'Type1', 20, 30,), # does not have Type2
(8, 'Type1', 20, 30,), # multiple
(8, 'Type1', 25, 35,), # multiple
(8, 'Type1', 50, 55,), # multiple
]
list2 = [(1, 'Type2', 40, 50,), # after
(2, 'Type2', 10, 15,), # before
(3, 'Type2', 25, 28,), # inside
(4, 'Type2', 25, 35,), # inside-after
(4, 'Type2', 15, 25,), # inside-before
(7, 'Type2', 20, 30,), # does not have Type1
(8, 'Type2', 40, 50,), # multiple
(8, 'Type2', 60, 70,), # multiple
(8, 'Type2', 80, 90,), # multiple
]
result = [(l1 + l2[1:])
for l1 in list1
for l2 in list2
if (l1[0] == l2[0] and l1[3] < l2[2])
]
print '\n'.join(str(r) for r in result)
It is not clear what result would you like if there is more then one occurrence of both Type1 and Type2 within the same text ID. Please specify.
A:
I don't know how many types you have. But If we assume you have only type 1 and type 2, then it sounds like a problem similar to a merge sort. Doing it with a merge sort, you make a single pass through the list.
Take two indexes, one for type 1 and one for type 2 (I1, I2). Sort the list by id, start1. Start I1 as the first instance of type1, and I2 as zero. If I1.id < I2.Id then increment I1. If I2.id < I1.id then increment I2. If I1.id = I2.id then check iStart.
I1 can only stop on a type one record and I2 can only stop on a type 2 record. Keep incrementing the index till it lands on an appropriate record.
You can make some assumptions to make this faster. When you find an block that succeeds, you can move I1 to the next block. Whenever I2 < I1, you can start I2 at I1 + 1 (WOOPS MAKE SURE YOU DONT DO THIS, BECAUSE YOU WOULD MISS THE FAILURE CASE!) Whenever you detect an obvious failure case, move I1 and I2 to the next block (on appropriate recs of course).
A:
I recently did something like this. I might not be understanding your problem but here goes.
I would use a dictionary:
from collections import defaultdict:
masterdictType1=defaultDict(dict)
masterdictType2=defaultdict(dict)
for item in myList:
if item[1]=Type1
if item[0] not in masterdictType1:
masterdictType1[item[0]]['begin']=item[2] # start index
masterdictType1[item[0]]['end']=item[-1] # end index
if item[1]=Type2
if item[0] not in masterdictType2:
masterdictType2[item[0]]['begin']=item[2] # start index
masterdictType2[item[0]]['end']=item[-1] # end index
joinedDict=defaultdict(dict)
for id in masterdictType1:
if id in masterdictType2:
if masterdictType1[id]['begin']<masterdictType2[id]['begin']:
joinedDict[id]['Type1Begin']=masterdictType1[id]['begin']
joinedDict[id]['Type1End']=masterdictType1[id]['end']
joinedDict[id]['Type2Begin']=masterdictType2[id]['begin']
joinedDict[id]['Type2End']=masterdictType2[id]['end']
This gives you explicitness and gives you something that is durable since you can pickle the dictionary easily.
A:
Assuming there are lots of entries for each ID, I would (pseudo-code)
for each ID:
for each type2 substring of that ID:
store it in an ordered list, sorted by start point
for each type1 substring of that ID:
calculate the end point (or whatever)
look it up in the ordered list
if there's anything to the right, you have a hit
So, if you have control of the initial sort, then instead of (ID, start), you want them sorted by ID, then by type (2 before 1). Then within the type, sort by start point for type2, and the offset you're going to compare for type1. I'm not sure whether by "A before B" you mean "A starts before B starts" or "A ends before B starts", but do whatever's appropriate.
Then you can do the whole operation by running over the list once. You don't need to actually construct an index of type2s, because they're already in order. Since the type1s are sorted too, you can do each lookup with a linear or binary search starting from the result of the previous search. Use a linear search if there are lots of type1s compared with type2s (so results are close together), and a binary search if there are lots of type2s compared with type1s (so results are sparse). Or just stick with the linear search as it's simpler - this lookup is the inner loop, but its performance might not be critical.
If you don't have control of the sort, then I don't know whether it's faster to build the list of type2 substrings for each ID as you go; or to sort the entire list before you start into the required order; or just to work with what you've got, by writing a "lookup" that ignores the type1 entries when searching through the type2s (which are already sorted as required). Test it, or just do whatever results in clearer code. Even without re-sorting, you can still use the merge-style optimisation unless "sorted by start index" is the wrong thing for the type1s.
A:
Could I check, by before, do you mean immediately before (ie. t1_a, t2_b, t2_c, t2_d should just give the pair (t1_a, t2_b), or do you want all pairs where a type1 value occurs anywhere before a type2 one within the same block. (ie (t1_a, t2_b), (t1_a, t2_c), (t1_a, t2_d) for the previous example).
In either case, you should be able to do this with a single pass over your list (assuming sorted by id, then start index).
Here's a solution assuming the second option (every pair):
import itertools, operator
def find_t1_t2(seq):
"""Find every pair of type1, type2 values where the type1 occurs
before the type2 within a block with the same id.
Assumes sequence is ordered by id, then start location.
Generates a sequence of tuples of the type1,type2 entries.
"""
for group, items in itertools.groupby(seq, operator.itemgetter(0)):
type1s=[]
for item in items:
if item[1] == TYPE1:
type1s.append(item)
elif item[1] == TYPE2:
for t1 in type1s:
yield t1 + item[1:]
If it's just immediately before, it's even simpler: just keep track of the previous item and yield the tuple whenever it is type1 and the current one is type2.
Here's an example of usage, and the results returned:
l=[[1, TYPE1, 10, 15],
[1, TYPE2, 20, 25], # match with first
[1, TYPE2, 30, 35], # match with first (2 total matches)
[2, TYPE2, 10, 15], # No match
[2, TYPE1, 20, 25],
[2, TYPE1, 30, 35],
[2, TYPE2, 40, 45], # Match with previous 2 type1s.
[2, TYPE1, 50, 55],
[2, TYPE2, 60, 65], # Match with 3 previous type1 entries (5 total)
]
for x in find_t1_t2(l):
print x
This returns:
[1, 'type1', 10, 15, 'type2', 20, 25]
[1, 'type1', 10, 15, 'type2', 30, 35]
[2, 'type1', 20, 25, 'type2', 40, 45]
[2, 'type1', 30, 35, 'type2', 40, 45]
[2, 'type1', 20, 25, 'type2', 60, 65]
[2, 'type1', 30, 35, 'type2', 60, 65]
[2, 'type1', 50, 55, 'type2', 60, 65]
|
Efficient Tuple List Comparisons
|
I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.
I have a large list of four element tuples in the format:
(ID number, Type, Start Index, End Index)
Previously in the code, I have searched through thousands of blocks of text for two specific types of substrings. These tuples store in which large chunk of text the substring was found, which of the two types of substrings it is, and the start and end index of this substring.
The final goal is to look through this list to find all instances where a type 1 substring occurs before a type 2 substring in a block of text with the same ID. Then I would like to store these objects in the format (ID, Type 1, Start, End, Type2, Start, End).
I've tried to mess around with a bunch of stuff that was super inefficient. I have the list sorted by ID then Start Index, and if been trying varying ways of popping the items off the list for comparisons. I have to imagine there is a more elegant solution. Any brilliant people out there wish to assist my tired brain???
Thanks in advance
|
[
"Solution:\nresult = [(l1 + l2[1:]) \n for l1 in list1 \n for l2 in list2 \n if (l1[0] == l2[0] and l1[3] < l2[2])\n ]\n\n... with test code:\nlist1 = [(1, 'Type1', 20, 30,),\n (2, 'Type1', 20, 30,),\n (3, 'Type1', 20, 30,),\n (4, 'Type1', 20, 30,),\n (5, 'Type1', 20, 30,),\n (6, 'Type1', 20, 30,), # does not have Type2\n\n (8, 'Type1', 20, 30,), # multiple\n (8, 'Type1', 25, 35,), # multiple\n (8, 'Type1', 50, 55,), # multiple\n ]\n\nlist2 = [(1, 'Type2', 40, 50,), # after\n (2, 'Type2', 10, 15,), # before\n (3, 'Type2', 25, 28,), # inside\n (4, 'Type2', 25, 35,), # inside-after\n (4, 'Type2', 15, 25,), # inside-before\n (7, 'Type2', 20, 30,), # does not have Type1\n\n (8, 'Type2', 40, 50,), # multiple\n (8, 'Type2', 60, 70,), # multiple\n (8, 'Type2', 80, 90,), # multiple\n ]\n\nresult = [(l1 + l2[1:]) \n for l1 in list1 \n for l2 in list2 \n if (l1[0] == l2[0] and l1[3] < l2[2])\n ]\n\nprint '\\n'.join(str(r) for r in result)\n\nIt is not clear what result would you like if there is more then one occurrence of both Type1 and Type2 within the same text ID. Please specify. \n",
"I don't know how many types you have. But If we assume you have only type 1 and type 2, then it sounds like a problem similar to a merge sort. Doing it with a merge sort, you make a single pass through the list. \nTake two indexes, one for type 1 and one for type 2 (I1, I2). Sort the list by id, start1. Start I1 as the first instance of type1, and I2 as zero. If I1.id < I2.Id then increment I1. If I2.id < I1.id then increment I2. If I1.id = I2.id then check iStart. \nI1 can only stop on a type one record and I2 can only stop on a type 2 record. Keep incrementing the index till it lands on an appropriate record.\nYou can make some assumptions to make this faster. When you find an block that succeeds, you can move I1 to the next block. Whenever I2 < I1, you can start I2 at I1 + 1 (WOOPS MAKE SURE YOU DONT DO THIS, BECAUSE YOU WOULD MISS THE FAILURE CASE!) Whenever you detect an obvious failure case, move I1 and I2 to the next block (on appropriate recs of course).\n",
"I recently did something like this. I might not be understanding your problem but here goes.\nI would use a dictionary:\nfrom collections import defaultdict:\nmasterdictType1=defaultDict(dict)\nmasterdictType2=defaultdict(dict)\n\n\nfor item in myList:\n if item[1]=Type1\n if item[0] not in masterdictType1:\n masterdictType1[item[0]]['begin']=item[2] # start index\n masterdictType1[item[0]]['end']=item[-1] # end index\n if item[1]=Type2\n if item[0] not in masterdictType2:\n masterdictType2[item[0]]['begin']=item[2] # start index\n masterdictType2[item[0]]['end']=item[-1] # end index\n\njoinedDict=defaultdict(dict)\n\nfor id in masterdictType1:\n if id in masterdictType2:\n if masterdictType1[id]['begin']<masterdictType2[id]['begin']:\n joinedDict[id]['Type1Begin']=masterdictType1[id]['begin']\n joinedDict[id]['Type1End']=masterdictType1[id]['end']\n joinedDict[id]['Type2Begin']=masterdictType2[id]['begin']\n joinedDict[id]['Type2End']=masterdictType2[id]['end']\n\nThis gives you explicitness and gives you something that is durable since you can pickle the dictionary easily.\n",
"Assuming there are lots of entries for each ID, I would (pseudo-code)\n\n for each ID:\n for each type2 substring of that ID:\n store it in an ordered list, sorted by start point\n for each type1 substring of that ID:\n calculate the end point (or whatever)\n look it up in the ordered list\n if there's anything to the right, you have a hit\n\nSo, if you have control of the initial sort, then instead of (ID, start), you want them sorted by ID, then by type (2 before 1). Then within the type, sort by start point for type2, and the offset you're going to compare for type1. I'm not sure whether by \"A before B\" you mean \"A starts before B starts\" or \"A ends before B starts\", but do whatever's appropriate. \nThen you can do the whole operation by running over the list once. You don't need to actually construct an index of type2s, because they're already in order. Since the type1s are sorted too, you can do each lookup with a linear or binary search starting from the result of the previous search. Use a linear search if there are lots of type1s compared with type2s (so results are close together), and a binary search if there are lots of type2s compared with type1s (so results are sparse). Or just stick with the linear search as it's simpler - this lookup is the inner loop, but its performance might not be critical.\nIf you don't have control of the sort, then I don't know whether it's faster to build the list of type2 substrings for each ID as you go; or to sort the entire list before you start into the required order; or just to work with what you've got, by writing a \"lookup\" that ignores the type1 entries when searching through the type2s (which are already sorted as required). Test it, or just do whatever results in clearer code. Even without re-sorting, you can still use the merge-style optimisation unless \"sorted by start index\" is the wrong thing for the type1s.\n",
"Could I check, by before, do you mean immediately before (ie. t1_a, t2_b, t2_c, t2_d should just give the pair (t1_a, t2_b), or do you want all pairs where a type1 value occurs anywhere before a type2 one within the same block. (ie (t1_a, t2_b), (t1_a, t2_c), (t1_a, t2_d) for the previous example).\nIn either case, you should be able to do this with a single pass over your list (assuming sorted by id, then start index).\nHere's a solution assuming the second option (every pair):\nimport itertools, operator\n\ndef find_t1_t2(seq):\n \"\"\"Find every pair of type1, type2 values where the type1 occurs \n before the type2 within a block with the same id.\n\n Assumes sequence is ordered by id, then start location.\n Generates a sequence of tuples of the type1,type2 entries.\n \"\"\"\n for group, items in itertools.groupby(seq, operator.itemgetter(0)):\n type1s=[]\n for item in items:\n if item[1] == TYPE1: \n type1s.append(item)\n elif item[1] == TYPE2:\n for t1 in type1s:\n yield t1 + item[1:]\n\nIf it's just immediately before, it's even simpler: just keep track of the previous item and yield the tuple whenever it is type1 and the current one is type2.\nHere's an example of usage, and the results returned:\nl=[[1, TYPE1, 10, 15],\n [1, TYPE2, 20, 25], # match with first\n [1, TYPE2, 30, 35], # match with first (2 total matches)\n\n [2, TYPE2, 10, 15], # No match\n [2, TYPE1, 20, 25],\n [2, TYPE1, 30, 35],\n [2, TYPE2, 40, 45], # Match with previous 2 type1s.\n [2, TYPE1, 50, 55],\n [2, TYPE2, 60, 65], # Match with 3 previous type1 entries (5 total)\n ]\n\nfor x in find_t1_t2(l):\n print x\n\nThis returns:\n[1, 'type1', 10, 15, 'type2', 20, 25]\n[1, 'type1', 10, 15, 'type2', 30, 35]\n[2, 'type1', 20, 25, 'type2', 40, 45]\n[2, 'type1', 30, 35, 'type2', 40, 45]\n[2, 'type1', 20, 25, 'type2', 60, 65]\n[2, 'type1', 30, 35, 'type2', 60, 65]\n[2, 'type1', 50, 55, 'type2', 60, 65]\n\n"
] |
[
1,
1,
1,
0,
0
] |
[] |
[] |
[
"algorithm",
"list",
"python",
"tuples"
] |
stackoverflow_0000988346_algorithm_list_python_tuples.txt
|
Q:
Python string find
I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it?
A:
So you're searching for all the strings in a list of strings that contain a certain substring? This will do it:
DATA = ['Hello', 'Python', 'World']
SEARCH_STRING = 'n'
print [s for s in DATA if SEARCH_STRING in s]
# Prints ['Python']
Edit at Andrew's suggestion: You should read that list comprehension as "Make a list of all the strings in the list DATA where SEARCH_STRING appears somewhere in the string."
A:
have you looked here it is very simple to do, just do a search in the python documentation
|
Python string find
|
I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it?
|
[
"So you're searching for all the strings in a list of strings that contain a certain substring? This will do it:\nDATA = ['Hello', 'Python', 'World']\nSEARCH_STRING = 'n'\nprint [s for s in DATA if SEARCH_STRING in s]\n# Prints ['Python']\n\nEdit at Andrew's suggestion: You should read that list comprehension as \"Make a list of all the strings in the list DATA where SEARCH_STRING appears somewhere in the string.\"\n",
"have you looked here it is very simple to do, just do a search in the python documentation\n"
] |
[
4,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000989170_python.txt
|
Q:
What's the point of os.error?
Why does Python's os module contain error, an alias for OSError?
Is there a reason to ever spell it os.error? OSError certainly seems more consistent with all the other built-in exceptions.
I hoped os.py would shed some light, but it uses error sometimes and OSError others.
It seems goofy to have an extra name for one of the exceptions, yet it survives into Python 3.0. What am I missing?
A:
The documentation for OSError says that it was added in version 1.5.2. My guess is that error predates this a little and in an effort to remain backwards-compatible to code written for Python before 1.5.2 error was made an alias for OSError.
|
What's the point of os.error?
|
Why does Python's os module contain error, an alias for OSError?
Is there a reason to ever spell it os.error? OSError certainly seems more consistent with all the other built-in exceptions.
I hoped os.py would shed some light, but it uses error sometimes and OSError others.
It seems goofy to have an extra name for one of the exceptions, yet it survives into Python 3.0. What am I missing?
|
[
"The documentation for OSError says that it was added in version 1.5.2. My guess is that error predates this a little and in an effort to remain backwards-compatible to code written for Python before 1.5.2 error was made an alias for OSError.\n"
] |
[
6
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000989259_python.txt
|
Q:
Pythonic way to implement three similar integer range operators?
I am working on a circular problem. In this problem, we have objects that are put on a ring of size MAX, and are assigned IDs from (0 to MAX-1).
I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is i inRange(j,k)). And I have the same for ranges ]j,k[ and ]j,k].
Code in those three methods look duplicated from one method to another:
def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!
After thinking of a better solution, I came up with:
from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
Is it any better? Can you come up with something more intuitive?
In short, what would be the Pythonic way to write these three operators?
Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?
Thanks.
A:
Two Zen of Python principles leap to mind:
Simple is better than complex.
There should be one—and preferably only one—obvious way to do it.
range
The Python built-in function range(start, end) generates a list from start to end.1 The first element of that list is start, and the last element is end - 1.
There is no range_strict function or inclusive_range function. This was very awkward to me when I started in Python. ("I just want a list from a to b inclusive! How hard is that, Guido?") However, the convention used in calling the range function was simple and easy to remember, and the lack of multiple functions made it easy to remember exactly how to generate a range every time.
Recommendation
As you've probably guessed, my recommendation is to only create a function to test whether i is in the range [j, k). In fact, my recommendation is to keep only your existing inRange function.
(Since your question specifically mentions Pythonicity, I would recommend you name the function as in_range to better fit with the Python Style Guide.)
Justification
Why is this a good idea?
The single function is easy to understand. It is very easy to learn how to use it.
Of course, the same could be said for each of your three starting functions. So far so good.
There is only one function to learn. There are not three functions with necessarily similar names.
Given the similar names and behaviours of your three functions, it is somewhat possible that you will, at some point, use the wrong function. This is compounded by the fact that the functions return the same value except for edge cases, which could lead to a hard-to-find off-by-one bug. By only making one function available, you know you will not make such a mistake.
The function is easy to edit.
It is unlikely that you'll need to ever debug or edit such an easy piece of code. However, should you need to do so, you need only edit this one function. With your original three functions, you have to make the same edit in three places. With your revised code in your self-answer, the code is made slightly less intuitive by the operator obfuscation.
The "size" of the range is obvious.
For a given ring where you would use inRange(i, j, k), it is obvious how many elements would be covered by the range [j, k). Here it is in code.
if j <= k:
size = k - j
if j > k:
size = k - j + MAX
So therefore
size = (k - j) % MAX
Caveats
I'm approaching this problem from a completely generic point of view, such as that of a person writing a function for a publicly-released library. Since I don't know your problem domain, I can't say whether this is a practical solution.
Using this solution may mean a fair bit of refactoring of the code that calls these functions. Look through this code to see if editing it is prohibitively difficult or tedious.
1: Actually, it is range([start], end, [step]). I trust you get what I mean though.
A:
The Pythonic way to do it is to choose readability, and therefor keep the 3 methods as they were at the beginning.
It's not like they are HUGE methods, or there are thousand of them, or you would have to dynamically generate them.
A:
No higher-order functions, but it's less code, even with the extraneous else.
def exclusive(i, j, k):
if j <= k:
return j < i < k
else:
return j < i or i < k
def inclusive_left(i, j, k):
return i==j or exclusive(i, j, k)
def inclusive_right(i, j, k):
return i==k or exclusive(i, j, k)
I actually tried switching the identifiers to n, a, b, but the code began to look less cohesive. (My point: perfecting this code may not be a productive use of time.)
A:
Now I am thinking of something such as:
def comparator(lop, rop):
def comp(i, j, k):
if j <= k:
return lop(j, i) and rop(i,k)
return lop(j, i) or rop(i,k)
return comp
from operator import le, lt
inRange = comparator(le, lt)
inStrictRange = comparator(lt, lt)
inRange2 = comparator(lt, le)
Which looks better indeed.
A:
I certainly agree that you need only one function, and that the function should use a (Pythonic) half-open range.
Two suggestions:
Use meaningful names for the args:
in_range(x, lo, hi) is a big
improvement relative to the
2-keystroke cost.
Document the fact that the
constraint hi < MAX means that it is
not possible to express a range that
includes all MAX elements. As
Wesley remarked, size = (k - j) %
MAX i.e. size = (hi - lo) % MAX
and thus 0 <= size < MAX.
A:
To make it more familiar to your users, I would have one main in_range function with the same bounds as range(). This makes it much easier to remember, and has other nice properties as Wesley mentioned.
def in_range(i, j, k):
return (j <= i < k) if j <= k else (j <= i or i < k)
You can certainly use this one alone for all your use cases by adding 1 to j and/or k. If you find that you're using a specific form frequently, then you can define it in terms of the main one:
def exclusive(i, j, k):
"""Excludes both endpoints."""
return in_range(i, j + 1, k)
def inclusive(i, j, k):
"""Includes both endpoints."""
return in_range(i, j, k + 1)
def weird(i, j, k):
"""Excludes the left endpoint but includes the right endpoint."""
return in_range(i, j + 1, k + 1)
This is shorter than mucking around with operators, and is also much less confusing to understand. Also, note that you should use underscores instead of camelCase for function names in Python.
A:
I'd go one step further than Wesley in aping the normal python 'in range' idiom; i'd write a cyclic_range class:
import itertools
MAX = 10 # or whatever
class cyclic_range(object):
def __init__(self, start, stop):
# mod so you can be a bit sloppy with indices, plus -1 means the last element, as with list indices
self.start = start % MAX
self.stop = stop % MAX
def __len__(self):
return (self.stop - self.start) % MAX
def __getitem__(self, i):
return (self.start + i) % MAX
def __contains__(self, x):
if (self.start < self.stop):
return (x >= self.start) and (x < self.stop)
else:
return (x >= self.start) or (x < self.stop)
def __iter__(self):
for i in xrange(len(self)):
yield self[i]
def __eq__(self, other):
if (len(self) != len(other)): return False
for a, b in itertools.izip(self, other):
if (a != b): return False
return True
def __hash__(self):
return (self.start << 1) + self.stop
def __str__(self):
return str(list(self))
def __repr__(self):
return "cyclic_range(" + str(self.start) + ", " + str(self.stop) + ")"
# and whatever other list-like methods you fancy
You can then write code like:
if (myIndex in cyclic_range(firstNode, stopNode)):
blah
To do the equivalent of inRange. To do inStrictRange, write:
if (myIndex in cyclic_range(firstNode + 1, stopNode)):
And to do inRange2:
if (myIndex in cyclic_range(firstNode + 1, stopNode + 1)):
If you don't like doing the additions by hand, how about adding these methods:
def strict(self):
return cyclic_range(self.start + 1, self.stop)
def right_closed(self):
return cyclic_range(self.start + 1, self.stop + 1)
And then doing:
if (myIndex in cyclic_range(firstNode, stopNode).strict()): # inStrictRange
if (myIndex in cyclic_range(firstNode, stopNode).closed_right()): # inRange2
Whilst this approach is, IMHO, more readable, it does involve doing an allocation, rather than just a function call, which is more expensive - although still O(1). But then if you really cared about performance, you wouldn't be using python!
|
Pythonic way to implement three similar integer range operators?
|
I am working on a circular problem. In this problem, we have objects that are put on a ring of size MAX, and are assigned IDs from (0 to MAX-1).
I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is i inRange(j,k)). And I have the same for ranges ]j,k[ and ]j,k].
Code in those three methods look duplicated from one method to another:
def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!
After thinking of a better solution, I came up with:
from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
Is it any better? Can you come up with something more intuitive?
In short, what would be the Pythonic way to write these three operators?
Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?
Thanks.
|
[
"Two Zen of Python principles leap to mind:\n\nSimple is better than complex.\nThere should be one—and preferably only one—obvious way to do it.\n\nrange\nThe Python built-in function range(start, end) generates a list from start to end.1 The first element of that list is start, and the last element is end - 1.\nThere is no range_strict function or inclusive_range function. This was very awkward to me when I started in Python. (\"I just want a list from a to b inclusive! How hard is that, Guido?\") However, the convention used in calling the range function was simple and easy to remember, and the lack of multiple functions made it easy to remember exactly how to generate a range every time.\nRecommendation\nAs you've probably guessed, my recommendation is to only create a function to test whether i is in the range [j, k). In fact, my recommendation is to keep only your existing inRange function.\n(Since your question specifically mentions Pythonicity, I would recommend you name the function as in_range to better fit with the Python Style Guide.)\nJustification\nWhy is this a good idea?\n\nThe single function is easy to understand. It is very easy to learn how to use it.\nOf course, the same could be said for each of your three starting functions. So far so good.\nThere is only one function to learn. There are not three functions with necessarily similar names.\nGiven the similar names and behaviours of your three functions, it is somewhat possible that you will, at some point, use the wrong function. This is compounded by the fact that the functions return the same value except for edge cases, which could lead to a hard-to-find off-by-one bug. By only making one function available, you know you will not make such a mistake.\nThe function is easy to edit.\nIt is unlikely that you'll need to ever debug or edit such an easy piece of code. However, should you need to do so, you need only edit this one function. With your original three functions, you have to make the same edit in three places. With your revised code in your self-answer, the code is made slightly less intuitive by the operator obfuscation.\nThe \"size\" of the range is obvious.\nFor a given ring where you would use inRange(i, j, k), it is obvious how many elements would be covered by the range [j, k). Here it is in code.\nif j <= k:\n size = k - j\nif j > k:\n size = k - j + MAX\n\nSo therefore\nsize = (k - j) % MAX\n\n\nCaveats\nI'm approaching this problem from a completely generic point of view, such as that of a person writing a function for a publicly-released library. Since I don't know your problem domain, I can't say whether this is a practical solution.\nUsing this solution may mean a fair bit of refactoring of the code that calls these functions. Look through this code to see if editing it is prohibitively difficult or tedious.\n\n1: Actually, it is range([start], end, [step]). I trust you get what I mean though.\n",
"The Pythonic way to do it is to choose readability, and therefor keep the 3 methods as they were at the beginning.\nIt's not like they are HUGE methods, or there are thousand of them, or you would have to dynamically generate them.\n",
"No higher-order functions, but it's less code, even with the extraneous else.\ndef exclusive(i, j, k):\n if j <= k:\n return j < i < k\n else:\n return j < i or i < k\n\ndef inclusive_left(i, j, k):\n return i==j or exclusive(i, j, k)\n\ndef inclusive_right(i, j, k):\n return i==k or exclusive(i, j, k)\n\nI actually tried switching the identifiers to n, a, b, but the code began to look less cohesive. (My point: perfecting this code may not be a productive use of time.)\n",
"Now I am thinking of something such as:\ndef comparator(lop, rop):\n def comp(i, j, k):\n if j <= k:\n return lop(j, i) and rop(i,k)\n return lop(j, i) or rop(i,k)\n\n return comp\n\nfrom operator import le, lt\n\ninRange = comparator(le, lt)\ninStrictRange = comparator(lt, lt)\ninRange2 = comparator(lt, le)\n\nWhich looks better indeed.\n",
"I certainly agree that you need only one function, and that the function should use a (Pythonic) half-open range.\nTwo suggestions:\n\nUse meaningful names for the args:\nin_range(x, lo, hi) is a big\nimprovement relative to the\n2-keystroke cost.\nDocument the fact that the\nconstraint hi < MAX means that it is\nnot possible to express a range that\nincludes all MAX elements. As\nWesley remarked, size = (k - j) %\nMAX i.e. size = (hi - lo) % MAX\nand thus 0 <= size < MAX.\n\n",
"To make it more familiar to your users, I would have one main in_range function with the same bounds as range(). This makes it much easier to remember, and has other nice properties as Wesley mentioned.\ndef in_range(i, j, k):\n return (j <= i < k) if j <= k else (j <= i or i < k)\n\nYou can certainly use this one alone for all your use cases by adding 1 to j and/or k. If you find that you're using a specific form frequently, then you can define it in terms of the main one:\ndef exclusive(i, j, k):\n \"\"\"Excludes both endpoints.\"\"\"\n return in_range(i, j + 1, k)\n\ndef inclusive(i, j, k):\n \"\"\"Includes both endpoints.\"\"\"\n return in_range(i, j, k + 1)\n\ndef weird(i, j, k):\n \"\"\"Excludes the left endpoint but includes the right endpoint.\"\"\"\n return in_range(i, j + 1, k + 1)\n\nThis is shorter than mucking around with operators, and is also much less confusing to understand. Also, note that you should use underscores instead of camelCase for function names in Python.\n",
"I'd go one step further than Wesley in aping the normal python 'in range' idiom; i'd write a cyclic_range class:\nimport itertools\n\nMAX = 10 # or whatever\n\nclass cyclic_range(object):\n def __init__(self, start, stop):\n # mod so you can be a bit sloppy with indices, plus -1 means the last element, as with list indices\n self.start = start % MAX\n self.stop = stop % MAX\n def __len__(self):\n return (self.stop - self.start) % MAX\n def __getitem__(self, i):\n return (self.start + i) % MAX\n def __contains__(self, x):\n if (self.start < self.stop):\n return (x >= self.start) and (x < self.stop)\n else:\n return (x >= self.start) or (x < self.stop)\n def __iter__(self):\n for i in xrange(len(self)):\n yield self[i]\n def __eq__(self, other):\n if (len(self) != len(other)): return False\n for a, b in itertools.izip(self, other):\n if (a != b): return False\n return True\n def __hash__(self):\n return (self.start << 1) + self.stop\n def __str__(self):\n return str(list(self))\n def __repr__(self):\n return \"cyclic_range(\" + str(self.start) + \", \" + str(self.stop) + \")\"\n # and whatever other list-like methods you fancy\n\nYou can then write code like:\nif (myIndex in cyclic_range(firstNode, stopNode)):\n blah\n\nTo do the equivalent of inRange. To do inStrictRange, write:\nif (myIndex in cyclic_range(firstNode + 1, stopNode)):\n\nAnd to do inRange2:\nif (myIndex in cyclic_range(firstNode + 1, stopNode + 1)):\n\nIf you don't like doing the additions by hand, how about adding these methods:\n def strict(self):\n return cyclic_range(self.start + 1, self.stop)\n def right_closed(self):\n return cyclic_range(self.start + 1, self.stop + 1)\n\nAnd then doing:\nif (myIndex in cyclic_range(firstNode, stopNode).strict()): # inStrictRange\nif (myIndex in cyclic_range(firstNode, stopNode).closed_right()): # inRange2\n\nWhilst this approach is, IMHO, more readable, it does involve doing an allocation, rather than just a function call, which is more expensive - although still O(1). But then if you really cared about performance, you wouldn't be using python!\n"
] |
[
7,
5,
4,
2,
2,
1,
1
] |
[] |
[] |
[
"operators",
"python"
] |
stackoverflow_0000985309_operators_python.txt
|
Q:
Getting the first and last item in a python for loop
Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?
from calendar import Calendar
cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
if (is first item): # this is fake
month_start = date
if (is last item): # so is this
month_end = date
This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.
Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this?
A:
I would just force it into a list at the beginning:
from calendar import Calendar, SUNDAY
cal = Calendar(SUNDAY)
month_dates = list(cal.itermonthdates(year, month))
month_start = month_dates[0]
month_end = month_dates[-1]
Since there can only be 42 days (counting leading and tailing context), this has negligible performance impact.
Also, using SUNDAY is better than a magic number.
A:
Richie's got the right idea. Simpler:
month_dates = cal.itermonthdates(year, month)
month_start = month_dates.next()
for month_end in month_dates: pass # bletcherous
A:
How about this?
for i, date in enumerate(month_dates):
if i == 0:
month_start = date
month_end = date
enumerate() lets you find the first one, and the date variable falls out of the loop to give you the last one.
A:
For this specific problem, I think I would go with Matthew Flaschen's solution. It seems the most straightforward to me.
If your question is meant to be taken more generally, though, for any generator (with an unknown and possibly large number of elements), then something more like RichieHindle's approach may be better. My slight modification on his solution is not to enumerate and test for element 0, but rather just grab the first element explicitly:
month_dates = cal.itermonthdates(year, month)
month_start = month_dates.next()
for date in month_dates:
pass
month_end = date
|
Getting the first and last item in a python for loop
|
Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?
from calendar import Calendar
cal = Calendar(6)
month_dates = cal.itermonthdates(year, month)
for date in month_dates:
if (is first item): # this is fake
month_start = date
if (is last item): # so is this
month_end = date
This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.
Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this?
|
[
"I would just force it into a list at the beginning:\nfrom calendar import Calendar, SUNDAY\n\ncal = Calendar(SUNDAY)\nmonth_dates = list(cal.itermonthdates(year, month))\n\nmonth_start = month_dates[0]\nmonth_end = month_dates[-1]\n\nSince there can only be 42 days (counting leading and tailing context), this has negligible performance impact.\nAlso, using SUNDAY is better than a magic number.\n",
"Richie's got the right idea. Simpler:\nmonth_dates = cal.itermonthdates(year, month)\nmonth_start = month_dates.next()\nfor month_end in month_dates: pass # bletcherous\n\n",
"How about this?\nfor i, date in enumerate(month_dates):\n if i == 0:\n month_start = date\n\nmonth_end = date\n\nenumerate() lets you find the first one, and the date variable falls out of the loop to give you the last one.\n",
"For this specific problem, I think I would go with Matthew Flaschen's solution. It seems the most straightforward to me.\nIf your question is meant to be taken more generally, though, for any generator (with an unknown and possibly large number of elements), then something more like RichieHindle's approach may be better. My slight modification on his solution is not to enumerate and test for element 0, but rather just grab the first element explicitly:\nmonth_dates = cal.itermonthdates(year, month)\nmonth_start = month_dates.next()\nfor date in month_dates:\n pass\nmonth_end = date\n\n"
] |
[
11,
11,
10,
2
] |
[] |
[] |
[
"for_loop",
"python"
] |
stackoverflow_0000989665_for_loop_python.txt
|
Q:
Automated Python to Java translation
Is there a tool out there that can automatically convert Python to Java?
Can Jython do this?
A:
Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc
In fact, this is probably pretty easy to knock up in Python.
I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.
Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.
A:
It may not be an easy problem.
Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).
A:
Yes Jython does this, but it may or may not be what you want
A:
to clarify your question:
From Python Source code to Java source code? (I don't think so)
.. or from Python source code to Java Bytecode? (Jython does this under the hood)
|
Automated Python to Java translation
|
Is there a tool out there that can automatically convert Python to Java?
Can Jython do this?
|
[
"Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc\nIn fact, this is probably pretty easy to knock up in Python.\nI worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.\nHere's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.\n",
"It may not be an easy problem.\nDetermining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding). \n",
"Yes Jython does this, but it may or may not be what you want\n",
"to clarify your question:\nFrom Python Source code to Java source code? (I don't think so)\n.. or from Python source code to Java Bytecode? (Jython does this under the hood)\n"
] |
[
15,
8,
4,
1
] |
[] |
[] |
[
"code_translation",
"java",
"jython",
"python"
] |
stackoverflow_0000153491_code_translation_java_jython_python.txt
|
Q:
python string input problem with whitespace!
my input is something like this
23 + 45 = astart
for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this
SyntaxError: invalid syntax
the code is this
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
its always number + number = astar
its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error
A:
Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing
on either side of the + and = in the code and input.
You appear to have two spaces on either side of them in the code, but only one on either
side in the input. Also - you do not have to use the str(i) in a generator. You can do
it like a,b=k.split(' + ')
My cut and pastes:
My test script:
print 'Enter input #1:'
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
print 'Here are the resulting values:'
print a
print b
print c
print 'Enter input #2:'
k=raw_input()
a,b=k.split(' + ')
b,c=b.split(' = ')
print 'Here are the resulting values:'
print a
print b
print c
From the interpreter:
>>>
Enter input #1:
23 + 45 = astart
Here are the resulting values:
23
45
astart
Enter input #2:
23 + 45 = astart
Here are the resulting values:
23
45
astart
>>>
A:
Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs
calling (... for ...) only returns a generator object, not a tuple
try one of the following:
a,b=[str(i) for i in k.split(' + ')]
a,b=list(str(i) for i in k.split(' + '))
they return a list which can be unpacked (assuming one split)
or use str.partition assuming 2.5 or greater:
a, serperator, b = k.partition('+')
which will always return a 3 tuple even if the string isn't found
Edit: and if you don't want the spaces in your input use the strip function
a = a.strip()
b = b.strip()
Edit: fixed str.partition method, had wrong function name for some reason
A:
I think I'd just use a simple regular expression:
# Set up a few regular expressions
parser = re.compile("(\d+)\+(\d+)=(.+)")
spaces = re.compile("\s+")
# Grab input
input = raw_input()
# Remove all whitespace
input = spaces.sub('',input)
# Parse away
num1, num2, result = m.match(input)
A:
You could just use:
a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()
Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:
a, b, c = raw_input().split()[::2]
Hrm - just realized that second one requires spaces, though, so not as good.
A:
Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products.
k=raw_input()
print k.split(' + ')
a,b=(str(i) for i in k.split(' + '))
print b.split(' = ')
b,c=(str(i) for i in b.split(' = '))
This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.
I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on.
|
python string input problem with whitespace!
|
my input is something like this
23 + 45 = astart
for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this
SyntaxError: invalid syntax
the code is this
k=raw_input()
a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))
its always number + number = astar
its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error
|
[
"Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing\non either side of the + and = in the code and input.\nYou appear to have two spaces on either side of them in the code, but only one on either\nside in the input. Also - you do not have to use the str(i) in a generator. You can do\nit like a,b=k.split(' + ')\nMy cut and pastes:\n\nMy test script:\n\nprint 'Enter input #1:'\nk=raw_input()\n\na,b=(str(i) for i in k.split(' + '))\nb,c=(str(i) for i in b.split(' = '))\n\nprint 'Here are the resulting values:'\nprint a\nprint b\nprint c\n\n\nprint 'Enter input #2:'\nk=raw_input()\n\na,b=k.split(' + ')\nb,c=b.split(' = ')\n\nprint 'Here are the resulting values:'\nprint a\nprint b\nprint c\n\n\nFrom the interpreter:\n\n>>> \nEnter input #1:\n23 + 45 = astart\nHere are the resulting values:\n23\n45\nastart\nEnter input #2:\n23 + 45 = astart\nHere are the resulting values:\n23\n45\nastart\n>>> \n\n",
"Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs\ncalling (... for ...) only returns a generator object, not a tuple\ntry one of the following:\na,b=[str(i) for i in k.split(' + ')]\na,b=list(str(i) for i in k.split(' + '))\n\nthey return a list which can be unpacked (assuming one split)\n\nor use str.partition assuming 2.5 or greater:\na, serperator, b = k.partition('+')\n\nwhich will always return a 3 tuple even if the string isn't found\nEdit: and if you don't want the spaces in your input use the strip function\na = a.strip()\nb = b.strip()\n\nEdit: fixed str.partition method, had wrong function name for some reason\n",
"I think I'd just use a simple regular expression:\n# Set up a few regular expressions\nparser = re.compile(\"(\\d+)\\+(\\d+)=(.+)\")\nspaces = re.compile(\"\\s+\")\n\n# Grab input\ninput = raw_input()\n\n# Remove all whitespace\ninput = spaces.sub('',input)\n\n# Parse away\nnum1, num2, result = m.match(input)\n\n",
"You could just use:\na, b, c = raw_input().replace('+',' ').replace('=', ' ').split()\n\nOr [Edited to add] - here's another one that avoids creating the extra intermediate strings:\na, b, c = raw_input().split()[::2]\n\nHrm - just realized that second one requires spaces, though, so not as good.\n",
"Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products. \nk=raw_input()\nprint k.split(' + ')\na,b=(str(i) for i in k.split(' + '))\nprint b.split(' = ')\nb,c=(str(i) for i in b.split(' = '))\n\nThis will show you the actual list elements produced by the split, which might shed some light on the problem you're having.\nI'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on. \n"
] |
[
2,
1,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000989276_python.txt
|
Q:
Python and psycopg2 - raw sql select from table with integer criteria
It should be simple, bit I've spent the last hour searching for the answer. This is using psycopg2 on python 2.6.
I need something like this:
special_id = 5
sql = """
select count(*) as ct,
from some_table tbl
where tbl.id = %(the_id)
"""
cursor = connection.cursor()
cursor.execute(sql, {"the_id" : special_id})
I cannot get this to work. Were special_id a string, I could replace %(the_id) with %(the_id)s and things work well. However, I want it to use the integer so that it hits my indexes correctly.
There is a surprising lack of specific information on psycopg2 on the internet. I hope someone has an answer to this seemingly simple question.
A:
Per PEP 249, since in psycopg2 paramstyle is pyformat, you need to use %(the_id)s even for non-strings -- trust it to do the right thing.
BTW, internet searches will work better if you use the correct spelling (no h there), but even if you mis-spelled, I'm surprised you didn't get a "did you mean" hint (I did when I deliberately tried!).
|
Python and psycopg2 - raw sql select from table with integer criteria
|
It should be simple, bit I've spent the last hour searching for the answer. This is using psycopg2 on python 2.6.
I need something like this:
special_id = 5
sql = """
select count(*) as ct,
from some_table tbl
where tbl.id = %(the_id)
"""
cursor = connection.cursor()
cursor.execute(sql, {"the_id" : special_id})
I cannot get this to work. Were special_id a string, I could replace %(the_id) with %(the_id)s and things work well. However, I want it to use the integer so that it hits my indexes correctly.
There is a surprising lack of specific information on psycopg2 on the internet. I hope someone has an answer to this seemingly simple question.
|
[
"Per PEP 249, since in psycopg2 paramstyle is pyformat, you need to use %(the_id)s even for non-strings -- trust it to do the right thing.\nBTW, internet searches will work better if you use the correct spelling (no h there), but even if you mis-spelled, I'm surprised you didn't get a \"did you mean\" hint (I did when I deliberately tried!).\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000989833_python.txt
|
Q:
Weird program behaviour in Python
When running the following code, which is an easy problem, the Python interpreter works weirdly:
n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?
EDIT: I'm working under Python 2.5, 32 bits in Windows.
A:
Are you sure that the problem is the print i statement? The code works as
expected when I uncomment that statement and run it. However, if I forget to
enter a value for the first input() call, and just enter "4 PYTHON" right off
the bat, then I get:
"SyntaxError: unexpected EOF while parsing"
This happens because input() is not simply storing the text you enter, but also
running eval() on it. And "4 PYTHON" isn't valid python code.
A:
This worked for me too, give it a try...
n = raw_input()
n = int(n)
for i in range(n):
testcase = raw_input()
print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
Note the n = int(n)
PS: You can continue to use n = input() on the first line; i prefer raw_input.
A:
I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.
Do you always get that error? Can you post a transcript of your interactive session, complete with stack trace?
|
Weird program behaviour in Python
|
When running the following code, which is an easy problem, the Python interpreter works weirdly:
n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?
EDIT: I'm working under Python 2.5, 32 bits in Windows.
|
[
"Are you sure that the problem is the print i statement? The code works as\nexpected when I uncomment that statement and run it. However, if I forget to\nenter a value for the first input() call, and just enter \"4 PYTHON\" right off\nthe bat, then I get:\n\"SyntaxError: unexpected EOF while parsing\"\n\nThis happens because input() is not simply storing the text you enter, but also\nrunning eval() on it. And \"4 PYTHON\" isn't valid python code.\n",
"This worked for me too, give it a try...\nn = raw_input()\nn = int(n)\nfor i in range(n):\n testcase = raw_input()\n print i\n print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]\n\nNote the n = int(n)\nPS: You can continue to use n = input() on the first line; i prefer raw_input.\n",
"I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.\nDo you always get that error? Can you post a transcript of your interactive session, complete with stack trace?\n"
] |
[
4,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000982970_python.txt
|
Q:
How do I draw out specific data from an opened url in Python using urllib2?
I'm new to Python and am playing around with making a very basic web crawler. For instance, I have made a simple function to load a page that shows the high scores for an online game. So I am able to get the source code of the html page, but I need to draw specific numbers from that page. For instance, the webpage looks like this:
http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13
where 'bigdrizzle13' is the unique part of the link. The numbers on that page need to be drawn out and returned. Essentially, I want to build a program that all I would have to do is type in 'bigdrizzle13' and it could output those numbers.
A:
As another poster mentioned, BeautifulSoup is a wonderful tool for this job.
Here's the entire, ostentatiously-commented program. It could use a lot of error tolerance, but as long as you enter a valid username, it will pull all the scores from the corresponding web page.
I tried to comment as well as I could. If you're fresh to BeautifulSoup, I highly recommend working through my example with the BeautifulSoup documentation handy.
The whole program...
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
import sys
URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1]
# Grab page html, create BeatifulSoup object
html = urlopen(URL).read()
soup = BeautifulSoup(html)
# Grab the <table id="mini_player"> element
scores = soup.find('table', {'id':'mini_player'})
# Get a list of all the <tr>s in the table, skip the header row
rows = scores.findAll('tr')[1:]
# Helper function to return concatenation of all character data in an element
def parse_string(el):
text = ''.join(el.findAll(text=True))
return text.strip()
for row in rows:
# Get all the text from the <td>s
data = map(parse_string, row.findAll('td'))
# Skip the first td, which is an image
data = data[1:]
# Do something with the data...
print data
And here's a test run.
> test.py bigdrizzle13
[u'Overall', u'87,417', u'1,784', u'78,772,017']
[u'Attack', u'140,903', u'88', u'4,509,031']
[u'Defence', u'123,057', u'85', u'3,449,751']
[u'Strength', u'325,883', u'84', u'3,057,628']
[u'Hitpoints', u'245,982', u'85', u'3,571,420']
[u'Ranged', u'583,645', u'71', u'856,428']
[u'Prayer', u'227,853', u'62', u'357,847']
[u'Magic', u'368,201', u'75', u'1,264,042']
[u'Cooking', u'34,754', u'99', u'13,192,745']
[u'Woodcutting', u'50,080', u'93', u'7,751,265']
[u'Fletching', u'53,269', u'99', u'13,051,939']
[u'Fishing', u'5,195', u'99', u'14,512,569']
[u'Firemaking', u'46,398', u'88', u'4,677,933']
[u'Crafting', u'328,268', u'62', u'343,143']
[u'Smithing', u'39,898', u'77', u'1,561,493']
[u'Mining', u'31,584', u'85', u'3,331,051']
[u'Herblore', u'247,149', u'52', u'135,215']
[u'Agility', u'225,869', u'60', u'276,753']
[u'Thieving', u'292,638', u'56', u'193,037']
[u'Slayer', u'113,245', u'73', u'998,607']
[u'Farming', u'204,608', u'51', u'115,507']
[u'Runecraft', u'38,369', u'71', u'880,789']
[u'Hunter', u'384,920', u'53', u'139,030']
[u'Construction', u'232,379', u'52', u'125,708']
[u'Summoning', u'87,236', u'64', u'419,086']
Voila :)
A:
You can use Beautiful Soup to parse the HTML.
|
How do I draw out specific data from an opened url in Python using urllib2?
|
I'm new to Python and am playing around with making a very basic web crawler. For instance, I have made a simple function to load a page that shows the high scores for an online game. So I am able to get the source code of the html page, but I need to draw specific numbers from that page. For instance, the webpage looks like this:
http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13
where 'bigdrizzle13' is the unique part of the link. The numbers on that page need to be drawn out and returned. Essentially, I want to build a program that all I would have to do is type in 'bigdrizzle13' and it could output those numbers.
|
[
"As another poster mentioned, BeautifulSoup is a wonderful tool for this job. \nHere's the entire, ostentatiously-commented program. It could use a lot of error tolerance, but as long as you enter a valid username, it will pull all the scores from the corresponding web page. \nI tried to comment as well as I could. If you're fresh to BeautifulSoup, I highly recommend working through my example with the BeautifulSoup documentation handy. \nThe whole program...\nfrom urllib2 import urlopen\nfrom BeautifulSoup import BeautifulSoup\nimport sys\n\nURL = \"http://hiscore.runescape.com/hiscorepersonal.ws?user1=\" + sys.argv[1]\n\n# Grab page html, create BeatifulSoup object\nhtml = urlopen(URL).read()\nsoup = BeautifulSoup(html)\n\n# Grab the <table id=\"mini_player\"> element\nscores = soup.find('table', {'id':'mini_player'})\n\n# Get a list of all the <tr>s in the table, skip the header row\nrows = scores.findAll('tr')[1:]\n\n# Helper function to return concatenation of all character data in an element\ndef parse_string(el):\n text = ''.join(el.findAll(text=True))\n return text.strip()\n\nfor row in rows:\n\n # Get all the text from the <td>s\n data = map(parse_string, row.findAll('td'))\n\n # Skip the first td, which is an image\n data = data[1:]\n\n # Do something with the data...\n print data\n\nAnd here's a test run.\n> test.py bigdrizzle13\n[u'Overall', u'87,417', u'1,784', u'78,772,017']\n[u'Attack', u'140,903', u'88', u'4,509,031']\n[u'Defence', u'123,057', u'85', u'3,449,751']\n[u'Strength', u'325,883', u'84', u'3,057,628']\n[u'Hitpoints', u'245,982', u'85', u'3,571,420']\n[u'Ranged', u'583,645', u'71', u'856,428']\n[u'Prayer', u'227,853', u'62', u'357,847']\n[u'Magic', u'368,201', u'75', u'1,264,042']\n[u'Cooking', u'34,754', u'99', u'13,192,745']\n[u'Woodcutting', u'50,080', u'93', u'7,751,265']\n[u'Fletching', u'53,269', u'99', u'13,051,939']\n[u'Fishing', u'5,195', u'99', u'14,512,569']\n[u'Firemaking', u'46,398', u'88', u'4,677,933']\n[u'Crafting', u'328,268', u'62', u'343,143']\n[u'Smithing', u'39,898', u'77', u'1,561,493']\n[u'Mining', u'31,584', u'85', u'3,331,051']\n[u'Herblore', u'247,149', u'52', u'135,215']\n[u'Agility', u'225,869', u'60', u'276,753']\n[u'Thieving', u'292,638', u'56', u'193,037']\n[u'Slayer', u'113,245', u'73', u'998,607']\n[u'Farming', u'204,608', u'51', u'115,507']\n[u'Runecraft', u'38,369', u'71', u'880,789']\n[u'Hunter', u'384,920', u'53', u'139,030']\n[u'Construction', u'232,379', u'52', u'125,708']\n[u'Summoning', u'87,236', u'64', u'419,086']\n\nVoila :)\n",
"You can use Beautiful Soup to parse the HTML.\n"
] |
[
11,
3
] |
[] |
[] |
[
"python",
"urllib2"
] |
stackoverflow_0000989872_python_urllib2.txt
|
Q:
Curious about differences in vtkMassProperties for VTK 5.04 and VTK 5.4.2
I have a small python VTK function that calculates the volume and surface area of an object embedded in a stack of TIFF images. To read the TIFF's into VTK, I have used vtkTIFFReader and processed the result using vtkImageThreshold. I then use vtkMassProperties to extract the volume and surface area of the object identified after thresholding.
With VTK-5.04, this function returns the correct value for a test stack (3902 pixels). However, using VTK-5.4.2 the same function returns a different value (422 pixels). Can someone explain this?
Code
def testvtk():
# read 36 TIFF images. Each TIFF is 27x27 pixels
v16=vtk.vtkTIFFReader()
v16.SetFilePrefix("d:/test/slice")
v16.SetDataExtent(0,27,0,27,1,36)
v16.SetFilePattern("%s%04d.tif")
v16.SetDataSpacing (1,1,1)
v16.Update()
# Threshold level for seperating background/foreground pixels
maxthres=81
# Threshold the image stack
thres=vtk.vtkImageThreshold()
thres.SetInputConnection(v16.GetOutputPort())
thres.ThresholdByLower(0)
thres.ThresholdByUpper(maxthres)
# create ISO surface from thresholded images
iso=vtk.vtkImageMarchingCubes()
iso.SetInputConnection(thres.GetOutputPort())
# Have VTK calculate the Mass (volume) and surface area
Mass = vtk.vtkMassProperties()
Mass.SetInputConnection(iso.GetOutputPort())
Mass.Update()
# just print the results
print "Volume = ", Mass.GetVolume()
print "Surface = ", Mass.GetSurfaceArea()
Note
By testing both VTK-5.4.2 and VTK-5.2.1, I narrowed things down a bit and believe this behaviour was introduced between versions 5.0.4 and 5.2.1.
Update
It seems that in VTK-5.4.2, vtkTIFFReader ignores the x and y values set in the SetDataSpacing method. Instead vtkTIFFReader is calculating the x and y dataspacing from the resolution reported by the TIFF files.
A:
I have never heard of VTK before, but here it goes.
Good thing about opensource software is that you can check the source code directly. Better yet, if there's web-based version control browser, we can talk about it online like this.
Let's see vtkMassProperties in question. 5.0.4 uses r1.28 and 5.4.2 uses r1.30. Here's the diff between r1.28 and r.30. The part that may affect volume calculations are
vol[2] += (area * (double)u[2] * (double)zavg); // 5.0.4
vol[2] += (area * u[2] * zavg); // 5.4.2
and
kxyz[0] = (munc[0] + (wxyz/3.0) + ((wxy+wxz)/2.0)) /(double)(numCells); // 5.0.4
kxyz[0] = (munc[0] + (wxyz/3.0) + ((wxy+wxz)/2.0)) /numCells; // 5.4.2
but all changes look ok to me.
Next suspicious are the vtkMarchingCubes. Diff between r1.1.6.1 and 1.5.
self->UpdateProgress ((double) k / ((double) dims[2] - 1)); // 5.0.4
self->UpdateProgress (k / static_cast<double>(dims[2] - 1)); // 5.4.2
and
estimatedSize = (int) pow ((double) (dims[0] * dims[1] * dims[2]), .75); // 5.0.4
estimatedSize = static_cast<int>(
pow(static_cast<double>(dims[0]*dims[1]*dims[2]),0.75)); // 5.4.2
Again, they are fixing stuff on casting, but it looks ok.
Might as well see vtkImageThreshold too. Diff between r1.50 and r1.52.
lowerThreshold = (IT) inData->GetScalarTypeMin(); // 5.0.4
lowerThreshold = static_cast<IT>(inData->GetScalarTypeMin()); // 5.4.2
There are bunch more, but they are all casting stuff.
It gets more interesting with vtkTIFFReader. Diff between 1.51 and 1.63. As you can see by the difference in the revision numbers, there has been some development in this class compared to others. Here are the checkin comments:
ENH: Add an name for scalars. Visible in Paraview.
ENH: vtkDataArray now has a new superclass-vtkAbstractArray...
ENH: Set default number of sampels per pixel for files that are missing this meta data.
ENH: Read only what you need.
ENH: add multipage TIFF file support
ENH: print ivars
BUG: TIFF Reader did not properly account for RLE encoded data. Also, ExecuteInformation
overwrote user specified spacing and origin.
BUG: when reading beach.tif (from current CVS VTKData), the image would be loaded upside down.
STYLE: s/OrientationTypeSpecifiedFlag/OriginSpecifiedFlag/g and s/OrientationTypeSpecifiedFlag/SpacingSpecifiedFlag/g
BUG: Reader was not handling extents properly.
COMP: Fixing a warning.
COMP: Getting rid of a warning.
From the amount of changes that was made in vtkTIFFReader, I would guess that the difference in behavior is coming from there. For example, it may have started to recognize your Tiff as different format and changed the internal pixel values. Try printing out pixel values and see if there is any difference. If the pixel values have changed maxthres=81 may be too high.
|
Curious about differences in vtkMassProperties for VTK 5.04 and VTK 5.4.2
|
I have a small python VTK function that calculates the volume and surface area of an object embedded in a stack of TIFF images. To read the TIFF's into VTK, I have used vtkTIFFReader and processed the result using vtkImageThreshold. I then use vtkMassProperties to extract the volume and surface area of the object identified after thresholding.
With VTK-5.04, this function returns the correct value for a test stack (3902 pixels). However, using VTK-5.4.2 the same function returns a different value (422 pixels). Can someone explain this?
Code
def testvtk():
# read 36 TIFF images. Each TIFF is 27x27 pixels
v16=vtk.vtkTIFFReader()
v16.SetFilePrefix("d:/test/slice")
v16.SetDataExtent(0,27,0,27,1,36)
v16.SetFilePattern("%s%04d.tif")
v16.SetDataSpacing (1,1,1)
v16.Update()
# Threshold level for seperating background/foreground pixels
maxthres=81
# Threshold the image stack
thres=vtk.vtkImageThreshold()
thres.SetInputConnection(v16.GetOutputPort())
thres.ThresholdByLower(0)
thres.ThresholdByUpper(maxthres)
# create ISO surface from thresholded images
iso=vtk.vtkImageMarchingCubes()
iso.SetInputConnection(thres.GetOutputPort())
# Have VTK calculate the Mass (volume) and surface area
Mass = vtk.vtkMassProperties()
Mass.SetInputConnection(iso.GetOutputPort())
Mass.Update()
# just print the results
print "Volume = ", Mass.GetVolume()
print "Surface = ", Mass.GetSurfaceArea()
Note
By testing both VTK-5.4.2 and VTK-5.2.1, I narrowed things down a bit and believe this behaviour was introduced between versions 5.0.4 and 5.2.1.
Update
It seems that in VTK-5.4.2, vtkTIFFReader ignores the x and y values set in the SetDataSpacing method. Instead vtkTIFFReader is calculating the x and y dataspacing from the resolution reported by the TIFF files.
|
[
"I have never heard of VTK before, but here it goes.\nGood thing about opensource software is that you can check the source code directly. Better yet, if there's web-based version control browser, we can talk about it online like this.\nLet's see vtkMassProperties in question. 5.0.4 uses r1.28 and 5.4.2 uses r1.30. Here's the diff between r1.28 and r.30. The part that may affect volume calculations are\nvol[2] += (area * (double)u[2] * (double)zavg); // 5.0.4\nvol[2] += (area * u[2] * zavg); // 5.4.2\n\nand \nkxyz[0] = (munc[0] + (wxyz/3.0) + ((wxy+wxz)/2.0)) /(double)(numCells); // 5.0.4\nkxyz[0] = (munc[0] + (wxyz/3.0) + ((wxy+wxz)/2.0)) /numCells; // 5.4.2\n\nbut all changes look ok to me.\nNext suspicious are the vtkMarchingCubes. Diff between r1.1.6.1 and 1.5.\nself->UpdateProgress ((double) k / ((double) dims[2] - 1)); // 5.0.4\nself->UpdateProgress (k / static_cast<double>(dims[2] - 1)); // 5.4.2\n\nand \nestimatedSize = (int) pow ((double) (dims[0] * dims[1] * dims[2]), .75); // 5.0.4\nestimatedSize = static_cast<int>(\n pow(static_cast<double>(dims[0]*dims[1]*dims[2]),0.75)); // 5.4.2\n\nAgain, they are fixing stuff on casting, but it looks ok.\nMight as well see vtkImageThreshold too. Diff between r1.50 and r1.52.\nlowerThreshold = (IT) inData->GetScalarTypeMin(); // 5.0.4\nlowerThreshold = static_cast<IT>(inData->GetScalarTypeMin()); // 5.4.2\n\nThere are bunch more, but they are all casting stuff.\nIt gets more interesting with vtkTIFFReader. Diff between 1.51 and 1.63. As you can see by the difference in the revision numbers, there has been some development in this class compared to others. Here are the checkin comments:\n\nENH: Add an name for scalars. Visible in Paraview.\nENH: vtkDataArray now has a new superclass-vtkAbstractArray...\nENH: Set default number of sampels per pixel for files that are missing this meta data.\nENH: Read only what you need.\nENH: add multipage TIFF file support\nENH: print ivars\nBUG: TIFF Reader did not properly account for RLE encoded data. Also, ExecuteInformation\noverwrote user specified spacing and origin.\nBUG: when reading beach.tif (from current CVS VTKData), the image would be loaded upside down.\nSTYLE: s/OrientationTypeSpecifiedFlag/OriginSpecifiedFlag/g and s/OrientationTypeSpecifiedFlag/SpacingSpecifiedFlag/g\nBUG: Reader was not handling extents properly.\nCOMP: Fixing a warning.\nCOMP: Getting rid of a warning. \n\nFrom the amount of changes that was made in vtkTIFFReader, I would guess that the difference in behavior is coming from there. For example, it may have started to recognize your Tiff as different format and changed the internal pixel values. Try printing out pixel values and see if there is any difference. If the pixel values have changed maxthres=81 may be too high.\n"
] |
[
5
] |
[] |
[] |
[
"3d",
"python",
"vtk"
] |
stackoverflow_0000967468_3d_python_vtk.txt
|
Q:
Trie (Prefix Tree) in Python
I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)
If anything is unclear I'm very happy to clarify things.
I just implemented a Trie in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?
My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words stackoverflow, stackbase and stackbased, then the tree would look something like this:
[s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
Note that one can still think of the edges having one character (the first one of the child node).
Find-query is simple to implement.
Insertion is not hard, but somewhat more complex than I want.. :(
My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (Find(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)
k is identical to k'
k is a "proper" prefix of k'
k' is a "proper" prefix of k
k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.
It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?
Thanks :)
A:
At a glance, it sounds like you've implemented a Patricia Trie. This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion algorithm.
There's also another compression method you may want to look at: level compression. The idea behind path compression is to replace strings of single child nodes with a single super node that has a "skip" count. The idea behind level compression is to replace full or nearly full subtrees with a super node with a "degree" count that says how many digits of the key the node decodes. There's also a 3rd approach called width compression, but I'm afraid my memory fails me and I couldn't find a description of it with quick googling.
Level compression can shorten the average path considerably, but insertion and removal algorithms get quite complicated as they need to manage the trie nodes as similarly to dynamic arrays. For the right data sets, level compressed trees can be fast. From what I remember, they're the 2nd fastest approach for storing IP routing tables, the fastest is some sort of hash trie.
A:
I don't see anything wrong with your approach. If you're looking for a spike solution, perhaps the action taken in case 4 is actually feasible for the first three cases, IE find the common prefix to k and k' and rebuild the node with that in mind. If it happens that the keys were prefixes of one-another, the resulting trie will still be correct, only the implementation did a bit more work than it really had to. but then again, without any code to look at it's hard to say if this works in your case.
A:
Somewhat of a tangent, but if you are super worried about the number of nodes in your Trie, you may look at joining your word suffixes too. I'd take a look at the DAWG (Directed Acyclic Word Graph) idea: http://en.wikipedia.org/wiki/Directed_acyclic_word_graph
The downside of these is that they aren't very dynamic and creating them can be difficult. But, if your dictionary is static, they can be super compact.
A:
I have a question regarding your implementation. What is the level of granularity that you decide to split your strings on to make the prefix tree. You could split stack as either s,t,a,c,k or st,ta,ac,ck and many other ngrams of it. Most prefix tree implementations take into account an alphabet for the language, based on this alphabet, you do the splitting.
If you were building a prefix tree implementation for python then your alphabets would be things like def, : , if , else... etc
Choosing the right alphabet makes a huge difference in building efficient prefix trees. As for your answers, you could look for PERL packages on CPAN which do longest common substring computation using trie's. You may have some luck there as most of their implementation is pretty robust.
A:
Look at : Judy-arrays and the python interface at http://www.dalkescientific.com/Python/PyJudy.html
|
Trie (Prefix Tree) in Python
|
I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)
If anything is unclear I'm very happy to clarify things.
I just implemented a Trie in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem?
My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words stackoverflow, stackbase and stackbased, then the tree would look something like this:
[s]tack
[o]verflow ______/ \_______ [b]ase
\___ [d]
Note that one can still think of the edges having one character (the first one of the child node).
Find-query is simple to implement.
Insertion is not hard, but somewhat more complex than I want.. :(
My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (Find(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases:
(Let k be the key we want to insert, and k' be the key of the node, where the search ended)
k is identical to k'
k is a "proper" prefix of k'
k' is a "proper" prefix of k
k and k' share some common prefix, but none of the cases (1), (2) or (3) occur.
It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach?
Thanks :)
|
[
"At a glance, it sounds like you've implemented a Patricia Trie. This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion algorithm.\nThere's also another compression method you may want to look at: level compression. The idea behind path compression is to replace strings of single child nodes with a single super node that has a \"skip\" count. The idea behind level compression is to replace full or nearly full subtrees with a super node with a \"degree\" count that says how many digits of the key the node decodes. There's also a 3rd approach called width compression, but I'm afraid my memory fails me and I couldn't find a description of it with quick googling. \nLevel compression can shorten the average path considerably, but insertion and removal algorithms get quite complicated as they need to manage the trie nodes as similarly to dynamic arrays. For the right data sets, level compressed trees can be fast. From what I remember, they're the 2nd fastest approach for storing IP routing tables, the fastest is some sort of hash trie.\n",
"I don't see anything wrong with your approach. If you're looking for a spike solution, perhaps the action taken in case 4 is actually feasible for the first three cases, IE find the common prefix to k and k' and rebuild the node with that in mind. If it happens that the keys were prefixes of one-another, the resulting trie will still be correct, only the implementation did a bit more work than it really had to. but then again, without any code to look at it's hard to say if this works in your case.\n",
"Somewhat of a tangent, but if you are super worried about the number of nodes in your Trie, you may look at joining your word suffixes too. I'd take a look at the DAWG (Directed Acyclic Word Graph) idea: http://en.wikipedia.org/wiki/Directed_acyclic_word_graph\nThe downside of these is that they aren't very dynamic and creating them can be difficult. But, if your dictionary is static, they can be super compact.\n",
"I have a question regarding your implementation. What is the level of granularity that you decide to split your strings on to make the prefix tree. You could split stack as either s,t,a,c,k or st,ta,ac,ck and many other ngrams of it. Most prefix tree implementations take into account an alphabet for the language, based on this alphabet, you do the splitting. \nIf you were building a prefix tree implementation for python then your alphabets would be things like def, : , if , else... etc \nChoosing the right alphabet makes a huge difference in building efficient prefix trees. As for your answers, you could look for PERL packages on CPAN which do longest common substring computation using trie's. You may have some luck there as most of their implementation is pretty robust. \n",
"Look at : Judy-arrays and the python interface at http://www.dalkescientific.com/Python/PyJudy.html\n"
] |
[
19,
2,
2,
2,
1
] |
[] |
[] |
[
"algorithm",
"python",
"trie"
] |
stackoverflow_0000960963_algorithm_python_trie.txt
|
Q:
Experiences of creating Social Network site in Django
I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility.
Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available.
I would like to hear what kind of experiences you may have had with Django in creating social network type sites. Any experiences in using any of the Django powered social network "frameworks" would also be welcome.
A:
If you're interested in creating a social-network site in Django, you should definitely investigate Pinax. This is a project that integrates a number of apps that are useful for creating this sort of site - friends, messaging, invitations, registration, etc. They're mostly very high quality.
|
Experiences of creating Social Network site in Django
|
I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility.
Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available.
I would like to hear what kind of experiences you may have had with Django in creating social network type sites. Any experiences in using any of the Django powered social network "frameworks" would also be welcome.
|
[
"If you're interested in creating a social-network site in Django, you should definitely investigate Pinax. This is a project that integrates a number of apps that are useful for creating this sort of site - friends, messaging, invitations, registration, etc. They're mostly very high quality.\n"
] |
[
27
] |
[
"Are you saying that a random survey of some posted Django apps (not Django itself) reveals that some people post code that doesn't meet your standards of quality?\nIsn't that universally true of all code posted everywhere on the internet?\nA random survey of any code in any language for any framework will turn up quality issues.\nWhat's your real question? Do you think this phenomena will somehow rub off on you and taint your code with their lack of quality?\n"
] |
[
-1
] |
[
"django",
"python"
] |
stackoverflow_0000986594_django_python.txt
|
Q:
how to take a matrix in python?
i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!!
A:
I think you will need to use numpy to hold such a big matrix efficiently , not just computation. You have ~5e6 items of 4/8 bytes means 20/40 Mb in pure C already, several times of that in python without an efficient data structure (a list of rows, each row a list).
Now, concerning your question:
import numpy as np
a = np.empty((1234, 5678), dtype=np.int)
a[:] = np.linspace(1, 5678, 5678)
You first create an array of the requested size, with type int (I assume you know you want 4 bytes integer, which is what np.int will give you on most platforms). The 3rd line uses broadcasting so that each row (a[0], a[1], ... a[1233]) is assigned the values of the np.linspace line (which gives you an array of [1, ....., 5678]). If you want F storage, that is column major:
a = np.empty((1234, 4567), dtype=np.int, order='F')
...
The matrix a will takes only a tiny amount of memory more than an array in C, and for computation at least, the indexing capabilities of arrays are much better than python lists.
A nitpick: numeric is the name of the old numerical package for python - the recommended name is numpy.
A:
Or just use Numerical Python if you want to do some mathematical stuff on matrix too (like multiplication, ...). If they use row major order for the matrix layout in memory I can't tell you but it gets coverd in their documentation
A:
Here's a forum post that has some code examples of what you are trying to achieve.
|
how to take a matrix in python?
|
i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!!
|
[
"I think you will need to use numpy to hold such a big matrix efficiently , not just computation. You have ~5e6 items of 4/8 bytes means 20/40 Mb in pure C already, several times of that in python without an efficient data structure (a list of rows, each row a list).\nNow, concerning your question:\nimport numpy as np\na = np.empty((1234, 5678), dtype=np.int)\na[:] = np.linspace(1, 5678, 5678)\n\nYou first create an array of the requested size, with type int (I assume you know you want 4 bytes integer, which is what np.int will give you on most platforms). The 3rd line uses broadcasting so that each row (a[0], a[1], ... a[1233]) is assigned the values of the np.linspace line (which gives you an array of [1, ....., 5678]). If you want F storage, that is column major:\na = np.empty((1234, 4567), dtype=np.int, order='F')\n...\n\nThe matrix a will takes only a tiny amount of memory more than an array in C, and for computation at least, the indexing capabilities of arrays are much better than python lists.\nA nitpick: numeric is the name of the old numerical package for python - the recommended name is numpy.\n",
"Or just use Numerical Python if you want to do some mathematical stuff on matrix too (like multiplication, ...). If they use row major order for the matrix layout in memory I can't tell you but it gets coverd in their documentation\n",
"Here's a forum post that has some code examples of what you are trying to achieve.\n"
] |
[
6,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000990469_python.txt
|
Q:
Using doctest "result parser" within unit-tests in Python?
I recently faced a problem about combining unit tests and doctests in Python. I worked around this problem in other way, but I still have question about it.
Python's doctest module parses docstrings in a module and run commands following ">>> " at the beginning of each line and compare the output of it and those in docstrings.
I wonder that I could use that comparison method implemented by doctest module when I want. I know that it's possible add doctest to test suite as a test case, but here I want to do it inside a single test case.
It is something like this:
class MyTest(TestCase):
def testIt(self):
# some codes like self.assertEqual(...)
output = StringIO()
with StdoutCollector(output):
# do something that uses stdout
# I want something like this:
doctest.compare_result(output.getvalue(), 'expected output')
# do more things
Because doctest uses some heuristics to compare the outputs like ellipsis.
Would somebody give an idea or suggestions?
A:
See doctest.OutputChecker.check_output()
|
Using doctest "result parser" within unit-tests in Python?
|
I recently faced a problem about combining unit tests and doctests in Python. I worked around this problem in other way, but I still have question about it.
Python's doctest module parses docstrings in a module and run commands following ">>> " at the beginning of each line and compare the output of it and those in docstrings.
I wonder that I could use that comparison method implemented by doctest module when I want. I know that it's possible add doctest to test suite as a test case, but here I want to do it inside a single test case.
It is something like this:
class MyTest(TestCase):
def testIt(self):
# some codes like self.assertEqual(...)
output = StringIO()
with StdoutCollector(output):
# do something that uses stdout
# I want something like this:
doctest.compare_result(output.getvalue(), 'expected output')
# do more things
Because doctest uses some heuristics to compare the outputs like ellipsis.
Would somebody give an idea or suggestions?
|
[
"See doctest.OutputChecker.check_output()\n"
] |
[
2
] |
[] |
[] |
[
"doctest",
"documentation",
"python",
"testing",
"unit_testing"
] |
stackoverflow_0000990500_doctest_documentation_python_testing_unit_testing.txt
|
Q:
How to write a proxy server in Python?
I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server.
I study programming. How can I do this in Python?
A:
Good example below on how to do this without the overhead of a framework.
http://www.warriorhut.org/whatwg/websocket-proxy.py
A:
Look at the Twisted framework, particularly Twisted Web. It's all freely available under MIT, so you can build off and/or modify it.
See also Python Twisted Examples.
A:
While Twisted, as recommended by @Matthew, is awesome, easier to learn, understand and modify might be this tiny example -- far away from the "production quality" and scalability that Twisted can offer, but, you could start with it to understand the issues better.
For a wide variety of open-source HTTP proxies written in Python, I recommend this list -- that reference has proxies for all tastes built on top of threading, Twisted, asyncore, and other technologies yet!
A:
Have a look at Tiny HTTP Proxy (1) and of course the related docs (2). It's basically running a server and handling requests.
(1) http://www.oki-osk.jp/esc/python/proxy/
(2) http://docs.python.org/library/basehttpserver.html
A:
WSGI may be a little easier to get your head around. So I'll throw paste.proxy out there either as something to build on or as a reference.
http://pythonpaste.org/modules/proxy.html
A:
http://twistedmatrix.com/
Great library for any networking needs.
|
How to write a proxy server in Python?
|
I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server.
I study programming. How can I do this in Python?
|
[
"Good example below on how to do this without the overhead of a framework.\nhttp://www.warriorhut.org/whatwg/websocket-proxy.py\n",
"Look at the Twisted framework, particularly Twisted Web. It's all freely available under MIT, so you can build off and/or modify it.\nSee also Python Twisted Examples.\n",
"While Twisted, as recommended by @Matthew, is awesome, easier to learn, understand and modify might be this tiny example -- far away from the \"production quality\" and scalability that Twisted can offer, but, you could start with it to understand the issues better.\nFor a wide variety of open-source HTTP proxies written in Python, I recommend this list -- that reference has proxies for all tastes built on top of threading, Twisted, asyncore, and other technologies yet!\n",
"Have a look at Tiny HTTP Proxy (1) and of course the related docs (2). It's basically running a server and handling requests.\n(1) http://www.oki-osk.jp/esc/python/proxy/\n(2) http://docs.python.org/library/basehttpserver.html\n",
"WSGI may be a little easier to get your head around. So I'll throw paste.proxy out there either as something to build on or as a reference.\nhttp://pythonpaste.org/modules/proxy.html\n",
"http://twistedmatrix.com/ \nGreat library for any networking needs.\n"
] |
[
14,
13,
7,
5,
3,
2
] |
[] |
[] |
[
"http_headers",
"proxy",
"python"
] |
stackoverflow_0000989739_http_headers_proxy_python.txt
|
Q:
How to find out the arity of a method in Python
I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:
def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # => 1
I'd like to be able to achieve this:
Foo().bar.arity() # => 1
Update: Right now the above function fails with built-in types, any help on this would also be appreciated:
# Traceback (most recent call last):
# File "bla.py", line 10, in <module>
# print arity('foo', 'split') # =>
# File "bla.py", line 3, in arity
# return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
# AttributeError: 'method_descriptor' object has no attribute 'func_co
A:
Module inspect from Python's standard library is your friend -- see the online docs! inspect.getargspec(func) returns a tuple with four items, args, varargs, varkw, defaults: len(args) is the "primary arity", but arity can be anything from that to infinity if you have varargs and/or varkw not None, and some arguments may be omitted (and defaulted) if defaults is not None. How you turn that into a single number, beats me, but presumably you have your ideas in the matter!-)
This applies to Python-coded functions, but not to C-coded ones. Nothing in the Python C API lets C-coded functions (including built-ins) expose their signature for introspection, except via their docstring (or optionally via annotations in Python 3); so, you will need to fall back to docstring parsing as a last ditch if other approaches fail (of course, the docstring might be missing too, in which case the function will remain a mystery).
A:
Use a decorator to decorate methods e.g.
def arity(method):
def _arity():
return method.func_code.co_argcount - 1 # remove self
method.arity = _arity
return method
class Foo:
@arity
def bar(self, bla):
pass
print Foo().bar.arity()
Now implement _arity function to calculate arg count based on your needs
A:
Ideally, you'd want to monkey-patch the arity function as a method on Python functors. Here's how:
def arity(self, method):
return getattr(self.__class__, method).func_code.co_argcount - 1
functor = arity.__class__
functor.arity = arity
arity.__class__.arity = arity
But, CPython implements functors in C, you can't actually modify them. This may work in PyPy, though.
That's all assuming your arity() function is correct. What about variadic functions? Do you even want an answer then?
A:
This is the only way that I can think of that should be 100% effective (at least with regard to whether the function is user-defined or written in C) at determining a function's (minimum) arity. However, you should be sure that this function won't cause any side-effects and that it won't throw a TypeError:
from functools import partial
def arity(func):
pfunc = func
i = 0
while True:
try:
pfunc()
except TypeError:
pfunc = partial(pfunc, '')
i += 1
else:
return i
def foo(x, y, z):
pass
def varfoo(*args):
pass
class klass(object):
def klassfoo(self):
pass
print arity(foo)
print arity(varfoo)
x = klass()
print arity(x.klassfoo)
# output
# 3
# 0
# 0
As you can see, this will determine the minimum arity if a function takes a variable amount of arguments. It also won't take into account the self or cls argument of a class or instance method.
To be totally honest though, I wouldn't use this function in a production environment unless I knew exactly which functions would be called though as there is a lot of room for stupid errors. This may defeat the purpose.
A:
here is another attempt using metaclass, as i use python 2.5, but with 2.6 you could easily decorate the class
metaclass can also be defined at module level, so it works for all classes
from types import FunctionType
def arity(unboundmethod):
def _arity():
return unboundmethod.func_code.co_argcount - 1 # remove self
unboundmethod.arity = _arity
return unboundmethod
class AirtyMetaclass(type):
def __new__(meta, name, bases, attrs):
newAttrs = {}
for attributeName, attribute in attrs.items():
if type(attribute) == FunctionType:
attribute = arity(attribute)
newAttrs[attributeName] = attribute
klass = type.__new__(meta, name, bases, newAttrs)
return klass
class Foo:
__metaclass__ = AirtyMetaclass
def bar(self, bla):
pass
print Foo().bar.arity()
|
How to find out the arity of a method in Python
|
I'd like to find out the arity of a method in Python (the number of parameters that it receives).
Right now I'm doing this:
def arity(obj, method):
return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
class Foo:
def bar(self, bla):
pass
arity(Foo(), "bar") # => 1
I'd like to be able to achieve this:
Foo().bar.arity() # => 1
Update: Right now the above function fails with built-in types, any help on this would also be appreciated:
# Traceback (most recent call last):
# File "bla.py", line 10, in <module>
# print arity('foo', 'split') # =>
# File "bla.py", line 3, in arity
# return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self
# AttributeError: 'method_descriptor' object has no attribute 'func_co
|
[
"Module inspect from Python's standard library is your friend -- see the online docs! inspect.getargspec(func) returns a tuple with four items, args, varargs, varkw, defaults: len(args) is the \"primary arity\", but arity can be anything from that to infinity if you have varargs and/or varkw not None, and some arguments may be omitted (and defaulted) if defaults is not None. How you turn that into a single number, beats me, but presumably you have your ideas in the matter!-)\nThis applies to Python-coded functions, but not to C-coded ones. Nothing in the Python C API lets C-coded functions (including built-ins) expose their signature for introspection, except via their docstring (or optionally via annotations in Python 3); so, you will need to fall back to docstring parsing as a last ditch if other approaches fail (of course, the docstring might be missing too, in which case the function will remain a mystery).\n",
"Use a decorator to decorate methods e.g.\ndef arity(method):\n\n def _arity():\n return method.func_code.co_argcount - 1 # remove self\n\n method.arity = _arity\n\n return method\n\nclass Foo:\n @arity\n def bar(self, bla):\n pass\n\nprint Foo().bar.arity()\n\nNow implement _arity function to calculate arg count based on your needs\n",
"Ideally, you'd want to monkey-patch the arity function as a method on Python functors. Here's how:\ndef arity(self, method):\n return getattr(self.__class__, method).func_code.co_argcount - 1\n\nfunctor = arity.__class__\nfunctor.arity = arity\narity.__class__.arity = arity\n\nBut, CPython implements functors in C, you can't actually modify them. This may work in PyPy, though.\nThat's all assuming your arity() function is correct. What about variadic functions? Do you even want an answer then?\n",
"This is the only way that I can think of that should be 100% effective (at least with regard to whether the function is user-defined or written in C) at determining a function's (minimum) arity. However, you should be sure that this function won't cause any side-effects and that it won't throw a TypeError:\nfrom functools import partial\n\ndef arity(func):\n pfunc = func\n i = 0\n while True:\n try:\n pfunc()\n except TypeError:\n pfunc = partial(pfunc, '')\n i += 1\n else:\n return i\n\ndef foo(x, y, z):\n pass\n\ndef varfoo(*args):\n pass\n\nclass klass(object):\n def klassfoo(self):\n pass\n\nprint arity(foo)\nprint arity(varfoo)\n\nx = klass()\nprint arity(x.klassfoo)\n\n# output\n# 3\n# 0\n# 0\n\nAs you can see, this will determine the minimum arity if a function takes a variable amount of arguments. It also won't take into account the self or cls argument of a class or instance method.\nTo be totally honest though, I wouldn't use this function in a production environment unless I knew exactly which functions would be called though as there is a lot of room for stupid errors. This may defeat the purpose.\n",
"here is another attempt using metaclass, as i use python 2.5, but with 2.6 you could easily decorate the class\nmetaclass can also be defined at module level, so it works for all classes\nfrom types import FunctionType\n\ndef arity(unboundmethod):\n def _arity():\n return unboundmethod.func_code.co_argcount - 1 # remove self\n unboundmethod.arity = _arity\n\n return unboundmethod\n\nclass AirtyMetaclass(type):\n def __new__(meta, name, bases, attrs):\n newAttrs = {}\n for attributeName, attribute in attrs.items():\n if type(attribute) == FunctionType:\n attribute = arity(attribute)\n\n newAttrs[attributeName] = attribute\n\n klass = type.__new__(meta, name, bases, newAttrs)\n\n return klass\n\nclass Foo:\n __metaclass__ = AirtyMetaclass\n def bar(self, bla):\n pass\n\nprint Foo().bar.arity()\n\n"
] |
[
51,
6,
2,
2,
0
] |
[] |
[] |
[
"metaprogramming",
"python"
] |
stackoverflow_0000990016_metaprogramming_python.txt
|
Q:
String reversal in Python
I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?
I am not able to convert the integer into a list so not able to apply the reverse function.
A:
You can use the slicing operator to reverse a string:
s = "hello, world"
s = s[::-1]
print s # prints "dlrow ,olleh"
To convert an integer to a string, reverse it, and convert it back to an integer, you can do:
x = 314159
x = int(str(x)[::-1])
print x # prints 951413
A:
Code:
>>> n = 1234
>>> print str(n)[::-1]
4321
A:
>>> int(''.join(reversed(str(12345))))
54321
|
String reversal in Python
|
I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?
I am not able to convert the integer into a list so not able to apply the reverse function.
|
[
"You can use the slicing operator to reverse a string:\ns = \"hello, world\"\ns = s[::-1]\nprint s # prints \"dlrow ,olleh\"\n\nTo convert an integer to a string, reverse it, and convert it back to an integer, you can do:\nx = 314159\nx = int(str(x)[::-1])\nprint x # prints 951413\n\n",
"Code:\n>>> n = 1234\n>>> print str(n)[::-1]\n4321\n\n",
">>> int(''.join(reversed(str(12345))))\n54321\n\n"
] |
[
30,
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000990934_python.txt
|
Q:
"Pythonic" equivalent for handling switch and multiple string compares
Alright, so my title sucked. An example works better:
input = 'check yahoo.com'
I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it:
if len(input) > 0:
a = input.split(' ')
if a[0] == 'check':
if len(a) > 1:
do_check(a[1])
elif a[0] == 'search':
if len(a) > 1:
do_search(a[1])
I like Python because it makes normally complicated things into rather simple things. I'm not too experienced with it, and I am fairly sure there's a much better way to do these things... some way more pythonic. I've seen some examples of people replacing switch statements with dicts and lambda functions, while other people simply recommended if..else nests.
A:
dispatch = {
'check': do_check,
'search': do_search,
}
cmd, _, arg = input.partition(' ')
if cmd in dispatch:
dispatch[cmd](arg)
else:
do_default(cmd, arg)
A:
I am fairly sure there's a much better way to do these things... some way more pythonic.
Not really. You code is simple, clear, obvious and English-like.
I've seen some examples of people replacing switch statements with dicts and lambda functions,
Yes, you've seen them and they're not clear, obvious or English-like. They exist because some people like to wring their hands over the switch statement.
while other people simply recommended if..else nests.
Correct. They work. They're simple, clear, ...
Your code is good. Leave it alone. Move on.
A:
This lets you avoid giving each command name twice; function names are used almost directly as command names.
class CommandFunctions:
def c_check(self, arg):
print "checking", arg
def c_search(self, arg):
print "searching for", arg
def c_compare(self, arg1, arg2):
print "comparing", arg1, "with", arg2
def execute(self, line):
words = line.split(' ')
fn = getattr(self, 'c_' + words[0], None)
if fn is None:
import sys
sys.stderr.write('error: no such command "%s"\n' % words[0])
return
fn(*words[1:])
cf = CommandFunctions()
import sys
for line in sys.stdin:
cf.execute(line.strip())
A:
If you're looking for a one liner 'pythonic' approach to this you can use this:
def do_check(x): print 'checking for:', x
def do_search(x): print 'searching for:', x
input = 'check yahoo.com'
{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])
# checking for: yahoo.com
input = 'search google.com'
{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])
# searching for: google.com
input = 'foo bar.com'
{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])
# searching for: bar.com
A:
Disregard, I just realized that my answer was similar to one of the other answers - and apparently there's no delete key :)
A:
Variation on @MizardX's answer:
from collections import defaultdict
dispatch = defaultdict(do_default, check=do_check, search=do_search)
cmd, _, arg = input.partition(' ')
dispatch[cmd](arg)
|
"Pythonic" equivalent for handling switch and multiple string compares
|
Alright, so my title sucked. An example works better:
input = 'check yahoo.com'
I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it:
if len(input) > 0:
a = input.split(' ')
if a[0] == 'check':
if len(a) > 1:
do_check(a[1])
elif a[0] == 'search':
if len(a) > 1:
do_search(a[1])
I like Python because it makes normally complicated things into rather simple things. I'm not too experienced with it, and I am fairly sure there's a much better way to do these things... some way more pythonic. I've seen some examples of people replacing switch statements with dicts and lambda functions, while other people simply recommended if..else nests.
|
[
"dispatch = {\n 'check': do_check,\n 'search': do_search,\n}\ncmd, _, arg = input.partition(' ')\nif cmd in dispatch:\n dispatch[cmd](arg)\nelse:\n do_default(cmd, arg)\n\n",
"\nI am fairly sure there's a much better way to do these things... some way more pythonic.\n\nNot really. You code is simple, clear, obvious and English-like.\n\nI've seen some examples of people replacing switch statements with dicts and lambda functions,\n\nYes, you've seen them and they're not clear, obvious or English-like. They exist because some people like to wring their hands over the switch statement.\n\nwhile other people simply recommended if..else nests.\n\nCorrect. They work. They're simple, clear, ...\nYour code is good. Leave it alone. Move on.\n",
"This lets you avoid giving each command name twice; function names are used almost directly as command names.\nclass CommandFunctions:\n def c_check(self, arg):\n print \"checking\", arg\n\n def c_search(self, arg):\n print \"searching for\", arg\n\n def c_compare(self, arg1, arg2):\n print \"comparing\", arg1, \"with\", arg2\n\n def execute(self, line):\n words = line.split(' ')\n fn = getattr(self, 'c_' + words[0], None)\n if fn is None:\n import sys\n sys.stderr.write('error: no such command \"%s\"\\n' % words[0])\n return\n fn(*words[1:])\n\ncf = CommandFunctions()\nimport sys\nfor line in sys.stdin:\n cf.execute(line.strip())\n\n",
"If you're looking for a one liner 'pythonic' approach to this you can use this:\n\ndef do_check(x): print 'checking for:', x\ndef do_search(x): print 'searching for:', x\n\ninput = 'check yahoo.com'\n{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])\n# checking for: yahoo.com\n\ninput = 'search google.com'\n{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])\n# searching for: google.com\n\ninput = 'foo bar.com'\n{'check': do_check}.get(input.split()[0], do_search)(input.split()[1])\n# searching for: bar.com\n\n",
"Disregard, I just realized that my answer was similar to one of the other answers - and apparently there's no delete key :)\n",
"Variation on @MizardX's answer:\nfrom collections import defaultdict\n\ndispatch = defaultdict(do_default, check=do_check, search=do_search)\ncmd, _, arg = input.partition(' ')\ndispatch[cmd](arg)\n\n"
] |
[
31,
4,
3,
0,
0,
0
] |
[] |
[] |
[
"conditional",
"python"
] |
stackoverflow_0000641469_conditional_python.txt
|
Q:
Deleting files by type in Python on Windows
I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.
Say the directory is \myfolder
I want to delete all files that are .config files, but nothing to the other ones.
How would I do this?
Thanks Kindly
A:
Use the glob module:
import os
from glob import glob
for f in glob ('myfolder/*.config'):
os.unlink (f)
A:
I would do something like the following:
import os
files = os.listdir("myfolder")
for f in files:
if not os.path.isdir(f) and ".config" in f:
os.remove(f)
It lists the files in a directory and if it's not a directory and the filename has ".config" anywhere in it, delete it. You'll either need to be in the same directory as myfolder, or give it the full path to the directory. If you need to do this recursively, I would use the os.walk function.
A:
Here ya go:
import os
# Return all files in dir, and all its subdirectories, ending in pattern
def gen_files(dir, pattern):
for dirname, subdirs, files in os.walk(dir):
for f in files:
if f.endswith(pattern):
yield os.path.join(dirname, f)
# Remove all files in the current dir matching *.config
for f in gen_files('.', '.config'):
os.remove(f)
Note also that gen_files can be easily rewritten to accept a tuple of patterns, since str.endswith accepts a tuple
|
Deleting files by type in Python on Windows
|
I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.
Say the directory is \myfolder
I want to delete all files that are .config files, but nothing to the other ones.
How would I do this?
Thanks Kindly
|
[
"Use the glob module:\nimport os\nfrom glob import glob\n\nfor f in glob ('myfolder/*.config'):\n os.unlink (f)\n\n",
"I would do something like the following:\nimport os\nfiles = os.listdir(\"myfolder\")\nfor f in files:\n if not os.path.isdir(f) and \".config\" in f:\n os.remove(f)\n\nIt lists the files in a directory and if it's not a directory and the filename has \".config\" anywhere in it, delete it. You'll either need to be in the same directory as myfolder, or give it the full path to the directory. If you need to do this recursively, I would use the os.walk function. \n",
"Here ya go:\nimport os\n\n# Return all files in dir, and all its subdirectories, ending in pattern\ndef gen_files(dir, pattern):\n for dirname, subdirs, files in os.walk(dir):\n for f in files:\n if f.endswith(pattern):\n yield os.path.join(dirname, f)\n\n\n# Remove all files in the current dir matching *.config\nfor f in gen_files('.', '.config'):\n os.remove(f)\n\nNote also that gen_files can be easily rewritten to accept a tuple of patterns, since str.endswith accepts a tuple\n"
] |
[
17,
5,
1
] |
[] |
[] |
[
"file",
"python"
] |
stackoverflow_0000991279_file_python.txt
|
Q:
re.search() breaks for key in form.keys() loop
Perhaps I am just crazy or missing something really basic. Why would this happen?
If I use this url
index.cgi?mode=pos&pos_mode=checkout&0_name=Shampoo&0_type=Product&0_price=4.50&0_qty=1&0_total=4.50
which runs this code
form = cgi.FieldStorage()
for key in form.keys()
print key
if re.search("name", key):
print "Found name."
The result prints
mode
If I remove the re.search() it prints all the keys. Why?
I searched stackoverflow and google before I posted but I didn't come up with anything. Thanks in advance.
A:
Are you getting an exception? Check your server logs. Have you done:
import re
at the top of the script? Try wrapping the code in try / except.
A:
Perhaps you get an error? Try checking types of all keys or anything you suspect could be wrong.
|
re.search() breaks for key in form.keys() loop
|
Perhaps I am just crazy or missing something really basic. Why would this happen?
If I use this url
index.cgi?mode=pos&pos_mode=checkout&0_name=Shampoo&0_type=Product&0_price=4.50&0_qty=1&0_total=4.50
which runs this code
form = cgi.FieldStorage()
for key in form.keys()
print key
if re.search("name", key):
print "Found name."
The result prints
mode
If I remove the re.search() it prints all the keys. Why?
I searched stackoverflow and google before I posted but I didn't come up with anything. Thanks in advance.
|
[
"Are you getting an exception? Check your server logs. Have you done:\nimport re\n\nat the top of the script? Try wrapping the code in try / except.\n",
"Perhaps you get an error? Try checking types of all keys or anything you suspect could be wrong.\n"
] |
[
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000991351_python.txt
|
Q:
an error in taking an input in python
111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number
A:
It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using repr (or something that invokes repr, like printing a list) that it gets the 'L'.
What exactly is going wrong?
Edit: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.
A:
It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:
a=(0.5 + 2.5*(k %2))*k + k % 2
This implicitly results in a floating point number for the value of (0.5 + 2.5*(k %2))*k. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:
a=(1 + 5*(k %2))*k//2 + k % 2
A:
As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following page.
When I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:
>>> a = 111111111111111111111111111111111111111
>>> a + 1
111111111111111111111111111111111111112L
>>> str(a)
'111111111111111111111111111111111111111'
>>> int(a)
111111111111111111111111111111111111111L
I did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have unlimited precision. So cool!
A:
Another way to avoid numerical errors in python is to use Decimal type instead of standard float.
Please refer to official docs
A:
Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.
|
an error in taking an input in python
|
111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number
|
[
"It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using repr (or something that invokes repr, like printing a list) that it gets the 'L'.\nWhat exactly is going wrong?\nEdit: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.\n",
"It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:\na=(0.5 + 2.5*(k %2))*k + k % 2\n\nThis implicitly results in a floating point number for the value of (0.5 + 2.5*(k %2))*k. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:\na=(1 + 5*(k %2))*k//2 + k % 2\n\n",
"As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following page.\nWhen I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:\n>>> a = 111111111111111111111111111111111111111\n>>> a + 1\n111111111111111111111111111111111111112L\n>>> str(a)\n'111111111111111111111111111111111111111'\n>>> int(a)\n111111111111111111111111111111111111111L\n\nI did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have unlimited precision. So cool!\n",
"Another way to avoid numerical errors in python is to use Decimal type instead of standard float. \nPlease refer to official docs\n",
"Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.\n"
] |
[
3,
3,
2,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000991220_python.txt
|
Q:
How to programatically combine two aac files into one?
I'm looking for a cat for aac music files (the stuff iTunes uses).
Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.
I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.
I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net...
A:
I created a freeware program called "Chapter and Verse" to concatenate m4a (AAC) files into a single m4b audiobook file with chapter marks and metadata.
If you have already ripped the CD's to AAC using itunes (which you say you have) then the rest is easy with my software. I wrote it for this exact reason and scenario. You can download it from www.lodensoftware.com
After trying to work with SlideShow Assembler, the QT SDK and a bunch of other command line tools, I ended up building my own application based on the publicly available MP4v2 library. The concatenating of files and adding of chapters is done using the MP4v2 library.
There are quite a few nuances in building an audiobook properly formatted for the iPod. The information is hard to find. Working with Apple documentation and open libraries has its own challenges as well.
Best of Luck.
A:
Not programming related (well, kinda.)
iTunes already has functionality to rip as a single track (e.g. an audiobook.) Check this out: http://www.ehow.com/how_2108906_merge-cd-single-track-itunes.html
That fixes your immediate problem, but I guess people can keep discussing how to do it programatically.
A:
The most powerful Python audio manipulation module out there seems to be Python Audio Tools. The download comes with CLI tools that would probably do everything you'd want to do, even ripping, so you can even get by with shell scripting the whole thing. The module itself is also pretty powerful and has a handy set of functions to manipulate audio files. If you want to stick with writing everything in python, you can possibly learn enough to do what you want to do after studying their CLI source code. Specifically they have a tool that just does audio file cat in any codec. (They do depend on FAAC/FAAD2 for AAC support, but that'd be true for every library you'll find)
A:
I haven't seen an aac codec library for python, but you could use wav files as an intermediary format.
You can pull the tracks off the cd as wav files, and then use the wave module to concatenate them into one large file, which could then be converted by itunes to aac. This may increase your processing time considerably because of the size of the data, but it would be fairly easy, and you don't need any external libraries.
|
How to programatically combine two aac files into one?
|
I'm looking for a cat for aac music files (the stuff iTunes uses).
Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.
I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.
I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net...
|
[
"I created a freeware program called \"Chapter and Verse\" to concatenate m4a (AAC) files into a single m4b audiobook file with chapter marks and metadata.\nIf you have already ripped the CD's to AAC using itunes (which you say you have) then the rest is easy with my software. I wrote it for this exact reason and scenario. You can download it from www.lodensoftware.com\nAfter trying to work with SlideShow Assembler, the QT SDK and a bunch of other command line tools, I ended up building my own application based on the publicly available MP4v2 library. The concatenating of files and adding of chapters is done using the MP4v2 library.\nThere are quite a few nuances in building an audiobook properly formatted for the iPod. The information is hard to find. Working with Apple documentation and open libraries has its own challenges as well.\nBest of Luck.\n",
"Not programming related (well, kinda.)\niTunes already has functionality to rip as a single track (e.g. an audiobook.) Check this out: http://www.ehow.com/how_2108906_merge-cd-single-track-itunes.html\nThat fixes your immediate problem, but I guess people can keep discussing how to do it programatically.\n",
"The most powerful Python audio manipulation module out there seems to be Python Audio Tools. The download comes with CLI tools that would probably do everything you'd want to do, even ripping, so you can even get by with shell scripting the whole thing. The module itself is also pretty powerful and has a handy set of functions to manipulate audio files. If you want to stick with writing everything in python, you can possibly learn enough to do what you want to do after studying their CLI source code. Specifically they have a tool that just does audio file cat in any codec. (They do depend on FAAC/FAAD2 for AAC support, but that'd be true for every library you'll find)\n",
"I haven't seen an aac codec library for python, but you could use wav files as an intermediary format.\nYou can pull the tracks off the cd as wav files, and then use the wave module to concatenate them into one large file, which could then be converted by itunes to aac. This may increase your processing time considerably because of the size of the data, but it would be fairly easy, and you don't need any external libraries.\n"
] |
[
5,
2,
1,
0
] |
[] |
[] |
[
"aac",
"itunes",
"python",
"scripting",
"windows"
] |
stackoverflow_0000836842_aac_itunes_python_scripting_windows.txt
|
Q:
Very simple Python script, puzzling behaviour
first of all, I'm not a programmer, so the answer to this might be completely obvious to someone more experienced.
I was playing around with python(2.5) to solve some probability puzzle, however I kept getting results which were way off from the mark I thought they should be. So after some experimenting, I managed to identify the behaviour which was causing the problem.
The script which seemed to isolate the weird behaviour is this:
import random
random.seed()
reps = 1000000
sub = [0]*10
hits = 0
first = random.randint(0,9)
while True:
second = random.randint(0,9)
if second != first:
break
sub[first] = 1
sub[second] = 1
sub[random.randint(0,9)] = 1
for i in range(1,reps):
first = random.randint(0,9)
while True:
second = random.randint(0,9)
if second != first:
break
if ((sub[first]) or (sub[second])):
hits = hits + 1
print "result: ", hits*1.0/reps*100.0
Now, this is not the problem I was initially trying to solve and the result for this script should be 34/90 or around 37.7 which is simple enough combinatorics. Sometimes, the script does give that result, however more often it gives 53.4, which seems to make no sense.
This is pretty much just idle curiosity as to why exactly this script behaves like it does.
A:
BTW, for the best way to "generate 3 different randomly distributed integers between 0 and 9 included", I heartily recommend a, b, c = random.sample(xrange(10), 3) [[s/xrange/range/ in Python 3.0]] rather than the while loops you're using.
A:
The result depends on whether line 13:
sub[random.randint(0,9)] = 1
hits the same index as one of lines 11 or 12:
sub[first] = 1
sub[second] = 1
You protect second from being the same as first, but you don't protect that third entry from being the same as one of first or second.
|
Very simple Python script, puzzling behaviour
|
first of all, I'm not a programmer, so the answer to this might be completely obvious to someone more experienced.
I was playing around with python(2.5) to solve some probability puzzle, however I kept getting results which were way off from the mark I thought they should be. So after some experimenting, I managed to identify the behaviour which was causing the problem.
The script which seemed to isolate the weird behaviour is this:
import random
random.seed()
reps = 1000000
sub = [0]*10
hits = 0
first = random.randint(0,9)
while True:
second = random.randint(0,9)
if second != first:
break
sub[first] = 1
sub[second] = 1
sub[random.randint(0,9)] = 1
for i in range(1,reps):
first = random.randint(0,9)
while True:
second = random.randint(0,9)
if second != first:
break
if ((sub[first]) or (sub[second])):
hits = hits + 1
print "result: ", hits*1.0/reps*100.0
Now, this is not the problem I was initially trying to solve and the result for this script should be 34/90 or around 37.7 which is simple enough combinatorics. Sometimes, the script does give that result, however more often it gives 53.4, which seems to make no sense.
This is pretty much just idle curiosity as to why exactly this script behaves like it does.
|
[
"BTW, for the best way to \"generate 3 different randomly distributed integers between 0 and 9 included\", I heartily recommend a, b, c = random.sample(xrange(10), 3) [[s/xrange/range/ in Python 3.0]] rather than the while loops you're using.\n",
"The result depends on whether line 13:\nsub[random.randint(0,9)] = 1\n\nhits the same index as one of lines 11 or 12:\nsub[first] = 1\nsub[second] = 1\n\nYou protect second from being the same as first, but you don't protect that third entry from being the same as one of first or second.\n"
] |
[
5,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000991784_python.txt
|
Q:
Changing brightness of the Macbook(Pro) keyboard backlight
Programaticly, how can I modify the brightness of the backlit keyboard on a Macbook or Macbook Pro using Python?
A:
Amit Singh discusses these undocumented APIs in this online bonus chapter, but does so using C -- I'm not sure if a Python extension exists to do the same work from Python, perhaps as part of PyObjC (otherwise, such an extension would have to be written -- or ctypes used to access the shared C libraries directly from Python [shudder;-)]).
|
Changing brightness of the Macbook(Pro) keyboard backlight
|
Programaticly, how can I modify the brightness of the backlit keyboard on a Macbook or Macbook Pro using Python?
|
[
"Amit Singh discusses these undocumented APIs in this online bonus chapter, but does so using C -- I'm not sure if a Python extension exists to do the same work from Python, perhaps as part of PyObjC (otherwise, such an extension would have to be written -- or ctypes used to access the shared C libraries directly from Python [shudder;-)]).\n"
] |
[
9
] |
[] |
[] |
[
"hardware",
"macos",
"python"
] |
stackoverflow_0000991813_hardware_macos_python.txt
|
Q:
What is this function doing in Python involving urllib2 and BeautifulSoup?
So I asked a question earlier about retrieving high scores form an html page and another user gave me the following code to help. I am new to python and beautifulsoup so I'm trying to go through some other codes piece by piece. I understand most of it but I dont get what this piece of code is and what its function is:
def parse_string(el):
text = ''.join(el.findAll(text=True))
return text.strip()
Here is the entire code:
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
import sys
URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1]
# Grab page html, create BeatifulSoup object
html = urlopen(URL).read()
soup = BeautifulSoup(html)
# Grab the <table id="mini_player"> element
scores = soup.find('table', {'id':'mini_player'})
# Get a list of all the <tr>s in the table, skip the header row
rows = scores.findAll('tr')[1:]
# Helper function to return concatenation of all character data in an element
def parse_string(el):
text = ''.join(el.findAll(text=True))
return text.strip()
for row in rows:
# Get all the text from the <td>s
data = map(parse_string, row.findAll('td'))
# Skip the first td, which is an image
data = data[1:]
# Do something with the data...
print data
A:
el.findAll(text=True) returns all the text contained within an element and its sub-elements. By text I mean everything not inside a tag; so in <b>hello</b> then "hello" would be the text but <b> and </b> would not.
That function therefore joins together all text found beneath the given element and strips whitespace off from the front and back.
Here's a link to the findAll documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text
|
What is this function doing in Python involving urllib2 and BeautifulSoup?
|
So I asked a question earlier about retrieving high scores form an html page and another user gave me the following code to help. I am new to python and beautifulsoup so I'm trying to go through some other codes piece by piece. I understand most of it but I dont get what this piece of code is and what its function is:
def parse_string(el):
text = ''.join(el.findAll(text=True))
return text.strip()
Here is the entire code:
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
import sys
URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1]
# Grab page html, create BeatifulSoup object
html = urlopen(URL).read()
soup = BeautifulSoup(html)
# Grab the <table id="mini_player"> element
scores = soup.find('table', {'id':'mini_player'})
# Get a list of all the <tr>s in the table, skip the header row
rows = scores.findAll('tr')[1:]
# Helper function to return concatenation of all character data in an element
def parse_string(el):
text = ''.join(el.findAll(text=True))
return text.strip()
for row in rows:
# Get all the text from the <td>s
data = map(parse_string, row.findAll('td'))
# Skip the first td, which is an image
data = data[1:]
# Do something with the data...
print data
|
[
"el.findAll(text=True) returns all the text contained within an element and its sub-elements. By text I mean everything not inside a tag; so in <b>hello</b> then \"hello\" would be the text but <b> and </b> would not.\nThat function therefore joins together all text found beneath the given element and strips whitespace off from the front and back.\nHere's a link to the findAll documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text\n"
] |
[
3
] |
[] |
[] |
[
"python",
"urllib2"
] |
stackoverflow_0000991967_python_urllib2.txt
|
Q:
Why are 008 and 009 invalid keys for Python dicts?
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine?
Example:
some_dict = {
001: "spam",
002: "eggs",
003: "foo",
004: "bar",
008: "anything", # Throws a SyntaxError
009: "nothing" # Throws a SyntaxError
}
Update: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero?
A:
In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this:
some_dict = {
1: "spam",
2: "eggs",
3: "foo",
4: "bar",
8: "anything",
9: "nothing" }
Or if the leading zeros are really important, use strings for the keys.
A:
Python takes 008 and 009 as octal numbers, therefore...invalid.
You can only go up to 007, then the next number would be 010 (8) then 011 (9). Try it in a Python interpreter, and you'll see what I mean.
A:
In Python (and many other languages), starting a number with a leading "0" indicates an octal number (base 8). Using this leading-zero notation is called an octal literal. Octal numbers go 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, etc. So 08 (in octal) is invalid.
If you remove the leading zeros, your code will be fine:
some_dict =
{
1: "spam",
2: "eggs",
3: "foo",
4: "bar",
8: "anything",
9: "nothing"
}
A:
@DoxaLogos is right. It's not that they're invalid keys - they're invalid literals. If you tried to use them in any other context, you'd get the same error.
A:
That is because, when you start a number with a 0, it is interpreted as an octal number. Since 008 and 009 are not octal numbers, it fails.
A 0 precedes an octal number so that you do not have to write (127)₈. From the Wikipedia page: "Sometimes octal numbers are represented by preceding a value with a 0 (e.g. in Python 2.x or JavaScript 1.x - although it is now deprecated in both)."
|
Why are 008 and 009 invalid keys for Python dicts?
|
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine?
Example:
some_dict = {
001: "spam",
002: "eggs",
003: "foo",
004: "bar",
008: "anything", # Throws a SyntaxError
009: "nothing" # Throws a SyntaxError
}
Update: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero?
|
[
"In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this:\nsome_dict = { \n 1: \"spam\",\n 2: \"eggs\",\n 3: \"foo\",\n 4: \"bar\",\n 8: \"anything\",\n 9: \"nothing\" }\n\nOr if the leading zeros are really important, use strings for the keys.\n",
"Python takes 008 and 009 as octal numbers, therefore...invalid.\nYou can only go up to 007, then the next number would be 010 (8) then 011 (9). Try it in a Python interpreter, and you'll see what I mean.\n",
"In Python (and many other languages), starting a number with a leading \"0\" indicates an octal number (base 8). Using this leading-zero notation is called an octal literal. Octal numbers go 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, etc. So 08 (in octal) is invalid.\nIf you remove the leading zeros, your code will be fine:\nsome_dict = \n{ \n 1: \"spam\",\n 2: \"eggs\",\n 3: \"foo\",\n 4: \"bar\",\n 8: \"anything\",\n 9: \"nothing\" \n}\n\n",
"@DoxaLogos is right. It's not that they're invalid keys - they're invalid literals. If you tried to use them in any other context, you'd get the same error.\n",
"That is because, when you start a number with a 0, it is interpreted as an octal number. Since 008 and 009 are not octal numbers, it fails.\nA 0 precedes an octal number so that you do not have to write (127)₈. From the Wikipedia page: \"Sometimes octal numbers are represented by preceding a value with a 0 (e.g. in Python 2.x or JavaScript 1.x - although it is now deprecated in both).\"\n"
] |
[
28,
10,
8,
7,
2
] |
[] |
[] |
[
"dictionary",
"python",
"python_2.x"
] |
stackoverflow_0000991978_dictionary_python_python_2.x.txt
|
Q:
Why am I getting "'ResultSet' has no attribute 'findAll'" using BeautifulSoup in Python?
So I am learning Python slowly, and am trying to make a simple function that will draw data from the high scores page of an online game. This is someone else's code that i rewrote into one function (which might be the problem), but I am getting this error. Here is the code:
>>> from urllib2 import urlopen
>>> from BeautifulSoup import BeautifulSoup
>>> def create(el):
source = urlopen(el).read()
soup = BeautifulSoup(source)
get_table = soup.find('table', {'id':'mini_player'})
get_rows = get_table.findAll('tr')
text = ''.join(get_rows.findAll(text=True))
data = text.strip()
return data
>>> create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13')
File "<pyshell#17>", line 6, in create
text = ''.join(get_rows.findAll(text=True))
AttributeError: 'ResultSet' object has no attribute 'findAll'
Thanks in advance.
A:
Wow. Triptych provided a great answer to a related question.
We can see, from BeautifulSoup's source code, that ResultSet subclasses list.
In your example, get_rows is an instance of BS's ResultSet class,
and since BS's ResultSet subclasses list, that means get_rows is a list.
get_rows, as an instance of ResultSet, does not have a findAll method implemented; hence your error.
What Triptych has done differently is to iterate over that list.
Triptych's method works because the items in the get_rows list are instances of BS's Tag class; which has a findAll method.
So, to fix your code, you could replace the last three lines of your create method with something like this:
for row in get_rows:
text = ''.join(row.findAll(text=True))
data = text.strip()
print data
Note to Leonard Richardson: in no way do I intend to demean the quality of your work by referring to it as BS ;-)
|
Why am I getting "'ResultSet' has no attribute 'findAll'" using BeautifulSoup in Python?
|
So I am learning Python slowly, and am trying to make a simple function that will draw data from the high scores page of an online game. This is someone else's code that i rewrote into one function (which might be the problem), but I am getting this error. Here is the code:
>>> from urllib2 import urlopen
>>> from BeautifulSoup import BeautifulSoup
>>> def create(el):
source = urlopen(el).read()
soup = BeautifulSoup(source)
get_table = soup.find('table', {'id':'mini_player'})
get_rows = get_table.findAll('tr')
text = ''.join(get_rows.findAll(text=True))
data = text.strip()
return data
>>> create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
create('http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13')
File "<pyshell#17>", line 6, in create
text = ''.join(get_rows.findAll(text=True))
AttributeError: 'ResultSet' object has no attribute 'findAll'
Thanks in advance.
|
[
"Wow. Triptych provided a great answer to a related question.\nWe can see, from BeautifulSoup's source code, that ResultSet subclasses list.\nIn your example, get_rows is an instance of BS's ResultSet class, \nand since BS's ResultSet subclasses list, that means get_rows is a list.\nget_rows, as an instance of ResultSet, does not have a findAll method implemented; hence your error. \nWhat Triptych has done differently is to iterate over that list. \nTriptych's method works because the items in the get_rows list are instances of BS's Tag class; which has a findAll method.\nSo, to fix your code, you could replace the last three lines of your create method with something like this:\nfor row in get_rows:\n text = ''.join(row.findAll(text=True))\n data = text.strip()\n print data\n\nNote to Leonard Richardson: in no way do I intend to demean the quality of your work by referring to it as BS ;-)\n"
] |
[
19
] |
[] |
[] |
[
"beautifulsoup",
"python",
"urllib2"
] |
stackoverflow_0000992183_beautifulsoup_python_urllib2.txt
|
Q:
django for loop counter break
This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos of each gallery in that list, since if each gallery even has 20 images, then that's 100 images on a page if I paginate at 5 posts. That'd be wasteful, and the wrong way to go about things.
The question I have is, is there a way to just display 3 photos from the photo set? What I'd like to do, but I don't think is possible is something like (pseudocode):
{% for photos in gallery.photo_set %}
{% if forloop.counter lt 3 %}
<img src="{{ photos.url }}">
{% endif %}
{% endfor %}
Judging from the documentation, unless I'm completely missing it, that's not possible via the templating system. Hence, I can just write my own template tag of sorts to work around it. I could probably do something from the view aspect, but I haven't looked to far into that idea. The other option I have is giving the model a preview field, and allow the user to select the photos they want in the preview field.
Anyways, a few different options, so I thought I'd poll the audience to see how you'd do it. Any opinion is appreciated. Personally, enjoying that there's numerous ways to skin this cat.
A:
Use:
{% for photos in gallery.photo_set|slice:":3" %}
A:
This is better done in the gallery.photo_set collection. The hard-coded "3" in the template is a bad idea in the long run.
class Gallery( object ):
def photo_subset( self ):
return Photo.objects.filter( gallery_id = self.id )[:3]
In your view function, you can do things like pick 3 random photos, or the 3 most recent photos.
def photo_recent( self ):
return Photo.objects.filter( gallery_id = self.id ).orderby( someDate )[:3]
def photo_random( self ):
pix = Photo.objects.filter( gallery_id = self.id ).all()
random.shuffle(pix)
return pix[:3]
|
django for loop counter break
|
This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos of each gallery in that list, since if each gallery even has 20 images, then that's 100 images on a page if I paginate at 5 posts. That'd be wasteful, and the wrong way to go about things.
The question I have is, is there a way to just display 3 photos from the photo set? What I'd like to do, but I don't think is possible is something like (pseudocode):
{% for photos in gallery.photo_set %}
{% if forloop.counter lt 3 %}
<img src="{{ photos.url }}">
{% endif %}
{% endfor %}
Judging from the documentation, unless I'm completely missing it, that's not possible via the templating system. Hence, I can just write my own template tag of sorts to work around it. I could probably do something from the view aspect, but I haven't looked to far into that idea. The other option I have is giving the model a preview field, and allow the user to select the photos they want in the preview field.
Anyways, a few different options, so I thought I'd poll the audience to see how you'd do it. Any opinion is appreciated. Personally, enjoying that there's numerous ways to skin this cat.
|
[
"Use:\n{% for photos in gallery.photo_set|slice:\":3\" %}\n\n",
"This is better done in the gallery.photo_set collection. The hard-coded \"3\" in the template is a bad idea in the long run.\nclass Gallery( object ):\n def photo_subset( self ):\n return Photo.objects.filter( gallery_id = self.id )[:3]\n\nIn your view function, you can do things like pick 3 random photos, or the 3 most recent photos.\n def photo_recent( self ):\n return Photo.objects.filter( gallery_id = self.id ).orderby( someDate )[:3]\n\n def photo_random( self ):\n pix = Photo.objects.filter( gallery_id = self.id ).all()\n random.shuffle(pix)\n return pix[:3]\n\n"
] |
[
85,
1
] |
[] |
[] |
[
"django",
"for_loop",
"python"
] |
stackoverflow_0000992230_django_for_loop_python.txt
|
Q:
How to setup twill for python 2.6 on Windows?
I have already downloaded twill 0.9. Also, I have installed easy_install for python 2.6. Now I'm stuck with twill installation. Could you help me to settle the problem?
A:
Something like:
easy_install twill
It assumes you have easy_install in your PATH, which is the case on unix, but not on windows. On windows, the easy_install script can be found in C:\Python25\Scripts
A:
easiest way is to just unzip the twill and keep it somewhere in PYTHONPATH e.g. in your project and just import twill
else copy twill folder directly to D:\Python26\Lib\site-packages
|
How to setup twill for python 2.6 on Windows?
|
I have already downloaded twill 0.9. Also, I have installed easy_install for python 2.6. Now I'm stuck with twill installation. Could you help me to settle the problem?
|
[
"Something like:\neasy_install twill\n\nIt assumes you have easy_install in your PATH, which is the case on unix, but not on windows. On windows, the easy_install script can be found in C:\\Python25\\Scripts\n",
"easiest way is to just unzip the twill and keep it somewhere in PYTHONPATH e.g. in your project and just import twill\nelse copy twill folder directly to D:\\Python26\\Lib\\site-packages\n"
] |
[
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000992638_python.txt
|
Q:
Python LDAP Authentication from remote web server
I have a django application hosted on webfaction which now has a static/private ip.
Our network in the office is obviously behind a firewall and the AD server is running behind this firewall. From inside the network i can authenticate using python-ldap with the AD's internal IP address and the port 389 and all works well.
When i move this to the hosted webserver i change the ip address and port that has been openend up on our firewall. For simplicity the port we opened up is 389 however the requests to authenticate always timeout. When logged into webfaction and running python from the shell and querying the ipaddress i get webfactional's general ip address rather than my static ip.
Is this whats happening when i try and auth in django? the request comes from the underlying ip address that python is running on rather than the static ip that my firewall is expecting?
Im fairly clueless to all this networking and port mapping so any help would be much appreciated!
Hope that makes sense?
A:
I would recommend against opening the port on the firewall directly to LDAP. Instead I would suggest making an SSH tunnel. This will put the necessary encryptionn around the LDAP traffic. Here is an example.
ssh -N -p 22 username@ldapserver -L 2222/localhost/389
This assumes that the ssh server is running on port 22 of your ldap server, and is accessible from your web host. It will create a tunnel from port 389 on the ldap server to port 2222 on the web host. Then, you configure your django application on the web host to think that the LDAP server is running on localhost port 2222.
A:
There are quite a few components between your hosted django application and your internal AD. You will need to test each to see if everything in the pathways between them is correct.
So your AD server is sitting behind your firewall. Your firewall has ip "a.b.c.d" and all traffic to the firewall ip on port 389 is forwarded to the AD server. I would recommend that you change this to a higher more random port on your firewall, btw. Less scans there.
With the shell access you can test to see if you can reach your network. Have your firewall admin check the firewall logs while you try one of the following (or something similar with python) :
check the route to your firewall (this might not work if webfaction blocks this, otherwise you will see a list of hosts along which your traffic will pass - if there is a firewall on the route somewhere you will see that your connection is lost there as this is dropped by default on most firewalls):
tracert a.b.c.d
do a telnet to your firewall ip on port 389 (the telnet test will allow your firewall admin to see the connection attempts coming in on port 389 in his log. If those do arrive, that means that external comm should work fine):
telnet a.b.c.d 389
Similarly, you need to check that your AD server receives these requests (check your logs) and as well can respond to them. Perhaps your AD server is not set up to talk to the firewall ?
|
Python LDAP Authentication from remote web server
|
I have a django application hosted on webfaction which now has a static/private ip.
Our network in the office is obviously behind a firewall and the AD server is running behind this firewall. From inside the network i can authenticate using python-ldap with the AD's internal IP address and the port 389 and all works well.
When i move this to the hosted webserver i change the ip address and port that has been openend up on our firewall. For simplicity the port we opened up is 389 however the requests to authenticate always timeout. When logged into webfaction and running python from the shell and querying the ipaddress i get webfactional's general ip address rather than my static ip.
Is this whats happening when i try and auth in django? the request comes from the underlying ip address that python is running on rather than the static ip that my firewall is expecting?
Im fairly clueless to all this networking and port mapping so any help would be much appreciated!
Hope that makes sense?
|
[
"I would recommend against opening the port on the firewall directly to LDAP. Instead I would suggest making an SSH tunnel. This will put the necessary encryptionn around the LDAP traffic. Here is an example.\nssh -N -p 22 username@ldapserver -L 2222/localhost/389\n\nThis assumes that the ssh server is running on port 22 of your ldap server, and is accessible from your web host. It will create a tunnel from port 389 on the ldap server to port 2222 on the web host. Then, you configure your django application on the web host to think that the LDAP server is running on localhost port 2222. \n",
"There are quite a few components between your hosted django application and your internal AD. You will need to test each to see if everything in the pathways between them is correct.\nSo your AD server is sitting behind your firewall. Your firewall has ip \"a.b.c.d\" and all traffic to the firewall ip on port 389 is forwarded to the AD server. I would recommend that you change this to a higher more random port on your firewall, btw. Less scans there.\nWith the shell access you can test to see if you can reach your network. Have your firewall admin check the firewall logs while you try one of the following (or something similar with python) :\n\ncheck the route to your firewall (this might not work if webfaction blocks this, otherwise you will see a list of hosts along which your traffic will pass - if there is a firewall on the route somewhere you will see that your connection is lost there as this is dropped by default on most firewalls): \ntracert a.b.c.d\ndo a telnet to your firewall ip on port 389 (the telnet test will allow your firewall admin to see the connection attempts coming in on port 389 in his log. If those do arrive, that means that external comm should work fine):\ntelnet a.b.c.d 389 \n\nSimilarly, you need to check that your AD server receives these requests (check your logs) and as well can respond to them. Perhaps your AD server is not set up to talk to the firewall ?\n"
] |
[
3,
0
] |
[] |
[] |
[
"active_directory",
"ldap",
"python",
"webserver"
] |
stackoverflow_0000990459_active_directory_ldap_python_webserver.txt
|
Q:
Does running separate python processes avoid the GIL?
I'm curious in how the Global Interpreter Lock in python actually works. If I have a c++ application launch four separate instances of a python script will they run in parallel on separate cores, or does the GIL go even deeper then just the single process that was launched and control all python process's regardless of the process that spawned it?
A:
The GIL only affects threads within a single process. The multiprocessing module is in fact an alternative to threading that lets Python programs use multiple cores &c. Your scenario will easily allow use of multiple cores, too.
A:
As Alex Martelli points out you can indeed avoid the GIL by running multiple processes, I just want to add and point out that the GIL is a limitation of the implementation (CPython) and not of Python in general, it's possible to implement Python without this limitation. Stackless Python comes to mind.
|
Does running separate python processes avoid the GIL?
|
I'm curious in how the Global Interpreter Lock in python actually works. If I have a c++ application launch four separate instances of a python script will they run in parallel on separate cores, or does the GIL go even deeper then just the single process that was launched and control all python process's regardless of the process that spawned it?
|
[
"The GIL only affects threads within a single process. The multiprocessing module is in fact an alternative to threading that lets Python programs use multiple cores &c. Your scenario will easily allow use of multiple cores, too.\n",
"As Alex Martelli points out you can indeed avoid the GIL by running multiple processes, I just want to add and point out that the GIL is a limitation of the implementation (CPython) and not of Python in general, it's possible to implement Python without this limitation. Stackless Python comes to mind.\n"
] |
[
33,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000992136_python.txt
|
Q:
Python disable/redirect keyboard input
I'm writing a macro generator/ keyboard remapper in python, for xubuntu.
I've figured out how to intercept and record keystrokes, and send keystrokes I want to record, but I haven't figured out how to block keystrokes. I need to disable keyboard input to remap a key. For example, if I wanted to send 'a' when I press the 's' key, I can currently record the 'a' keystroke, and set it to playback when I press the 's' key. I cannot, however keep the 's' keystroke from being sent alongside it.
I used the pyxhook module from an open source keyboard-logger for the hooks, and a again, the xtest fake input method from the python x library.
I remember reading somewhere about somebody blocking all keyboard input by redirecting all keystrokes to an invisible window by using tkinter. If somebody could post that method that'd be great.
I need something that will block all keystrokes, but not turn off my keyboard hooks.
A:
I think it's going to depend heavily on the environment: curses & the activestate recipe are good for command line, but if you want it to run in a DE, you'll need some hooks to that DE. You might look at Qt or GTK bindings for python, or there's a python-xlib library that might let you tie right into the X system.
So I guess the answer is "it depends." Are you looking for console noecho functionality, or a text replacement program for a DE, or an xmodmap-style layout changer?
A:
I've got a keyboard hook that detects X events. I'm looking for a way to globally prevent a single keyboard event from being sent to a window. Something that works by accessing the event queue and removing the keyboard event from it would be ideal. It looks like it should be possible using Python Xlib, but I can't figure it out.
|
Python disable/redirect keyboard input
|
I'm writing a macro generator/ keyboard remapper in python, for xubuntu.
I've figured out how to intercept and record keystrokes, and send keystrokes I want to record, but I haven't figured out how to block keystrokes. I need to disable keyboard input to remap a key. For example, if I wanted to send 'a' when I press the 's' key, I can currently record the 'a' keystroke, and set it to playback when I press the 's' key. I cannot, however keep the 's' keystroke from being sent alongside it.
I used the pyxhook module from an open source keyboard-logger for the hooks, and a again, the xtest fake input method from the python x library.
I remember reading somewhere about somebody blocking all keyboard input by redirecting all keystrokes to an invisible window by using tkinter. If somebody could post that method that'd be great.
I need something that will block all keystrokes, but not turn off my keyboard hooks.
|
[
"I think it's going to depend heavily on the environment: curses & the activestate recipe are good for command line, but if you want it to run in a DE, you'll need some hooks to that DE. You might look at Qt or GTK bindings for python, or there's a python-xlib library that might let you tie right into the X system.\nSo I guess the answer is \"it depends.\" Are you looking for console noecho functionality, or a text replacement program for a DE, or an xmodmap-style layout changer?\n",
"I've got a keyboard hook that detects X events. I'm looking for a way to globally prevent a single keyboard event from being sent to a window. Something that works by accessing the event queue and removing the keyboard event from it would be ideal. It looks like it should be possible using Python Xlib, but I can't figure it out. \n"
] |
[
1,
0
] |
[] |
[] |
[
"keyboard",
"python"
] |
stackoverflow_0000958491_keyboard_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.