title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 510,324 | <p>The DOM has (atleast in level 2) an interface
DATASection, and an operation Document::createCDATASection. They are
extension interfaces, supported only if an implementation supports the
"xml" feature.</p>
<p>from xml.dom import minidom</p>
<p>my_xmldoc=minidom.parse(xmlfile)</p>
<p>my_xmldoc.createCDATASection(data)</p>
<p>now u have cadata node add it wherever u want....</p>
| 1 | 2009-02-04T06:53:24Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 8,915,039 | <p>Here is a variant of gooli's solution that works for python 3.2:</p>
<pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as etree
def CDATA(text=None):
element = etree.Element('![CDATA[')
element.text = text
return element
etree._original_serialize_xml = etree._serialize_xml
def _serialize_xml(write, elem, qnames, namespaces):
if elem.tag == '![CDATA[':
write("\n<%s%s]]>\n" % (
elem.tag, elem.text))
return
return etree._original_serialize_xml(
write, elem, qnames, namespaces)
etree._serialize_xml = etree._serialize['xml'] = _serialize_xml
if __name__ == "__main__":
import sys
text = """
<?xml version='1.0' encoding='utf-8'?>
<text>
This is just some sample text.
</text>
"""
e = etree.Element("data")
cdata = CDATA(text)
e.append(cdata)
et = etree.ElementTree(e)
et.write(sys.stdout.buffer.raw, "utf-8")
</code></pre>
| 8 | 2012-01-18T18:03:56Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 10,440,166 | <p>Here's my version which is based on both gooli's and amaury's answers above. It works for both ElementTree 1.2.6 and 1.3.0, which use very different methods of doing this.</p>
<p>Note that gooli's does not work with 1.3.0, which seems to be the current standard in Python 2.7.x.</p>
<p>Also note that this version does not use the CDATA() method gooli used either.</p>
<pre><code>import xml.etree.cElementTree as ET
class ElementTreeCDATA(ET.ElementTree):
"""Subclass of ElementTree which handles CDATA blocks reasonably"""
def _write(self, file, node, encoding, namespaces):
"""This method is for ElementTree <= 1.2.6"""
if node.tag == '![CDATA[':
text = node.text.encode(encoding)
file.write("\n<![CDATA[%s]]>\n" % text)
else:
ET.ElementTree._write(self, file, node, encoding, namespaces)
def _serialize_xml(write, elem, qnames, namespaces):
"""This method is for ElementTree >= 1.3.0"""
if elem.tag == '![CDATA[':
write("\n<![CDATA[%s]]>\n" % elem.text)
else:
ET._serialize_xml(write, elem, qnames, namespaces)
</code></pre>
| 0 | 2012-05-03T22:27:49Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 13,919,169 | <p>I got here looking for a way to "parse an XML with CDATA sections and then output it again with the CDATA sections". </p>
<p>I was able to do this (maybe lxml has been updated since this post?) with the following: (it is a little rough - sorry ;-). Someone else may have a better way to find the CDATA sections programatically but I was too lazy.</p>
<pre class="lang-py prettyprint-override"><code> parser = etree.XMLParser(encoding='utf-8') # my original xml was utf-8 and that was a lot of the problem
tree = etree.parse(ppath, parser)
for cdat in tree.findall('./ProjectXMPMetadata'): # the tag where my CDATA lives
cdat.text = etree.CDATA(cdat.text)
# other stuff here
tree.write(opath, encoding="UTF-8",)
</code></pre>
| 0 | 2012-12-17T17:39:44Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 14,118,042 | <p>The accepted solution cannot work with <strong>Python 2.7</strong>. However, there is another package called <a href="http://lxml.de/" rel="nofollow">lxml</a> which (though slightly slower) shared a largely identical syntax with the <code>xml.etree.ElementTree</code>. <code>lxml</code> is able to both write and parse <code>CDATA</code>. Documentation <a href="http://lxml.de/" rel="nofollow">here</a></p>
| 1 | 2013-01-02T06:56:08Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 16,944,089 | <p>This ended up working for me in Python 2.7. Similar to Amaury's answer.</p>
<pre><code>import xml.etree.ElementTree as ET
ET._original_serialize_xml = ET._serialize_xml
def _serialize_xml(write, elem, encoding, qnames, namespaces):
if elem.tag == '![CDATA[':
write("<%s%s]]>%s" % (elem.tag, elem.text, elem.tail))
return
return ET._original_serialize_xml(
write, elem, encoding, qnames, namespaces)
ET._serialize_xml = ET._serialize['xml'] = _serialize_xml
</code></pre>
| 3 | 2013-06-05T15:37:11Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 20,894,783 | <p>I've discovered a hack to get CDATA to work using comments:</p>
<pre><code>node.append(etree.Comment(' --><![CDATA[' + data.replace(']]>', ']]]]><![CDATA[>') + ']]><!-- '))
</code></pre>
| 1 | 2014-01-03T01:04:33Z | [
"python",
"xml"
] |
How to output CDATA using ElementTree | 174,890 | <p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p>
<p>Can it be done?</p>
| 26 | 2008-10-06T15:56:07Z | 30,019,607 | <p>I don't know whether previous versions of proposed code worked very well and whether ElementTree module has been updated but I have faced problems with using this trick:</p>
<pre><code>etree._original_serialize_xml = etree._serialize_xml
def _serialize_xml(write, elem, qnames, namespaces):
if elem.tag == '![CDATA[':
write("\n<%s%s]]>\n" % (
elem.tag, elem.text))
return
return etree._original_serialize_xml(
write, elem, qnames, namespaces)
etree._serialize_xml = etree._serialize['xml'] = _serialize_xml
</code></pre>
<p>The problem with this approach is that after passing this exception, serializer is again treating it as normal tag afterwards. I was getting something like:</p>
<pre><code><textContent>
<![CDATA[this was the code I wanted to put inside of CDATA]]>
<![CDATA[>this was the code I wanted to put inside of CDATA</![CDATA[>
</textContent>
</code></pre>
<p>And of course we know that will cause only plenty of errors.
Why that was happening though?</p>
<p>The answer is in this little guy:</p>
<pre><code>return etree._original_serialize_xml(write, elem, qnames, namespaces)
</code></pre>
<p>We don't want to examine code once again through original serialise function if we have trapped our CDATA and successfully passed it through.
Therefore in the "if" block we have to return original serialize function only when CDATA was not there. We were missing "else" before returning original function.</p>
<p>Moreover in my version ElementTree module, serialize function was desperately asking for "short_empty_element" argument. So the most recent version I would recommend looks like this(also with "tail"):</p>
<pre><code>from xml.etree import ElementTree
from xml import etree
#in order to test it you have to create testing.xml file in the folder with the script
xmlParsedWithET = ElementTree.parse("testing.xml")
root = xmlParsedWithET.getroot()
def CDATA(text=None):
element = ElementTree.Element('![CDATA[')
element.text = text
return element
ElementTree._original_serialize_xml = ElementTree._serialize_xml
def _serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs):
if elem.tag == '![CDATA[':
write("\n<{}{}]]>\n".format(elem.tag, elem.text))
if elem.tail:
write(_escape_cdata(elem.tail))
else:
return ElementTree._original_serialize_xml(write, elem, qnames, namespaces,short_empty_elements, **kwargs)
ElementTree._serialize_xml = ElementTree._serialize['xml'] = _serialize_xml
text = """
<?xml version='1.0' encoding='utf-8'?>
<text>
This is just some sample text.
</text>
"""
e = ElementTree.Element("data")
cdata = CDATA(text)
root.append(cdata)
#tests
print(root)
print(root.getchildren()[0])
print(root.getchildren()[0].text + "\n\nyay!")
</code></pre>
<p>The output I got was:</p>
<pre><code><Element 'Database' at 0x10062e228>
<Element '![CDATA[' at 0x1021cc9a8>
<?xml version='1.0' encoding='utf-8'?>
<text>
This is just some sample text.
</text>
yay!
</code></pre>
<p>I wish you the same result!</p>
| 2 | 2015-05-03T21:27:30Z | [
"python",
"xml"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 175,258 | <p><em>I think this is a deeper issue than you realize</em>. Simply changing the file from Unicode into ASCII is easy, however, getting all of the Unicode characters to translate into reasonable ASCII counterparts (many letters are not available in both encodings) is another.</p>
<p>This Python Unicode tutorial may give you a better idea of what happens to Unicode strings that are translated to ASCII: <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html" rel="nofollow">http://www.reportlab.com/i18n/python_unicode_tutorial.html</a></p>
<p><strong>Here's a useful quote from the site:</strong></p>
<blockquote>
<p>Python 1.6 also gets a "unicode"
built-in function, to which you can
specify the encoding:</p>
</blockquote>
<pre><code>> >>> unicode('hello') u'hello'
> >>> unicode('hello', 'ascii') u'hello'
> >>> unicode('hello', 'iso-8859-1') u'hello'
> >>>
</code></pre>
<blockquote>
<p>All three of these return the same
thing, since the characters in 'Hello'
are common to all three encodings.</p>
<p>Now let's encode something with a
European accent, which is outside of
ASCII. What you see at a console may
depend on your operating system
locale; Windows lets me type in
ISO-Latin-1.</p>
</blockquote>
<pre><code>> >>> a = unicode('André','latin-1')
> >>> a u'Andr\202'
</code></pre>
<blockquote>
<p>If you can't type an acute letter e,
you can enter the string 'Andr\202',
which is unambiguous.</p>
<p>Unicode supports all the common
operations such as iteration and
splitting. We won't run over them
here.</p>
</blockquote>
| 11 | 2008-10-06T17:17:01Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 175,260 | <p>Like this:</p>
<pre><code>uc = open(filename).read().decode('utf8')
ascii = uc.decode('ascii')
</code></pre>
<p>Note, however, that this will <strong>fail</strong> with a <code>UnicodeDecodeError</code> exception if there are any characters that can't be converted to ASCII.</p>
<p>EDIT: As Pete Karl just pointed out, there is no one-to-one mapping from Unicode to ASCII. So some characters simply can't be converted in an information-preserving way. Moreover, standard ASCII is more or less a subset of UTF-8, so you don't really even need to do any decoding.</p>
| 2 | 2008-10-06T17:18:04Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 175,270 | <p>You can convert the file easily enough just using the <code>unicode</code> function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.</p>
<p><a href="http://www.peterbe.com/plog/unicode-to-ascii">This blog</a> recommends the <code><a href="http://www.python.org/doc/2.5.2/lib/module-unicodedata.html">unicodedata </a></code> module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g.</p>
<pre><code>>>> title = u"Klüft skräms inför pÃ¥ fédéral électoral groÃe"
</code></pre>
<p>is typically converted to </p>
<pre><code>Klft skrms infr p fdral lectoral groe
</code></pre>
<p>which is pretty wrong. However, using the <code>unicodedata</code> module, the result can be much closer to the original text:</p>
<pre><code>>>> import unicodedata
>>> unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'
</code></pre>
| 41 | 2008-10-06T17:21:15Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 175,286 | <p>Here's some simple (and stupid) code to do encoding translation. I'm assuming (but you shouldn't) that the input file is in UTF-16 (Windows calls this simply 'Unicode').</p>
<pre><code>input_codec = 'UTF-16'
output_codec = 'ASCII'
unicode_file = open('filename')
unicode_data = unicode_file.read().decode(input_codec)
ascii_file = open('new filename', 'w')
ascii_file.write(unicode_data.write(unicode_data.encode(output_codec)))
</code></pre>
<p>Note that this will not work if there are any characters in the Unicode file that are not also ASCII characters. You can do the following to turn unrecognized characters into '?'s:</p>
<pre><code>ascii_file.write(unicode_data.write(unicode_data.encode(output_codec, 'replace')))
</code></pre>
<p>Check out <a href="http://docs.python.org/library/stdtypes.html#str.encode" rel="nofollow">the docs</a> for more simple choices. If you need to do anything more sophisticated, you may wish to check out <a href="http://code.activestate.com/recipes/251871/" rel="nofollow">The UNICODE Hammer</a> at the Python Cookbook.</p>
| 2 | 2008-10-06T17:24:48Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 176,044 | <p>It's important to note that there is no 'Unicode' file format. Unicode can be encoded to bytes in several different ways. Most commonly UTF-8 or UTF-16. You'll need to know which one your 3rd-party tool is outputting. Once you know that, converting between different encodings is pretty easy:</p>
<pre><code>in_file = open("myfile.txt", "rb")
out_file = open("mynewfile.txt", "wb")
in_byte_string = in_file.read()
unicode_string = bytestring.decode('UTF-16')
out_byte_string = unicode_string.encode('ASCII')
out_file.write(out_byte_string)
out_file.close()
</code></pre>
<p>As noted in the other replies, you're probably going to want to supply an error handler to the encode method. Using 'replace' as the error handler is simple, but will mangle your text if it contains characters that cannot be represented in ASCII.</p>
| 0 | 2008-10-06T20:24:46Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 1,906,165 | <p>As other posters have noted, ASCII is a subset of unicode. </p>
<p>However if you:</p>
<ul>
<li>have a legacy app </li>
<li>you don't control the code for that app</li>
<li>you're sure your input falls into the ASCII subset</li>
</ul>
<p>Then the example below shows how to do it:</p>
<pre><code>mystring = u'bar'
type(mystring)
<type 'unicode'>
myasciistring = (mystring.encode('ASCII'))
type(myasciistring)
<type 'str'>
</code></pre>
| 0 | 2009-12-15T09:12:38Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 6,312,083 | <p>For my problem where I just wanted to skip the Non-ascii characters and just output only ascii output, the below solution worked really well:</p>
<pre><code> import unicodedata
input = open(filename).read().decode('UTF-16')
output = unicodedata.normalize('NFKD', input).encode('ASCII', 'ignore')
</code></pre>
| 2 | 2011-06-10T21:08:02Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | <p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
| 18 | 2008-10-06T17:11:30Z | 8,543,825 | <p>By the way, these is a linux command <code>iconv</code> to do this kind of job.</p>
<pre><code>iconv -f utf8 -t ascii <input.txt >output.txt
</code></pre>
| 3 | 2011-12-17T09:29:58Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 175,585 | <p>This is an NP-complete problem, I think, so it'll be impossible to have a very fast algorithm for any large data sets. </p>
<p>There's also the problem where you might have a schedule that is impossible to make. Given that that's not the case, something like this pseudocode is probably your best bet:</p>
<pre><code>sort players by priority, highest to lowest
start with empty schedule
for player in players:
for timeslot in player.preferences():
if timeslot is free:
schedule.fillslot(timeslot, player)
break
else:
#if we get here, it means this player couldn't be accomodated at all.
#you'll have to go through the slots that were filled and move another (higher-priority) player's time slot
</code></pre>
| 2 | 2008-10-06T18:29:26Z | [
"python",
"algorithm"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 175,612 | <p>There are several questions I'd ask before answering this queston:</p>
<ul>
<li>what happens if there is a conflict, i.e. a worse player books first, then a better player books the same court? Who wins? what happens for the loser?</li>
<li>do you let the best players play as long as the match runs, or do you have fixed time slots?</li>
<li>how often is the scheduling run - is it run interactively - so potentially someone could be told they can play, only to be told they can't; or is it run in a more batch manner - you put in requests, then get told later if you can have your slot. Or do users <em>set up a number of preferred times, and then the system has to maximise the number of people getting their most highly preferred times?</em></li>
</ul>
<p>As an aside, you can make it slightly less complex by re-writing the times as integer indexes (so you're dealing with integers rather than times).</p>
| 1 | 2008-10-06T18:35:00Z | [
"python",
"algorithm"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 175,683 | <p>Money. Allocate time slots based on who pays the most. In case of a draw don't let any of them have the slot.</p>
| -2 | 2008-10-06T18:53:38Z | [
"python",
"algorithm"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 175,697 | <p>You are describing a matching problem. Possible references are <a href="http://www.cs.sunysb.edu/~algorith/files/matching.shtml" rel="nofollow">the Stony Brook algorithm repository</a> and <a href="http://rads.stackoverflow.com/amzn/click/0321295358" rel="nofollow">Algorithm Design by Kleinberg and Tardos</a>. If the number of players is equal to the number of courts you can reach a stable matching - <a href="http://en.wikipedia.org/wiki/Stable_marriage_problem" rel="nofollow">The Stable Marriage Problem</a>. Other formulations become harder.</p>
| 2 | 2008-10-06T19:00:09Z | [
"python",
"algorithm"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 175,831 | <p>I would advise using a scoring algorithm. Basically construct a formula that pulls all the values you described into a single number. Who ever has the highest final score wins that slot. For example a simple formula might be:</p>
<pre><code>FinalScore = ( PlayerRanking * N1 ) + ( PlayerPreference * N2 )
</code></pre>
<p>Where N1, N2 are weights to control the formula.</p>
<p>This will allow you to get good (not perfect) results very quickly. We use this approach on a much more complex system with very good results.</p>
<p>You can add more variety to this by adding in factors for how many times the player has won or lost slots, or (as someone suggested) how much the player paid.</p>
<p>Also, you can use multiple passes to assign slots in the day. Use one strategy where it goes chronologically, one reverse chronologically, one that does the morning first, one that does the afternoon first, etc. Then sum the scores of the players that got the spots, and then you can decide strategy provided the best results.</p>
| 1 | 2008-10-06T19:34:44Z | [
"python",
"algorithm"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 175,941 | <p>Basically, you have the advantage that players have priorities; therefore, you sort the players by descending priority, and then you start allocating slots to them. The first gets their preferred slot, then the next takes his preferred among the free ones and so on. It's a O(N) algorithm.</p>
| 0 | 2008-10-06T20:00:10Z | [
"python",
"algorithm"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 178,185 | <h2>The basic Algorithm</h2>
<p>I'd sort the players by their rank, as the high ranked ones always push away the low ranked ones. Then you start with the player with the highest rank, give him what he asked for (if he really is the highest, he will always win, thus you can as well give him whatever he requested). Then I would start with the second highest one. If he requested something already taken by the highest, try to find a slot nearby and assign this slot to him. Now comes the third highest one. If he requested something already taken by the highest one, move him to a slot nearby. If this slot is already taken by the second highest one, move him to a slot some further away. Continue with all other players.</p>
<h3>Some tunings to consider:</h3>
<p>If multiple players can have the same rank, you may need to implement some "fairness". All players with equal rank will have a random order to each other if you sort them e.g. using QuickSort. You can get some some fairness, if you don't do it player for player, but rank for rank. You start with highest rank and the first player of this rank. Process his first request. However, before you process his second request, process the first request of the next player having highest rank and then of the third player having highest rank. The algorithm is the same as above, but assuming you have 10 players and player 1-4 are highest rank and players 5-7 are low and players 8-10 are very low, and every player made 3 requests, you process them as</p>
<pre><code>Player 1 - Request 1
Player 2 - Request 1
Player 3 - Request 1
Player 4 - Request 1
Player 1 - Request 2
Player 2 - Request 2
:
</code></pre>
<p>That way you have some fairness. You could also choose randomly within a ranking class each time, this could also provide some fairness.</p>
<p>You could implement fairness even across ranks. E.g. if you have 4 ranks, you could say</p>
<pre><code>Rank 1 - 50%
Rank 2 - 25%
Rank 3 - 12,5%
Rank 4 - 6,25%
</code></pre>
<p>(Just example values, you may use a different key than always multiplying by 0.5, e.g. multiplying by 0.8, causing the numbers to decrease slower)</p>
<p>Now you can say, you start processing with Rank 1, however once 50% of all Rank 1 requests have been fulfilled, you move on to Rank 2 and make sure 25% of their requests are fulfilled and so on. This way even a Rank 4 user can win over a Rank 1 user, somewhat defeating the initial algorithm, however you offer some fairness. Even a Rank 4 player can sometimes gets his request, he won't "run dry". Otherwise a Rank 1 player scheduling every request on the same time as a Rank 4 player will make sure a Rank 4 player has no chance to ever get a single request. This way there is at least a small chance he may get one.</p>
<p>After you made sure everyone had their minimal percentage processed (and the higher the rank, the more this is), you go back to top, starting with Rank 1 again and process the rest of their requests, then the rest of the Rank 2 requests and so on.</p>
<p><strong>Last but not least:</strong> You may want to define a maximum slot offset. If a slot is taken, the application should search for the nearest slot still free. However, what if this nearest slot is very far away? If I request a slot Monday at 4 PM and the application finds the next free one to be Wednesday on 9 AM, that's not really helpful for me, is it? I might have no time on Wednesday at all. So you may limit slot search to the same day and saying the slot might be at most 3 hours off. If no slot is found within that range, cancel the request. In that case you need to inform the player "We are sorry, but we could not find any nearby slot for you; please request a slot on another date/time and we will see if we can find a suitable slot there for you".</p>
| 3 | 2008-10-07T12:17:48Z | [
"python",
"algorithm"
] |
writing optimization function | 175,544 | <p>I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!</p>
<p>edit:</p>
<p>some clarifications-</p>
<p>the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times </p>
| 2 | 2008-10-06T18:21:53Z | 4,594,898 | <p>I think you should use genetic algorithm because:</p>
<ul>
<li>It is best suited for large problem instances.</li>
<li>It yields reduced time complexity on the price of inaccurate answer(Not the ultimate best)</li>
<li>You can specify constraints & preferences easily by adjusting fitness punishments for not met ones.</li>
<li>You can specify time limit for program execution.</li>
<li><p>The quality of solution depends on how much time you intend to spend solving the program..</p>
<p><a href="http://en.wikipedia.org/wiki/Genetic_algorithm" rel="nofollow">Genetic Algorithms Definition</a></p>
<p><a href="http://www.ai-junkie.com/ga/intro/gat1.html" rel="nofollow">Genetic Algorithms Tutorial</a></p>
<p><a href="http://www.codeproject.com/KB/recipes/GaClassSchedule.aspx" rel="nofollow">Class scheduling project with GA</a></p></li>
</ul>
<p>Also take a look at :<a href="http://stackoverflow.com/questions/2746309/best-fit-scheduling-algorithm/2749869#2749869">a similar question</a> and <a href="http://stackoverflow.com/questions/573670/which-algorithm-for-assigning-shifts-discrete-optimization-problem/4594818#4594818">another one</a></p>
| 0 | 2011-01-04T14:52:36Z | [
"python",
"algorithm"
] |
Python List vs. Array - when to use? | 176,011 | <p>If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.</p>
<p>What is the reason or circumstance where I would want to use the array module instead?</p>
<p>Is it for performance and memory optimization, or am I missing something obvious?</p>
| 195 | 2008-10-06T20:17:43Z | 176,033 | <p>My understanding is that arrays are stored more efficiently (i.e. as contiguous blocks of memory vs. pointers to Python objects), but I am not aware of any performance benefit. Additionally, with arrays you must store primitives of the same type, whereas lists can store anything.</p>
| 8 | 2008-10-06T20:22:50Z | [
"python",
"arrays",
"list"
] |
Python List vs. Array - when to use? | 176,011 | <p>If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.</p>
<p>What is the reason or circumstance where I would want to use the array module instead?</p>
<p>Is it for performance and memory optimization, or am I missing something obvious?</p>
| 195 | 2008-10-06T20:17:43Z | 176,043 | <p>For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see <a href="http://docs.python.org/library/array.html#module-array">docs</a>), with access to more C-like types such as signed/unsigned short or double, which are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.</p>
| 42 | 2008-10-06T20:24:38Z | [
"python",
"arrays",
"list"
] |
Python List vs. Array - when to use? | 176,011 | <p>If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.</p>
<p>What is the reason or circumstance where I would want to use the array module instead?</p>
<p>Is it for performance and memory optimization, or am I missing something obvious?</p>
| 195 | 2008-10-06T20:17:43Z | 176,047 | <p>Array can only be used for specific types, whereas lists can be used for any object.</p>
<p>Arrays can also only data of one type, whereas a list can have entries of various object types.</p>
<p>Arrays are also more efficient for some numerical computation.</p>
| 4 | 2008-10-06T20:25:05Z | [
"python",
"arrays",
"list"
] |
Python List vs. Array - when to use? | 176,011 | <p>If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.</p>
<p>What is the reason or circumstance where I would want to use the array module instead?</p>
<p>Is it for performance and memory optimization, or am I missing something obvious?</p>
| 195 | 2008-10-06T20:17:43Z | 176,073 | <p>If you're going to be using arrays, consider the numpy or scipy packages, which give you arrays with a lot more flexibility.</p>
| 2 | 2008-10-06T20:30:54Z | [
"python",
"arrays",
"list"
] |
Python List vs. Array - when to use? | 176,011 | <p>If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.</p>
<p>What is the reason or circumstance where I would want to use the array module instead?</p>
<p>Is it for performance and memory optimization, or am I missing something obvious?</p>
| 195 | 2008-10-06T20:17:43Z | 176,589 | <p>Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in <a href="http://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost">amortized constant time</a>. If you need to shrink and grow your array time-efficiently and without hassle, they are the way to go. But they use <strong>a lot more space than C arrays</strong>.</p>
<p>The <code>array.array</code> type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data, all of the same type, and so it uses only <code>sizeof(one object) * length</code> bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, <code>ioctl</code> or <code>fctnl</code>). It's also a good way to represent a <strong>mutable</strong> string (<code>array('B', bytes)</code>) until that actually becomes available in Python 3.0.</p>
<p>However, if you want to do <strong>math</strong> on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.</p>
<p><strong>To make a long story short</strong>: <code>array.array</code> is useful when you need a homogeneous C array of data for reasons <em>other than doing math</em>.</p>
| 241 | 2008-10-06T23:11:06Z | [
"python",
"arrays",
"list"
] |
Python List vs. Array - when to use? | 176,011 | <p>If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.</p>
<p>What is the reason or circumstance where I would want to use the array module instead?</p>
<p>Is it for performance and memory optimization, or am I missing something obvious?</p>
| 195 | 2008-10-06T20:17:43Z | 178,511 | <p>The standard library arrays are useful for binary I/O, such as translating a list of ints to a string to write to, say, a wave file. That said, as many have already noted, if you're going to do any real work then you should consider using NumPy.</p>
| 4 | 2008-10-07T13:47:01Z | [
"python",
"arrays",
"list"
] |
Python List vs. Array - when to use? | 176,011 | <p>If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.</p>
<p>What is the reason or circumstance where I would want to use the array module instead?</p>
<p>Is it for performance and memory optimization, or am I missing something obvious?</p>
| 195 | 2008-10-06T20:17:43Z | 178,590 | <p>The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). Most of the time, the array module is used to interface with C code. To give you a more direct answer to your question about performance:</p>
<p>Arrays are more efficient than lists for some uses. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory. GvR has an <a href="http://www.python.org/doc/essays/list2str/">optimization anecdote</a> in which the array module comes out to be the winner (long read, but worth it).</p>
<p>On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.</p>
<p>TL;DR I'd only use an array if you had an exceptional optimization need or you need to interface with C code (and can't use <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/">pyrex</a>).</p>
| 19 | 2008-10-07T14:00:40Z | [
"python",
"arrays",
"list"
] |
Writing a reliable, totally-ordered multicast system in Python | 176,179 | <p>I have to write a reliable, totally-ordered multicast system from scratch in Python. I can't use any external libraries. I'm allowed to use a central sequencer.</p>
<p>There seems to be two immediate approaches:</p>
<ol>
<li>write an efficient system, attaching a unique id to each multicasted message,
having the sequencer multicast sequence numbers for the message id's it receives,
and sending back and forth ACK's and NACK's.</li>
<li>write an inefficient flooding system, where each multicaster simply re-sends each
message it receives once (unless it was sent by that particular multicaster.)</li>
</ol>
<p>I'm allowed to use the second option, and am inclined to do so.</p>
<p>I'm currently multicasting UDP messages (which seems to be the only option,) but that means that some messages might get lost. That means I have to be able to uniquely identify each sent UDP message, so that it can be re-sent according to #2. Should I really generate unique numbers (e.g. using the sender address and a counter) and pack them into each and every UDP message sent? How would I go about doing that? And how do I receive a single UDP message in Python, and not a stream of data (i.e. <code>socket.recv</code>)?</p>
| 4 | 2008-10-06T21:03:55Z | 176,287 | <p>The flooding approach can cause a bad situation to get worse. If messages are dropped due to high network load, having every node resend every message will only make the situation worse.</p>
<p>The best approach to take depends on the nature of the data you are sending. For example:</p>
<ol>
<li>Multimedia data: no retries, a dropped packet is a dropped frame, which won't matter when the next frame gets there anyway.</li>
<li>Fixed period data: Recipient node keeps a timer that is reset each time an update is received. If the time expires, it requests the missing update from the master node. Retries can be unicast to the requesting node.</li>
</ol>
<p>If neither of these situations applies (every packet has to be received by every node, and the packet timing is unpredictable, so recipients can't detect missed packets on their own), then your options include:</p>
<ol>
<li>Explicit ACK from every node for each packet. Sender retries (unicast) any packet that is not ACKed.</li>
<li>TCP-based grid approach, where each node is manually repeats received packets to neighbor nodes, relying on TCP mechanisms to ensure delivery.</li>
</ol>
<p>You could possibly rely on recipients noticing a missed packet upon reception of one with a later sequence number, but this requires the sender to keep the packet around until at least one additional packet has been sent. Requiring positive ACKs is more reliable (and provable).</p>
| 4 | 2008-10-06T21:32:46Z | [
"python",
"sockets",
"networking",
"ip",
"multicast"
] |
Writing a reliable, totally-ordered multicast system in Python | 176,179 | <p>I have to write a reliable, totally-ordered multicast system from scratch in Python. I can't use any external libraries. I'm allowed to use a central sequencer.</p>
<p>There seems to be two immediate approaches:</p>
<ol>
<li>write an efficient system, attaching a unique id to each multicasted message,
having the sequencer multicast sequence numbers for the message id's it receives,
and sending back and forth ACK's and NACK's.</li>
<li>write an inefficient flooding system, where each multicaster simply re-sends each
message it receives once (unless it was sent by that particular multicaster.)</li>
</ol>
<p>I'm allowed to use the second option, and am inclined to do so.</p>
<p>I'm currently multicasting UDP messages (which seems to be the only option,) but that means that some messages might get lost. That means I have to be able to uniquely identify each sent UDP message, so that it can be re-sent according to #2. Should I really generate unique numbers (e.g. using the sender address and a counter) and pack them into each and every UDP message sent? How would I go about doing that? And how do I receive a single UDP message in Python, and not a stream of data (i.e. <code>socket.recv</code>)?</p>
| 4 | 2008-10-06T21:03:55Z | 176,501 | <p>The approach you take is going to depend very much on the nature of the data that you're sending, the scale of your network and the quantity of data you're sending. In particular it is going to depend on the number of targets each of your nodes is connected to.</p>
<p>If you're expecting this to scale to a large number of targets for each node and a large quantity of data then you may well find that the overhead of adding an ACK/NAK to every packet is sufficient to adversely limit your throughput, particularly when you add retransmissions into the mix.</p>
<p>As Frank Szczerba has said multimedia data has the benefit of being able to recover from lost packets. If you have any control over the data that you're sending you should try to design the payloads so that you minimise the susceptibility to dropped packets.</p>
<p>If the data that you're sending cannot tolerate dropped packets <em>and</em> you're trying to scale to high utilisation of your network then perhaps udp is not the best protocol to use. Implementing a series of tcp proxies (where each node retransmits, unicast, to all other connected nodes - similar to your flooding idea) would be a more reliable mechanism.</p>
<p>With all of that said, have you considered using true multicast for this application?</p>
<p><hr /></p>
<p>Just saw the "homework" tag... these suggestions might not be appropriate for a homework problem.</p>
| 1 | 2008-10-06T22:42:25Z | [
"python",
"sockets",
"networking",
"ip",
"multicast"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 176,226 | <p>I found these two books very useful when I used to build full-text search engines.</p>
<p><a href="http://rads.stackoverflow.com/amzn/click/0134638379">Information Retrieval</a></p>
<p><a href="http://rads.stackoverflow.com/amzn/click/1558605703">Managing Gigabytes</a></p>
| 5 | 2008-10-06T21:14:52Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 176,245 | <p>As always start in <a href="http://en.wikipedia.org/wiki/Index_(search_engine)" rel="nofollow">wikipedia</a>. First start is usually building an inverted index.</p>
| 2 | 2008-10-06T21:21:49Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 176,251 | <p>See also a question I asked: <a href="http://stackoverflow.com/questions/47762/how-to-ranking-search-results">How-to: Ranking Search Results</a>.</p>
<p>Surely there are more approaches, but this is the one I'm using for now.</p>
| 0 | 2008-10-06T21:23:36Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 176,374 | <p>First build your index.
Go through the input, split into words<br />
For each word check if it is already in the index, if it is add the current record number to the index list, if not add the word and record number.<br />
To look up a word go to the (possibly sorted) index and return all the record numbers for that word.<br />
It's very esy to do this for a reasoable size list using Python's builtin storage types.</p>
<p>As an extra refinement you only want to store the base part of a word, eg 'find' for 'finding' - look up stemming algorithms. </p>
| 1 | 2008-10-06T21:59:14Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 176,521 | <p>Honestly, smarter people than I have figured this stuff out. I'd load up the solr app and make json calls from my appengine app and let solr take care of indexing. </p>
| 0 | 2008-10-06T22:49:56Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 176,549 | <p>Here's an original idea:</p>
<p><em>Don't</em> build an index. Seriously.</p>
<p>I was faced with a similar progblem some time ago. I needed a fast method to search megs and megs of text that came from documentation. I needed to match not just words, but word proximity in large documents (is this word <em>near</em> that word). I just ended up writing it in C, and the speed of it surprised me. It was fast enough that it didn't need any optimizing or indexing.</p>
<p>With the speed of today's computers, if you write code that runs straight on the metal (compiled code), you often don't need an order log(n) type algorithm to get the performance you need.</p>
| 3 | 2008-10-06T22:58:42Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 176,972 | <p>Read Tim Bray's <a href="http://www.tbray.org/ongoing/When/200x/2003/07/30/OnSearchTOC">series of posts on the subject</a>.</p>
<blockquote>
<ul>
<li>Background</li>
<li>Usage of search engines</li>
<li>Basics</li>
<li>Precision and recall</li>
<li>Search engne intelligence</li>
<li>Tricky search terms</li>
<li>Stopwords</li>
<li>Metadata</li>
<li>Internationalization</li>
<li>Ranking results</li>
<li>XML</li>
<li>Robots</li>
<li>Requirements list</li>
</ul>
</blockquote>
| 6 | 2008-10-07T02:06:11Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 177,030 | <p>I would not build it yourself, if possible.</p>
<p>App Engine includes the basics of a Full Text searching engine, and there is a <a href="http://appengineguy.com/2008/06/how-to-full-text-search-in-google-app.html" rel="nofollow">great blog post here</a> that describes how to use it.</p>
<p>There is also a <a href="http://code.google.com/p/googleappengine/issues/detail?id=217" rel="nofollow">feature request in the bug tracker</a> that seems to be getting some attention lately, so you may want to hold out, if you can, until that is implemented.</p>
| 3 | 2008-10-07T02:30:26Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 177,046 | <p>I just found this article this weekend: <a href="http://www.perl.com/pub/a/2003/02/19/engine.html" rel="nofollow">http://www.perl.com/pub/a/2003/02/19/engine.html</a></p>
<p>Looks not too complicated to do a simple one (though it would need heavy optimizing to be an enterprise type solution for sure). I plan on trying a proof of concept with some data from Project Gutenberg.</p>
<p>If you're just looking for something you can explore and learn from I think this is a good start.</p>
| 0 | 2008-10-07T02:40:28Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 177,904 | <p><a href="http://en.wikipedia.org/wiki/Lucene" rel="nofollow">Lucene</a> or <a href="http://www.searchtools.com/tools/autonomy.html" rel="nofollow">Autonomy</a>! These are not out of the box solutions for you. You will have to write wrappers on top of their interfaces.<br />
They certainly do take care of the stemming, grammar , relational operators etc</p>
| 2 | 2008-10-07T10:41:51Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 181,086 | <p>The book <a href="http://www-csli.stanford.edu/~hinrich/information-retrieval-book.html" rel="nofollow">Introduction to Information Retrieval</a> provides a good introduction to the field.</p>
<p>A dead-tree version is published by Cambridge University Press, but you can also find a free online edition (in HTML and PDF) following the link above.</p>
| 1 | 2008-10-08T01:37:25Z | [
"python",
"full-text-search"
] |
Building a full text search engine: where to start | 176,213 | <p>I want to write a web application using <a href="http://code.google.com/appengine/">Google App Engine</a> (so the reference language would be <strong>Python</strong>). My application needs a simple search engine, so the users would be able to find data specifying keywords.</p>
<p>For example, if I have one table with those rows:</p>
<blockquote>
<p>1 Office space<br> 2 2001: A space
odyssey<br> 3 Brazil</p>
</blockquote>
<p>and the user queries for "space", rows 1 and 2 would be returned. If the user queries for "office space", the result should be rows 1 and 2 too (row 1 first).</p>
<p>What are the technical guidelines/algorithms to do this in a simple way?<br>
Can you give me good pointers to the theory behind this?<br></p>
<p>Thanks.</p>
<p><em>Edit</em>: I'm not looking for anything complex here (say, indexing tons of data).</p>
| 7 | 2008-10-06T21:10:44Z | 181,138 | <p>Look into the book "Managing Gigabytes" it covers storage and retrieval of huge amounts of plain text data -- eg. both compression and actual searching, and a variety of the algorithms that can be used for each.</p>
<p>Also for plain text retrieval you're best off using a vector based search system rather than a keyword->document indexing system as vector based systems can be much faster, and, more importantly can provide relevancy ranking relatively trivially.</p>
| 0 | 2008-10-08T02:26:31Z | [
"python",
"full-text-search"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 176,921 | <pre><code>>>> ["foo", "bar", "baz"].index("bar")
1
</code></pre>
<p>Reference: <a href="http://docs.python.org/2/tutorial/datastructures.html#more-on-lists">Data Structures > More on Lists</a></p>
| 1,857 | 2008-10-07T01:40:49Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 178,399 | <p>One thing that is really helpful in learning Python is to use the interactive help function:</p>
<pre><code>>>> help(["foo", "bar", "baz"])
Help on list object:
class list(object)
...
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value
|
</code></pre>
<p>which will often lead you to the method you are looking for.</p>
| 615 | 2008-10-07T13:19:56Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 7,241,298 | <p><code>index()</code> returns the <strong>first</strong> index of value!</p>
<blockquote>
<p>| index(...)<br>
| L.index(value, [start, [stop]]) -> integer -- return first index of value</p>
</blockquote>
<pre><code>def all_indices(value, qlist):
indices = []
idx = -1
while True:
try:
idx = qlist.index(value, idx+1)
indices.append(idx)
except ValueError:
break
return indices
all_indices("foo", ["foo","bar","baz","foo"])
</code></pre>
| 75 | 2011-08-30T09:40:54Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 12,054,409 | <pre><code>a = ["foo","bar","baz",'bar','any','much']
b = [item for item in range(len(a)) if a[item] == 'bar']
</code></pre>
| 34 | 2012-08-21T12:01:54Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 16,034,499 | <p>Problem will arrise if the element is not in the list. You can use this function, it handles the issue:</p>
<pre><code># if element is found it returns index of element else returns -1
def find_element_in_list(element, list_element):
try:
index_element = list_element.index(element)
return index_element
except ValueError:
return None
</code></pre>
| 31 | 2013-04-16T10:19:36Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 16,593,099 | <p>All of the proposed functions here reproduce inherent language behavior but obscure what's going on.</p>
<pre><code>[i for i in range(len(mylist)) if mylist[i]==myterm] # get the indices
[each for each in mylist if each==myterm] # get the items
mylist.index(myterm) if myterm in mylist else None # get the first index and fail quietly
</code></pre>
<p>Why write a function with exception handling if the language provides the methods to do what you want itself?</p>
| 11 | 2013-05-16T16:45:29Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 16,807,733 | <p>Simply you can go with</p>
<pre><code>a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']
res = [[x[0] for x in a].index(y) for y in b]
</code></pre>
| 6 | 2013-05-29T07:17:15Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 16,822,116 | <p>Another option</p>
<pre><code>>>> a = ['red', 'blue', 'green', 'red']
>>> b = 'red'
>>> offset = 0;
>>> indices = list()
>>> for i in range(a.count(b)):
... indices.append(a.index(b,offset))
... offset = indices[-1]+1
...
>>> indices
[0, 3]
>>>
</code></pre>
| 4 | 2013-05-29T19:17:21Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 17,202,481 | <p>I'm honestly surprised no one has mentioned <a href="http://docs.python.org/2/library/functions.html#enumerate"><code>enumerate()</code></a> yet:</p>
<pre><code>for i, j in enumerate(['foo', 'bar', 'baz']):
if j == 'bar':
print i
</code></pre>
<p>This can be more useful than index if there are duplicates in the list, because index() only returns the first occurrence, while enumerate returns all occurrences.</p>
<p>As a list comprehension:</p>
<pre><code>[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']
</code></pre>
<hr>
<p>Here's also another small solution with <a href="http://docs.python.org/2/library/itertools.html#itertools.count"><code>itertools.count()</code></a> (which is pretty much the same approach as enumerate):</p>
<pre><code>from itertools import izip as zip, count # izip for maximum efficiency
[i for i, j in zip(count(), ['foo', 'bar', 'baz']) if j == 'foo']
</code></pre>
<p>This is more efficient for larger lists than using <code>enumerate()</code>:</p>
<pre><code>$ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ['foo', 'bar', 'baz']*500) if j == 'foo']"
10000 loops, best of 3: 174 usec per loop
$ python -m timeit "[i for i, j in enumerate(['foo', 'bar', 'baz']*500) if j == 'foo']"
10000 loops, best of 3: 196 usec per loop
</code></pre>
| 262 | 2013-06-19T22:31:52Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 17,300,987 | <p>To get all indexes:</p>
<pre><code> indexes = [i for i,x in enumerate(xs) if x == 'foo']
</code></pre>
| 63 | 2013-06-25T15:07:55Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 22,708,420 | <p>A variant on the answer from FMc and user7177 will give a dict that can return all indices for any entry:</p>
<pre><code>>>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
>>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
>>> l['foo']
[0, 5]
>>> l ['much']
[6]
>>> l
{'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
>>>
</code></pre>
<p>You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called.</p>
| 4 | 2014-03-28T09:11:57Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 23,862,698 | <p>You have to set a condition to check if the element you're searching is in the list</p>
<pre><code>if 'your_element' in mylist:
print mylist.index('your_element')
else:
print None
</code></pre>
| 22 | 2014-05-26T04:26:52Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 27,712,517 | <p>And now, for something completely different, checking for the existence of the item before getting the index. The nice thing about this approach is the function always returns a list of indices -- even if it is an empty list. It works with strings as well.</p>
<pre><code>def indices(l, val):
"""always returns a list containing the indices of val in l
"""
retval = []
last = 0
while val in l[last:]:
i = l[last:].index(val)
retval.append(last + i)
last += i + 1
return retval
l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')
</code></pre>
<p>When pasted into an interactive python window:</p>
<pre><code>Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(l, val):
... """always returns a list containing the indices of val in l
... """
... retval = []
... last = 0
... while val in l[last:]:
... i = l[last:].index(val)
... retval.append(last + i)
... last += i + 1
... return retval
...
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>>
</code></pre>
| 2 | 2014-12-30T21:03:10Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 30,283,031 | <p>This solution is not as powerful as others, but if you're a beginner and only know about <code>for</code>loops it's still possible to find the first index of an item while avoiding the ValueError:</p>
<pre><code>def find_element(p,t):
i = 0
for e in p:
if e == t:
return i
else:
i +=1
return -1
</code></pre>
| 3 | 2015-05-17T03:21:00Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 31,230,699 | <pre><code>name ="bar"
list = [["foo", 1], ["bar", 2], ["baz", 3]]
new_list=[]
for item in list:
new_list.append(item[0])
print(new_list)
try:
location= new_list.index(name)
except:
location=-1
print (location)
</code></pre>
<p>This accounts for if the string is not in the list too, if it isn't in the list then location = -1</p>
| 0 | 2015-07-05T13:12:19Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 33,644,671 | <p>all indexes with zip function</p>
<pre><code>get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print get_indexes(2,[1,2,3,4,5,6,3,2,3,2])
print get_indexes('f','xsfhhttytffsafweef')
</code></pre>
| 5 | 2015-11-11T05:16:38Z | [
"python",
"list"
] |
Finding the index of an item given a list containing it in Python | 176,918 | <p>For a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, what's the cleanest way to get its index (1) in Python?</p>
| 1,222 | 2008-10-07T01:39:38Z | 33,765,024 | <p>If you want all indexes, then you can use numpy:</p>
<pre><code>import numpy as np
array = [1,2,1,3,4,5,1]
item = 1
np_array = np.array(array)
item_index = np.where(np_array==item)
print item_index
# Out: (array([0, 2, 6], dtype=int64),)
</code></pre>
<p>It is clear, readable solution.</p>
| 8 | 2015-11-17T19:05:23Z | [
"python",
"list"
] |
Offline access to MoinMoin wiki using Google Gears | 176,955 | <p>How to add offline access functionality to <a href="http://moinmo.in" rel="nofollow">MoinMoin wiki</a>?</p>
<p>As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.</p>
<p>Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.</p>
<p>An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.</p>
<p>Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.</p>
| 3 | 2008-10-07T01:53:38Z | 176,980 | <p>If you have the freedom to change the wiki software, I might suggest looking at <a href="http://ikiwiki.info" rel="nofollow">ikiwiki</a>. You can set it up so the pages are backed by a real VCS such as Git, in which case you can clone the whole wiki and read and even update it offline.</p>
| 2 | 2008-10-07T02:10:26Z | [
"python",
"wiki",
"offline",
"google-gears",
"moinmoin"
] |
Offline access to MoinMoin wiki using Google Gears | 176,955 | <p>How to add offline access functionality to <a href="http://moinmo.in" rel="nofollow">MoinMoin wiki</a>?</p>
<p>As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.</p>
<p>Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.</p>
<p>An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.</p>
<p>Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.</p>
| 3 | 2008-10-07T01:53:38Z | 177,321 | <p>Have a look at <a href="http://moinmo.in/DesktopEdition" rel="nofollow">MoinMoin Desktop Edition</a>.</p>
| -1 | 2008-10-07T05:33:30Z | [
"python",
"wiki",
"offline",
"google-gears",
"moinmoin"
] |
Offline access to MoinMoin wiki using Google Gears | 176,955 | <p>How to add offline access functionality to <a href="http://moinmo.in" rel="nofollow">MoinMoin wiki</a>?</p>
<p>As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.</p>
<p>Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.</p>
<p>An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.</p>
<p>Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.</p>
| 3 | 2008-10-07T01:53:38Z | 178,209 | <p><em>By using Gears with the Firefox Greasemonkey plugin, you can inject Gears code into any website that you want. Don't wait for your favorite website to enable offline support -- do it yourself.</em> <a href="http://code.google.com/apis/gears/articles/gearsmonkey.html" rel="nofollow">http://code.google.com/apis/gears/articles/gearsmonkey.html</a></p>
| 2 | 2008-10-07T12:27:47Z | [
"python",
"wiki",
"offline",
"google-gears",
"moinmoin"
] |
Offline access to MoinMoin wiki using Google Gears | 176,955 | <p>How to add offline access functionality to <a href="http://moinmo.in" rel="nofollow">MoinMoin wiki</a>?</p>
<p>As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.</p>
<p>Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.</p>
<p>An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.</p>
<p>Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.</p>
| 3 | 2008-10-07T01:53:38Z | 1,385,496 | <p>If you're patient enough, MoinMoin release 2.0 will ship with Mercurial DVCS backend, so you won't have to switch. More info on <a href="http://moinmo.in/MoinMoin2.0" rel="nofollow">http://moinmo.in/MoinMoin2.0</a></p>
| 1 | 2009-09-06T11:53:57Z | [
"python",
"wiki",
"offline",
"google-gears",
"moinmoin"
] |
Offline access to MoinMoin wiki using Google Gears | 176,955 | <p>How to add offline access functionality to <a href="http://moinmo.in" rel="nofollow">MoinMoin wiki</a>?</p>
<p>As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.</p>
<p>Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.</p>
<p>An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.</p>
<p>Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.</p>
| 3 | 2008-10-07T01:53:38Z | 1,932,825 | <ul>
<li>if you want to do that on servers see HelpOnSynchronisation in moinmoin + DesktopEdition </li>
<li>if locally, use <a href="http://www.cis.upenn.edu/~bcpierce/unison/" rel="nofollow">unison</a> + DesktopEdition . be careful to ignore cache and such. this will allow 2-way synchronisation.</li>
</ul>
| 1 | 2009-12-19T12:42:53Z | [
"python",
"wiki",
"offline",
"google-gears",
"moinmoin"
] |
SQL Absolute value across columns | 177,284 | <p>I have a table that looks something like this:</p>
<pre>
word big expensive smart fast
dog 9 -10 -20 4
professor 2 4 40 -7
ferrari 7 50 0 48
alaska 10 0 1 0
gnat -3 0 0 0
</pre>
<p>The + and - values are associated with the word, so professor is smart and dog is not smart. Alaska is big, as a proportion of the total value associated with its entries, and the opposite is true of gnat.</p>
<p>Is there a good way to get the absolute value of the number farthest from zero, and some token whether absolute value =/= value? Relatedly, how might I calculate whether the results for a given value are proportionately large with respect to the other values? I would write something to format the output to the effect of: "dog: not smart, probably not expensive; professor smart; ferrari: fast, expensive; alaska: big; gnat: probably small." (The formatting is not a question, just an illustration, I am stuck on the underlying queries.) </p>
<p>Also, the rest of the program is python, so if there is any python solution with normal dbapi modules or a more abstract module, any help appreciated.</p>
| 1 | 2008-10-07T05:06:31Z | 177,302 | <p>Can you use the built-in database aggregate functions like MAX(column)?</p>
| 0 | 2008-10-07T05:22:33Z | [
"python",
"mysql",
"sql",
"oracle",
"postgresql"
] |
SQL Absolute value across columns | 177,284 | <p>I have a table that looks something like this:</p>
<pre>
word big expensive smart fast
dog 9 -10 -20 4
professor 2 4 40 -7
ferrari 7 50 0 48
alaska 10 0 1 0
gnat -3 0 0 0
</pre>
<p>The + and - values are associated with the word, so professor is smart and dog is not smart. Alaska is big, as a proportion of the total value associated with its entries, and the opposite is true of gnat.</p>
<p>Is there a good way to get the absolute value of the number farthest from zero, and some token whether absolute value =/= value? Relatedly, how might I calculate whether the results for a given value are proportionately large with respect to the other values? I would write something to format the output to the effect of: "dog: not smart, probably not expensive; professor smart; ferrari: fast, expensive; alaska: big; gnat: probably small." (The formatting is not a question, just an illustration, I am stuck on the underlying queries.) </p>
<p>Also, the rest of the program is python, so if there is any python solution with normal dbapi modules or a more abstract module, any help appreciated.</p>
| 1 | 2008-10-07T05:06:31Z | 177,308 | <p>Words listed by absolute value of big:</p>
<pre><code>select word, big from myTable order by abs(big)
</code></pre>
<p>totals for each category:</p>
<pre><code>select sum(abs(big)) as sumbig,
sum(abs(expensive)) as sumexpensive,
sum(abs(smart)) as sumsmart,
sum(abs(fast)) as sumfast
from MyTable;
</code></pre>
| 3 | 2008-10-07T05:25:12Z | [
"python",
"mysql",
"sql",
"oracle",
"postgresql"
] |
SQL Absolute value across columns | 177,284 | <p>I have a table that looks something like this:</p>
<pre>
word big expensive smart fast
dog 9 -10 -20 4
professor 2 4 40 -7
ferrari 7 50 0 48
alaska 10 0 1 0
gnat -3 0 0 0
</pre>
<p>The + and - values are associated with the word, so professor is smart and dog is not smart. Alaska is big, as a proportion of the total value associated with its entries, and the opposite is true of gnat.</p>
<p>Is there a good way to get the absolute value of the number farthest from zero, and some token whether absolute value =/= value? Relatedly, how might I calculate whether the results for a given value are proportionately large with respect to the other values? I would write something to format the output to the effect of: "dog: not smart, probably not expensive; professor smart; ferrari: fast, expensive; alaska: big; gnat: probably small." (The formatting is not a question, just an illustration, I am stuck on the underlying queries.) </p>
<p>Also, the rest of the program is python, so if there is any python solution with normal dbapi modules or a more abstract module, any help appreciated.</p>
| 1 | 2008-10-07T05:06:31Z | 177,311 | <p>abs value fartherest from zero:</p>
<pre><code>select max(abs(mycol)) from mytbl
</code></pre>
<p>will be zero if the value is negative:</p>
<pre><code>select n+abs(mycol)
from zzz
where abs(mycol)=(select max(abs(mycol)) from mytbl);
</code></pre>
| 2 | 2008-10-07T05:28:46Z | [
"python",
"mysql",
"sql",
"oracle",
"postgresql"
] |
SQL Absolute value across columns | 177,284 | <p>I have a table that looks something like this:</p>
<pre>
word big expensive smart fast
dog 9 -10 -20 4
professor 2 4 40 -7
ferrari 7 50 0 48
alaska 10 0 1 0
gnat -3 0 0 0
</pre>
<p>The + and - values are associated with the word, so professor is smart and dog is not smart. Alaska is big, as a proportion of the total value associated with its entries, and the opposite is true of gnat.</p>
<p>Is there a good way to get the absolute value of the number farthest from zero, and some token whether absolute value =/= value? Relatedly, how might I calculate whether the results for a given value are proportionately large with respect to the other values? I would write something to format the output to the effect of: "dog: not smart, probably not expensive; professor smart; ferrari: fast, expensive; alaska: big; gnat: probably small." (The formatting is not a question, just an illustration, I am stuck on the underlying queries.) </p>
<p>Also, the rest of the program is python, so if there is any python solution with normal dbapi modules or a more abstract module, any help appreciated.</p>
| 1 | 2008-10-07T05:06:31Z | 177,637 | <p>Asking the question helped clarify the issue; here is a function that gets more at what I am trying to do. Is there a way to represent some of the stuff in ¶2 above, or a more efficient way to do in SQL or python what I am trying to accomplish in <code>show_distinct</code>?</p>
<pre><code>#!/usr/bin/env python
import sqlite3
conn = sqlite3.connect('so_question.sqlite')
cur = conn.cursor()
cur.execute('create table soquestion (word, big, expensive, smart, fast)')
cur.execute("insert into soquestion values ('dog', 9, -10, -20, 4)")
cur.execute("insert into soquestion values ('professor', 2, 4, 40, -7)")
cur.execute("insert into soquestion values ('ferrari', 7, 50, 0, 48)")
cur.execute("insert into soquestion values ('alaska', 10, 0, 1, 0)")
cur.execute("insert into soquestion values ('gnat', -3, 0, 0, 0)")
cur.execute("select * from soquestion")
all = cur.fetchall()
definition_list = ['word', 'big', 'expensive', 'smart', 'fast']
def show_distinct(db_tuple, def_list=definition_list):
minimum = min(db_tuple[1:])
maximum = max(db_tuple[1:])
if abs(minimum) > maximum:
print db_tuple[0], 'is not', def_list[list(db_tuple).index(minimum)]
elif maximum > abs(minimum):
print db_tuple[0], 'is', def_list[list(db_tuple).index(maximum)]
else:
print 'no distinct value'
for item in all:
show_distinct(item)
</code></pre>
<p>Running this gives:</p>
<pre>
dog is not smart
professor is smart
ferrari is expensive
alaska is big
gnat is not big
>>>
</pre>
| 0 | 2008-10-07T08:41:06Z | [
"python",
"mysql",
"sql",
"oracle",
"postgresql"
] |
SQL Absolute value across columns | 177,284 | <p>I have a table that looks something like this:</p>
<pre>
word big expensive smart fast
dog 9 -10 -20 4
professor 2 4 40 -7
ferrari 7 50 0 48
alaska 10 0 1 0
gnat -3 0 0 0
</pre>
<p>The + and - values are associated with the word, so professor is smart and dog is not smart. Alaska is big, as a proportion of the total value associated with its entries, and the opposite is true of gnat.</p>
<p>Is there a good way to get the absolute value of the number farthest from zero, and some token whether absolute value =/= value? Relatedly, how might I calculate whether the results for a given value are proportionately large with respect to the other values? I would write something to format the output to the effect of: "dog: not smart, probably not expensive; professor smart; ferrari: fast, expensive; alaska: big; gnat: probably small." (The formatting is not a question, just an illustration, I am stuck on the underlying queries.) </p>
<p>Also, the rest of the program is python, so if there is any python solution with normal dbapi modules or a more abstract module, any help appreciated.</p>
| 1 | 2008-10-07T05:06:31Z | 177,898 | <p>The problem seems to be that you mainly want to work within one row, and these type of questions are hard to answer in SQL.</p>
<p>I'd try to turn the structure you mentioned into a more "atomic" fact table like</p>
<pre><code>word property value
</code></pre>
<p>either by redesigning the underlying table (if possible and if that makes sense regarding the rest of the application), or by defining a view that does this for you, like</p>
<pre><code>select word, 'big' as property, big as value from soquestion
UNION ALLL
select word, 'expensive', expensive from soquestion
UNION ALL
...
</code></pre>
<p>This allows you to ask for the max value for each word:</p>
<pre><code>select word, max(value),
(select property from soquestion t2
where t1.word = t2.word and t2.value = max(t1.value))
from soquestion t1
group by word
</code></pre>
<p>Still a little awkward, but most logic will be in SQL, not in your programming language of choice.</p>
| 1 | 2008-10-07T10:39:37Z | [
"python",
"mysql",
"sql",
"oracle",
"postgresql"
] |
Alert boxes in Python? | 177,287 | <p>Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.</p>
<p>This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.</p>
<p>Update:<br />
This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.</p>
| 16 | 2008-10-07T05:08:36Z | 177,312 | <p>what about this:</p>
<pre><code>import win32api
win32api.MessageBox(0, 'hello', 'title')
</code></pre>
<p>Additionally:</p>
<pre><code>win32api.MessageBox(0, 'hello', 'title', 0x00001000)
</code></pre>
<p>will make the box appear on top of other windows, for urgent messages. See <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645505%28v=vs.85%29.aspx">MessageBox function</a> for other options.</p>
| 28 | 2008-10-07T05:29:15Z | [
"python",
"alerts"
] |
Alert boxes in Python? | 177,287 | <p>Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.</p>
<p>This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.</p>
<p>Update:<br />
This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.</p>
| 16 | 2008-10-07T05:08:36Z | 177,316 | <p>Start an app as a background process that either has a TCP port bound to localhost, or communicates through a file -- your daemon has the file open, and then you <code>echo "foo" > c:\your\file</code>. After, say, 1 second of no activity, you display the message and truncate the file.</p>
| -1 | 2008-10-07T05:30:52Z | [
"python",
"alerts"
] |
Alert boxes in Python? | 177,287 | <p>Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.</p>
<p>This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.</p>
<p>Update:<br />
This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.</p>
| 16 | 2008-10-07T05:08:36Z | 11,831,178 | <p>You can use win32 library in Python, this is classical example of OK or Cancel. </p>
<pre><code>import win32api
import win32com.client
import pythoncom
result = win32api.MessageBox(None,"Do you want to open a file?", "title",1)
if result == 1:
print 'Ok'
elif result == 2:
print 'cancel'
</code></pre>
<p>The collection:</p>
<pre><code>win32api.MessageBox(0,"msgbox", "title")
win32api.MessageBox(0,"ok cancel?", "title",1)
win32api.MessageBox(0,"abort retry ignore?", "title",2)
win32api.MessageBox(0,"yes no cancel?", "title",3)
</code></pre>
| 1 | 2012-08-06T15:23:17Z | [
"python",
"alerts"
] |
Alert boxes in Python? | 177,287 | <p>Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.</p>
<p>This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.</p>
<p>Update:<br />
This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.</p>
| 16 | 2008-10-07T05:08:36Z | 20,461,473 | <p>GTK may be a better option, as it is cross-platform. It'll work great on Ubuntu, and should work just fine on Windows when GTK and Python bindings are installed.</p>
<pre><code>from gi.repository import Gtk
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, "This is an INFO MessageDialog")
dialog.format_secondary_text(
"And this is the secondary text that explains things.")
dialog.run()
print "INFO dialog closed"
</code></pre>
<p>You can see other examples <a href="http://python-gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html" rel="nofollow">here</a>. (<a href="https://media.readthedocs.org/pdf/python-gtk-3-tutorial/latest/python-gtk-3-tutorial.pdf" rel="nofollow">pdf</a>)</p>
<p>The arguments passed should be the gtk.window parent (or None), DestroyWithParent, Message type, Message-buttons, title.</p>
| 2 | 2013-12-09T01:14:00Z | [
"python",
"alerts"
] |
Testing socket connection in Python | 177,389 | <p>This question will expand on: <a href="http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python">http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python</a><br />
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.
<br /><br />
Edit:
I tried this:</p>
<pre><code>try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
</code></pre>
<p>but the alert function is called even when that connection should have worked.</p>
| 17 | 2008-10-07T06:30:19Z | 177,411 | <p>It seems that you catch not the exception you wanna catch out there :)</p>
<p>if the <code>s</code> is a <code>socket.socket()</code> object, then the right way to call <code>.connect</code> would be:</p>
<pre><code>import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
</code></pre>
<p>Always try to see what kind of exception is what you're catching in a try-except loop. </p>
<p>You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate <code>except</code> statement for each one of them - this way you'll be able to react differently for different kind of problems.</p>
| 23 | 2008-10-07T06:46:53Z | [
"python",
"sockets"
] |
Testing socket connection in Python | 177,389 | <p>This question will expand on: <a href="http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python">http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python</a><br />
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.
<br /><br />
Edit:
I tried this:</p>
<pre><code>try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
</code></pre>
<p>but the alert function is called even when that connection should have worked.</p>
| 17 | 2008-10-07T06:30:19Z | 177,652 | <p>You should really post:</p>
<ol>
<li>The complete source code of your example</li>
<li>The <strong>actual</strong> result of it, not a summary</li>
</ol>
<p>Here is my code, which works:</p>
<pre><code>import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
</code></pre>
<p>When the server listens, I get nothing (this is normal), when it
doesn't, I get the expected message:</p>
<pre><code>Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
</code></pre>
| 4 | 2008-10-07T08:48:00Z | [
"python",
"sockets"
] |
Testing socket connection in Python | 177,389 | <p>This question will expand on: <a href="http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python">http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python</a><br />
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.
<br /><br />
Edit:
I tried this:</p>
<pre><code>try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
</code></pre>
<p>but the alert function is called even when that connection should have worked.</p>
| 17 | 2008-10-07T06:30:19Z | 20,541,919 | <p>You can use the function <a href="http://docs.python.org/2/library/socket.html#socket.socket.connect_ex" rel="nofollow">connect_ex</a>. It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as <a href="http://linux.die.net/man/3/errno" rel="nofollow">errno</a> in C):</p>
<pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.close()
if result:
print "problem with socket!"
else:
print "everything it's ok!"
</code></pre>
| 7 | 2013-12-12T11:12:04Z | [
"python",
"sockets"
] |
Keeping filters in Django Admin | 177,492 | <p>What I would like to achive is: </p>
<ul>
<li>I go to admin site, apply some filters to the list of objects</li>
<li>I click and object edit, edit, edit, hit 'Save'</li>
<li>Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied.</li>
</ul>
<p>Is there an easy way to do it?</p>
| 5 | 2008-10-07T07:33:58Z | 177,563 | <p>Click 2 times "Back"?</p>
| 1 | 2008-10-07T08:15:56Z | [
"python",
"django",
"django-admin"
] |
Keeping filters in Django Admin | 177,492 | <p>What I would like to achive is: </p>
<ul>
<li>I go to admin site, apply some filters to the list of objects</li>
<li>I click and object edit, edit, edit, hit 'Save'</li>
<li>Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied.</li>
</ul>
<p>Is there an easy way to do it?</p>
| 5 | 2008-10-07T07:33:58Z | 180,855 | <p>Unfortunately there's no easy way to do this. The filtering does not seem to be saved in any session variable.</p>
<p>Clicking back twice is the normal method, but it can be unweildy and annoying if you've just changed an object so that it should no longer be shown using your filter.</p>
<p>If it's just a one-off, click back twice or go through the filtering again, it's the easiest way.</p>
<p>If you're going to be filtering more often, or you just want to learn about hacking the admin (which is pretty open and easy), you'll want to write a <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/filterspecs.py" rel="nofollow">FilterSpec</a>.</p>
<p>Have a look <a href="http://www.djangosnippets.org/snippets/1051/" rel="nofollow">here</a> and <a href="http://www.djangosnippets.org/snippets/587/" rel="nofollow">here</a> for examples of people writing their own.</p>
<p>A really, really terrible way to do this would be to edit the admin interface so that after you click "Save", you are redirected to you filtered URL. I wouldn't recommend this at all, but it's an option.</p>
<p>Another fairly simple way to do this would be to write a generic view to show your filtered objects, then use Django forms to edit the items from there. I'd have a look at this, you'll be stunned just how little code you have to write to get a simple view/edit page going.</p>
| 2 | 2008-10-07T23:41:28Z | [
"python",
"django",
"django-admin"
] |
Keeping filters in Django Admin | 177,492 | <p>What I would like to achive is: </p>
<ul>
<li>I go to admin site, apply some filters to the list of objects</li>
<li>I click and object edit, edit, edit, hit 'Save'</li>
<li>Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied.</li>
</ul>
<p>Is there an easy way to do it?</p>
| 5 | 2008-10-07T07:33:58Z | 2,645,126 | <p>There's a simple hack to do this, but it's not a general solution and requires modifying every <code>ModelAdmin</code> which you want to support this. Maybe there is a general way to do this, but I've not spent the time to solve it on a general level.</p>
<p>The first step is to write a custom <code>FilterSpec</code> for the filter (see Harley's post for links that will help) which saves the chosen filter value in the session (and deletes it when no longer wanted).</p>
<pre><code># in cust_admin/filterspecs.py
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec
class MyFilterSpec(ChoicesFilterSpec):
def __init__(self, f, request, params, model, model_admin):
super(MyFilterSpec, self).__init__(f, request, params, model,
model_admin)
if self.lookup_val is not None:
request.session[self.lookup_kwarg] = self.lookup_val
elif self.lookup_kwarg in request.session:
del(request.session[self.lookup_kwarg])
# Register the filter with a test function which will apply it to any field
# with a my_filter attribute equal to True
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'my_filter', False),
MyFilterSpec))
</code></pre>
<p>You must import the module this is in somewhere, for example your <code>urls.py</code>:</p>
<pre><code># in urls.py
from cust_admin import filterspecs
</code></pre>
<p>Set a property on the field you want to apply the filter to:</p>
<pre><code># in models.py
class MyModel(models.Model):
my_field = Models.IntegerField(choices=MY_CHOICES)
my_field.my_filter = True
</code></pre>
<p>In a custom <code>ModelAdmin</code> class, override the <code>change_view</code> method, so that after the user clicks <strong>save</strong>, they are returned to the list view with their filter field value added to the URL.</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
def change_view(self, request, object_id, extra_context=None):
result = super(MyModelAdmin, self).change_view(request, object_id,
extra_context)
if '_save' in request.POST:
if 'my_field__exact' in request.session:
result['Location'] = '/admin/myapp/mymodel/?my_field__exact=%s' \
% request.session['my_field__exact']
return result
</code></pre>
| 1 | 2010-04-15T12:25:45Z | [
"python",
"django",
"django-admin"
] |
Keeping filters in Django Admin | 177,492 | <p>What I would like to achive is: </p>
<ul>
<li>I go to admin site, apply some filters to the list of objects</li>
<li>I click and object edit, edit, edit, hit 'Save'</li>
<li>Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied.</li>
</ul>
<p>Is there an easy way to do it?</p>
| 5 | 2008-10-07T07:33:58Z | 2,967,841 | <p>Another way to do this is to embed the filter in the queryset.</p>
<p>You can dynamically create a proxy model with a manager that filters the way you want, then call admin.site.register() to create a new model admin. All the links would then be relative to this view.</p>
| 0 | 2010-06-03T16:20:20Z | [
"python",
"django",
"django-admin"
] |
Keeping filters in Django Admin | 177,492 | <p>What I would like to achive is: </p>
<ul>
<li>I go to admin site, apply some filters to the list of objects</li>
<li>I click and object edit, edit, edit, hit 'Save'</li>
<li>Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied.</li>
</ul>
<p>Is there an easy way to do it?</p>
| 5 | 2008-10-07T07:33:58Z | 9,112,369 | <p>In my opinion its better to override methods from ModelAdmin <code>changelist_view</code> and <code>change_view</code>:</p>
<p>Like so:</p>
<pre><code>class FakturaAdmin(admin.ModelAdmin):
[...]
def changelist_view(self, request, extra_context=None):
result = super(FakturaAdmin, self).changelist_view(request, extra_context=None)
request.session['qdict'] = request.GET
return result
def change_view(self, request, object_id, extra_context=None):
result = super(FakturaAdmin, self).change_view(request, object_id, extra_context)
try:
result['location'] = result['location']+"?"+request.session['qdict'].urlencode()
except:
pass
return result
</code></pre>
<p>As you wish, after save object you go back to list of objects with active filters.</p>
| 0 | 2012-02-02T12:32:47Z | [
"python",
"django",
"django-admin"
] |
Keeping filters in Django Admin | 177,492 | <p>What I would like to achive is: </p>
<ul>
<li>I go to admin site, apply some filters to the list of objects</li>
<li>I click and object edit, edit, edit, hit 'Save'</li>
<li>Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied.</li>
</ul>
<p>Is there an easy way to do it?</p>
| 5 | 2008-10-07T07:33:58Z | 9,489,312 | <p>There is a change request at the Django project asking for exactly this functionality.</p>
<p>All it's waiting for to be checked in is some tests and documentation. You could write those, and help the whole project, or you could just take the proposed patch (near the bottom of the page) and try it out.</p>
<p><a href="https://code.djangoproject.com/ticket/6903" rel="nofollow">https://code.djangoproject.com/ticket/6903</a></p>
| 0 | 2012-02-28T20:36:46Z | [
"python",
"django",
"django-admin"
] |
Keeping filters in Django Admin | 177,492 | <p>What I would like to achive is: </p>
<ul>
<li>I go to admin site, apply some filters to the list of objects</li>
<li>I click and object edit, edit, edit, hit 'Save'</li>
<li>Site takes me to the list of objects... unfiltered. I'd like to have the filter from step 1 remembered and applied.</li>
</ul>
<p>Is there an easy way to do it?</p>
| 5 | 2008-10-07T07:33:58Z | 23,236,174 | <p>This feature has been added to Django as part of the 1.6 release and is enabled now by default. It is described in the <a href="https://docs.djangoproject.com/en/1.6/releases/1.6/#minor-features" rel="nofollow">release notes</a>:</p>
<blockquote>
<p>ModelAdmin now preserves filters on the list view after creating,
editing or deleting an object. Itâs possible to restore the previous
behavior of clearing filters by setting the preserve_filters attribute
to False.</p>
</blockquote>
| 0 | 2014-04-23T06:12:00Z | [
"python",
"django",
"django-admin"
] |
Accessing python egg's own metadata | 177,910 | <p>I've produced a python egg using setuptools and would like to access it's metadata at runtime. I currently got working this:</p>
<pre><code>import pkg_resources
dist = pkg_resources.get_distribution("my_project")
print(dist.version)
</code></pre>
<p>but this would probably work incorrectly if I had multiple versions of the same egg installed. And if I have both installed egg and development version, then running this code from development version would pick up version of the installed egg. </p>
<p>So, how do I get metadata for <em>my</em> egg not some random matching egg installed on my system? </p>
| 4 | 2008-10-07T10:43:22Z | 177,939 | <p>I am somewhat new to Python as well, but from what I understand: </p>
<p>Although you can install multiple versions of the "same" egg (having the same name), only one of them will be available to any particular piece of code at runtime (based on your discovery method). So if your egg is the one calling this code, it must have already been selected as <em>the</em> version of <code>my_project</code> for this code, and your access will be to your own version.</p>
| 3 | 2008-10-07T10:56:40Z | [
"python",
"setuptools",
"pkg-resources"
] |
Accessing python egg's own metadata | 177,910 | <p>I've produced a python egg using setuptools and would like to access it's metadata at runtime. I currently got working this:</p>
<pre><code>import pkg_resources
dist = pkg_resources.get_distribution("my_project")
print(dist.version)
</code></pre>
<p>but this would probably work incorrectly if I had multiple versions of the same egg installed. And if I have both installed egg and development version, then running this code from development version would pick up version of the installed egg. </p>
<p>So, how do I get metadata for <em>my</em> egg not some random matching egg installed on my system? </p>
| 4 | 2008-10-07T10:43:22Z | 177,966 | <p>Exactly. So you should only be able to get the information for the currently available egg (singular) of a library. If you have multiple eggs of the same library in your site-packages folder, check the easy-install.pth in the same folder to see which egg is really used :-)</p>
<p>On a site note: This is exactly the point of systems like zc.buildout which lets you define the exact version of a library that will be made available to you for example while developing an application or serving a web application. So you can for example use version 1.0 for one project and 1.2 for another. </p>
| 0 | 2008-10-07T11:06:09Z | [
"python",
"setuptools",
"pkg-resources"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 178,211 | <p>Yes,</p>
<pre><code>a = {"id": 1, "name":"Sesame Street"}
</code></pre>
| 6 | 2008-10-07T12:29:21Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 178,213 | <p>This sounds like the PHP array using named indices is very similar to a python dict:</p>
<pre><code>shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
</code></pre>
<p>See <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries">http://docs.python.org/tutorial/datastructures.html#dictionaries</a> for more on this.</p>
| 36 | 2008-10-07T12:29:57Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 178,224 | <p>PHP arrays are actually maps, which is equivalent to dicts in Python.</p>
<p>Thus, this is the Python equivalent:</p>
<p><code>showlist = [{'id':1, 'name':'Sesaeme Street'}, {'id':2, 'name':'Dora the Explorer'}]</code></p>
<p>Sorting example:</p>
<pre><code>from operator import attrgetter
showlist.sort(key=attrgetter('id'))
</code></pre>
<p>BUT! With the example you provided, a simpler datastructure would be better:</p>
<pre><code>shows = {1: 'Sesaeme Street', 2:'Dora the Explorer'}
</code></pre>
| 19 | 2008-10-07T12:33:18Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 178,227 | <p>You should read the <a href="http://docs.python.org/tutorial/" rel="nofollow">python tutorial</a> and esp. the section about <a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">datastructures</a> which also covers <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionaries.</a></p>
| 2 | 2008-10-07T12:34:06Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 178,239 | <p>To assist future Googling, these are usually called associative arrays in PHP, and dictionaries in Python.</p>
| 5 | 2008-10-07T12:37:05Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 178,370 | <p>Not exactly the same syntax, but there are a number of dictionary extensions out there which respect the order in which the key/value pairs have been added. E.g. <a href="http://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/Seqdict.html" rel="nofollow">seqdict</a>.</p>
| 1 | 2008-10-07T13:13:47Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 178,668 | <p>@Unkwntech,</p>
<p>What you want is available in the just-released Python 2.6 in the form of <a href="http://docs.python.org/whatsnew/2.6.html#new-improved-and-deprecated-modules">named tuples</a>. They allow you to do this:</p>
<pre><code>import collections
person = collections.namedtuple('Person', 'id name age')
me = person(id=1, age=1e15, name='Dan')
you = person(2, 'Somebody', 31.4159)
assert me.age == me[2] # can access fields by either name or position
</code></pre>
| 11 | 2008-10-07T14:21:43Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 179,169 | <p>Python has lists and dicts as 2 separate data structures. PHP mixes both into one. You should use dicts in this case. </p>
| 0 | 2008-10-07T15:55:45Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 199,271 | <p>I did it like this:</p>
<pre><code>def MyStruct(item1=0, item2=0, item3=0):
"""Return a new Position tuple."""
class MyStruct(tuple):
@property
def item1(self):
return self[0]
@property
def item2(self):
return self[1]
@property
def item3(self):
return self[2]
try:
# case where first argument a 3-tuple
return MyStruct(item1)
except:
return MyStruct((item1, item2, item3))
</code></pre>
<p>I did it also a bit more complicate with list instead of tuple, but I had override the setter as well as the getter.</p>
<p>Anyways this allows:</p>
<pre><code> a = MyStruct(1,2,3)
print a[0]==a.item1
</code></pre>
| -3 | 2008-10-13T22:32:51Z | [
"python",
"arrays"
] |
Python: can I have a list with named indices? | 178,199 | <p>In PHP I can name my array indicies so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
| 13 | 2008-10-07T12:25:25Z | 39,307,547 | <p>The <code>pandas</code> library has a really neat solution: <code>Series</code>. </p>
<pre><code>book = pandas.Series( ['Introduction to python', 'Someone', 359, 10],
index=['Title', 'Author', 'Number of pages', 'Price'])
print book['Author']
</code></pre>
<p>For more information check it's documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html</a>.</p>
| 0 | 2016-09-03T13:39:23Z | [
"python",
"arrays"
] |
Paver 0.8.1 compatibility with python 2.6 | 178,300 | <p>Does anyone manage to bootstrap its development area using paver with python 2.6 ?</p>
<p>I have install python 2.6, install paver with easy_install-2.6, everything looks fine.
But when I try to launch the bootstrap method it raises an urllib2.HTTPError (: HTTP Error 404: Not Found) while trying to download <a href="http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c8-py2.6.egg" rel="nofollow">http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c8-py2.6.egg</a>.
I have tryed to add the correct setuptools EGG file (which is 0.6c9) in the support-files directory, bootstrap.py find the EGG file, but doesn't seem to use it because it still try to download the 0.6c8 version which is no more available.</p>
<p>Any ideas how to solve this issue ?</p>
<p>Thanks in advance </p>
<p>Bertrand</p>
| 0 | 2008-10-07T12:56:40Z | 2,703,878 | <p>You should try newer version. =) <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">http://www.blueskyonmars.com/projects/paver/</a></p>
| 2 | 2010-04-24T09:15:11Z | [
"python",
"bootstrapper",
"build-environment"
] |
Python, unit-testing and mocking imports | 178,458 | <p>I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests?</p>
<p>As an example: The file with the functions I want to test, imports ten other files which is part of our software and not python core libs.</p>
<p>I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.</p>
<p>Thanks for all the answers. </p>
<p>I didn't really know what I wanted to do from the start but now I think I know. </p>
<p>Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path</p>
<p>Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.</p>
| 10 | 2008-10-07T13:34:42Z | 178,582 | <p>"imports a lot of other files"? Imports a lot of other files that are part of your customized code base? Or imports a lot of other files that are part of the Python distribution? Or imports a lot of other open source project files?</p>
<p>If your imports don't work, you have a "simple" <code>PYTHONPAT</code>H problem. Get all of your various project directories onto a <code>PYTHONPATH</code> that you can use for testing. We have a rather complex path, in Windows we manage it like this</p>
<pre><code>@set Part1=c:\blah\blah\blah
@set Part2=c:\some\other\path
@set that=g:\shared\stuff
set PYTHONPATH=%part1%;%part2%;%that%
</code></pre>
<p>We keep each piece of the path separate so that we (a) know where things come from and (b) can manage change when we move things around.</p>
<p>Since the <code>PYTHONPATH</code> is searched in order, we can control what gets used by adjusting the order on the path.</p>
<p>Once you have "everything", it becomes a question of trust.</p>
<p>Either </p>
<ul>
<li>you trust something (i.e., the Python code base) and just import it.</li>
</ul>
<p>Or </p>
<ul>
<li><p>You don't trust something (i.e., your own code) and you </p>
<ol>
<li>test it separately and </li>
<li>mock it for stand-alone testing.</li>
</ol></li>
</ul>
<p>Would you test the Python libraries? If so, you've got a lot of work. If not, then, you should perhaps only mock out the things you're actually going to test.</p>
| 1 | 2008-10-07T13:59:18Z | [
"python",
"unit-testing",
"refactoring",
"python-import"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.