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
list
Pair 2 elements in a list and make a conditional statement to see if the pairs are equal to each other
39,811,423
<p>So I have this homework assignment and seem to be stuck on this question.</p> <p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains three pairs of integers, and False otherwise.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt;threePairs([5, 6, 3, 2, 1, 4]) False &gt;&gt;&gt;threePairs([1, 1, 2, 2, 2, 2]) True </code></pre> <p>I've tried using indexes and I don't really know how to slice so I'm stuck in figuring out how I make those pairs equal to each other in the condition so it is True.</p> <p>This is what I had previous to deleting it and trying again.</p> <pre><code>def threePairs(aList): if [0] == [1] and [2] == [3] and [4] == [5]: return True else: return False </code></pre>
0
2016-10-01T20:59:26Z
39,811,474
<p>You don't need to slice, you need index access (as a side note, you should ask your teacher if they've ever heard of <code>pep8</code>, <code>three_pairs(mylist)</code> would be far better):</p> <pre><code>def threePairs(aList): if aList[0] == aList[1] and aList[2] == aList[3] and aList[4] == aList[5]: return True else: return False </code></pre> <p>But if you're ever returning <code>True</code> and <code>False</code> like this, you can just return the result of the comparison:</p> <pre><code>def threePairs(aList): return aList[0] == aList[1] and aList[2] == aList[3] and aList[4] == aList[5] </code></pre> <p>Though as other answers allude - your examples are not well defined. What if you have:</p> <pre><code>&gt;&gt;&gt; threePairs([1, 2, 3, 1, 2, 3]) </code></pre> <p>Should that return <code>True</code>, or <code>False</code>?</p>
1
2016-10-01T21:05:24Z
[ "python", "list", "python-3.x", "pair" ]
Pair 2 elements in a list and make a conditional statement to see if the pairs are equal to each other
39,811,423
<p>So I have this homework assignment and seem to be stuck on this question.</p> <p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains three pairs of integers, and False otherwise.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt;threePairs([5, 6, 3, 2, 1, 4]) False &gt;&gt;&gt;threePairs([1, 1, 2, 2, 2, 2]) True </code></pre> <p>I've tried using indexes and I don't really know how to slice so I'm stuck in figuring out how I make those pairs equal to each other in the condition so it is True.</p> <p>This is what I had previous to deleting it and trying again.</p> <pre><code>def threePairs(aList): if [0] == [1] and [2] == [3] and [4] == [5]: return True else: return False </code></pre>
0
2016-10-01T20:59:26Z
39,812,530
<pre><code>def threepairs(aList): counter = 0 for element in aList: if counter &gt;= 3: return True if element % 2 == 0: counter += 1 return False </code></pre>
-1
2016-10-01T23:41:56Z
[ "python", "list", "python-3.x", "pair" ]
How to multiply user input by a decimal number in python?
39,811,520
<p>Hello I am having trouble with using strings and integers during multiplication. If there is something I do not think I have done anything fundamentally wrong but then again, it's not working so I probably have done! </p> <p>This is my code as of now.</p> <pre><code> #This is where I ask the user for input for a value UI = print (float(input("Enter your value here: "))) #Here I have numbers that I need to multiply the input by FRT = (float(0.290949) SRM = (float(0.281913) #Here is the multiplication but this is where the issue occurrs QV = (float("FRT"*"UI")) SV = (float("SRM"*"UI")) </code></pre> <p>Both of these lines at the end have issues, I have tried using different set ups with using the numbers instead of defining them as FRT and SRM and using integer before float etc, but with these lines they both give the error "could not convert string to float "FRT""</p>
-1
2016-10-01T21:13:19Z
39,811,585
<p>There are quite a few issues with your code</p> <p>First of all, you have not closed your parenthesis on lines 4 and 5</p> <p>Secondly, you're trying to call variables by strings. That isn't how it works</p> <pre><code>QV = (float("FRT"*"UI")) </code></pre> <p>should be</p> <pre><code>QV = (float(FRI * UI)) </code></pre> <p>Lastly, <code>input</code> already displays text, so you don't need to <code>print</code> anything, and since <code>print</code> returns <code>None</code>, UI will always be <code>None</code>. </p> <pre><code>UI = print (float(input("Enter your value here: "))) </code></pre> <p>should be</p> <pre><code>UI = float(input("Enter your value here: ")) </code></pre> <p>So, the complete debugged code should be:</p> <pre><code>#This is where I ask the user for input for a value UI = float(input("Enter your value here: ")) #Here I have numbers that I need to multiply the input by FRT = (float(0.290949)) SRM = (float(0.281913)) #Here is the multiplication but this is where the issue occurrs QV = (float(FRT*UI)) SV = (float(SRM*UI)) </code></pre>
0
2016-10-01T21:22:09Z
[ "python", "math", "input", "floating-point", "integer" ]
How to multiply user input by a decimal number in python?
39,811,520
<p>Hello I am having trouble with using strings and integers during multiplication. If there is something I do not think I have done anything fundamentally wrong but then again, it's not working so I probably have done! </p> <p>This is my code as of now.</p> <pre><code> #This is where I ask the user for input for a value UI = print (float(input("Enter your value here: "))) #Here I have numbers that I need to multiply the input by FRT = (float(0.290949) SRM = (float(0.281913) #Here is the multiplication but this is where the issue occurrs QV = (float("FRT"*"UI")) SV = (float("SRM"*"UI")) </code></pre> <p>Both of these lines at the end have issues, I have tried using different set ups with using the numbers instead of defining them as FRT and SRM and using integer before float etc, but with these lines they both give the error "could not convert string to float "FRT""</p>
-1
2016-10-01T21:13:19Z
39,811,589
<p>"FRT" is a string, made of the letters F, R &amp; T. If you want to refer to the variable FRT, do not use quotation marks. <code>QV = (float("FRT"*"UI"))</code> is trying to first multiply the string "FRT" by the string "UI", and then convert the result to a float. Since string multiplication is not defined, you get an error.</p> <p>In your current code, I am unsure of what UI is, since you did not make it equal to a number but to the result of a <code>print()</code>. Your first line should be replaced by</p> <pre><code>UI = float(input("Enter your value here: ")) print(UI) </code></pre> <p>Then, <code>QV = FRT * UI</code> will do what you want, since both FRT and UI are floats. The parentheses around each operation are not needed.</p>
0
2016-10-01T21:22:32Z
[ "python", "math", "input", "floating-point", "integer" ]
How to multiply user input by a decimal number in python?
39,811,520
<p>Hello I am having trouble with using strings and integers during multiplication. If there is something I do not think I have done anything fundamentally wrong but then again, it's not working so I probably have done! </p> <p>This is my code as of now.</p> <pre><code> #This is where I ask the user for input for a value UI = print (float(input("Enter your value here: "))) #Here I have numbers that I need to multiply the input by FRT = (float(0.290949) SRM = (float(0.281913) #Here is the multiplication but this is where the issue occurrs QV = (float("FRT"*"UI")) SV = (float("SRM"*"UI")) </code></pre> <p>Both of these lines at the end have issues, I have tried using different set ups with using the numbers instead of defining them as FRT and SRM and using integer before float etc, but with these lines they both give the error "could not convert string to float "FRT""</p>
-1
2016-10-01T21:13:19Z
39,811,601
<pre><code> #This is where I ask the user for input for a value UI = print (float(input("Enter your value here: "))) </code></pre> <p>Above won't do what you want, print doesn't return anything</p> <pre><code>UI = float(input("...")) print(UI) </code></pre> <p>If using python 2.7 us raw_input, not input</p> <pre><code>#Here I have numbers that I need to multiply the input by FRT = (float(0.290949) SRM = (float(0.281913) </code></pre> <p>You just need:</p> <pre><code>FRT = 0.290949 </code></pre> <p>No need to convert a float into a float</p> <pre><code>#Here is the multiplication but this is where the issue occurrs QV = (float("FRT"*"UI")) SV = (float("SRM"*"UI")) </code></pre> <p>You are multiplying strings above, do this:</p> <pre><code>QV = FRT * UI </code></pre>
0
2016-10-01T21:24:28Z
[ "python", "math", "input", "floating-point", "integer" ]
Python OrderedDict __setitem__ overloading
39,811,562
<p>I'm building a class that inherits OrderedDict, in which every key returns a list. I'm looking to overload <strong>setitem</strong> such that if the key doesn't exist, new assignments immediately put the value into a list, otherwise the new value is appended to the list. The following seems to be working:</p> <pre><code>from collections import OrderedDict class ListDict(OrderedDict): def __init__(self): super(ListDict, self).__init__() def __setitem__(self, key, value): if key in self.keys(): self[key].append(value) else: super(ListDict, self).__setitem__(key, [value]) thedict = ListDict() thedict['a'] = 'first item' thedict['b'] = 'another first item' thedict['a'] = 'a second item?' print thedict </code></pre> <p>which prints:</p> <pre><code>$ python inheritex.py ListDict([('a', ['first item', 'a second item?']), ('b', ['another first item'])]) </code></pre> <p>Instead of appending with an assignment operator '=', I would rather have new items be appended with '+=', or even something like:</p> <pre><code>ListDict['key'] = ListDict['key'] + 'value' </code></pre> <p>How would one go about overloading this? Besides being possible to monkey patch an add function, is it even a Pythonic/readable means to alter class behavior, or is this acceptable because the inherited function (OrderedDict) is untouched?</p>
0
2016-10-01T21:18:42Z
39,811,695
<p>You can already use <code>+=</code> on <em>existing</em> keys:</p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; thedict = OrderedDict() &gt;&gt;&gt; thedict['a'] = [] # set initial list &gt;&gt;&gt; thedict['a'] += ['foo'] &gt;&gt;&gt; thedict['a'] += ['bar'] &gt;&gt;&gt; thedict OrderedDict([('a', ['foo', 'bar'])]) </code></pre> <p>Note that <code>+=</code> on a list is basically the same thing as <code>list.extend()</code>, so you need to append lists.</p> <p>If you want this to work for keys that don't exist yet, implement a <a href="https://docs.python.org/3/reference/datamodel.html#object.__missing__" rel="nofollow"><code>__missing__</code> method</a>, rather than <code>__setitem__</code>:</p> <pre><code>class ListDict(OrderedDict): def __missing__(self, key): self[key] = [] return self[key] </code></pre> <p>When a key is missing during <code>dict[key]</code> lookup, <code>__missing__</code> is called and it's return value is returned instead of raising a <code>KeyError</code>.</p> <p>Now both <code>+</code> and <code>+=</code> work on missing keys too:</p> <pre><code>&gt;&gt;&gt; thedict = ListDict() &gt;&gt;&gt; thedict['a'] += ['foo', 'bar'] &gt;&gt;&gt; thedict['b'] = thedict['b'] + ['spam', 'ham'] &gt;&gt;&gt; thedict ListDict([('a', ['foo', 'bar']), ('b', ['spam', 'ham'])]) </code></pre> <p>If you concatenation must work without adding lists, you could produce a custom list subclass too:</p> <pre><code>class ConcatList(list): def __add__(self, value): return type(self)(super(ContactList, self).__add__([value])) def __iadd__(self, value): self.append(value) return self </code></pre> <p>then use that type in <code>__missing__</code> (and convert any new lists set directly in <code>__setitem__</code>):</p> <pre><code>class ListDict(OrderedDict): def __missing__(self, key): self[key] = ConcatList() return self[key] def __setitem__(self, key, value): if not isinstance(key, ConcatList): value = ConcatList([value]) super(ListDict, self).__setitem__(key, value) </code></pre> <p>after which you can forgo brackets:</p> <pre><code>&gt;&gt;&gt; thedict = ListDict() &gt;&gt;&gt; thedict['a'] += 'foo' &gt;&gt;&gt; thedict['b'] = thedict['b'] + 'bar' &gt;&gt;&gt; thedict ListDict([('a', ['foo']), ('b', ['bar'])]) </code></pre>
2
2016-10-01T21:38:11Z
[ "python", "dictionary", "overloading", "ordereddictionary" ]
Python OrderedDict __setitem__ overloading
39,811,562
<p>I'm building a class that inherits OrderedDict, in which every key returns a list. I'm looking to overload <strong>setitem</strong> such that if the key doesn't exist, new assignments immediately put the value into a list, otherwise the new value is appended to the list. The following seems to be working:</p> <pre><code>from collections import OrderedDict class ListDict(OrderedDict): def __init__(self): super(ListDict, self).__init__() def __setitem__(self, key, value): if key in self.keys(): self[key].append(value) else: super(ListDict, self).__setitem__(key, [value]) thedict = ListDict() thedict['a'] = 'first item' thedict['b'] = 'another first item' thedict['a'] = 'a second item?' print thedict </code></pre> <p>which prints:</p> <pre><code>$ python inheritex.py ListDict([('a', ['first item', 'a second item?']), ('b', ['another first item'])]) </code></pre> <p>Instead of appending with an assignment operator '=', I would rather have new items be appended with '+=', or even something like:</p> <pre><code>ListDict['key'] = ListDict['key'] + 'value' </code></pre> <p>How would one go about overloading this? Besides being possible to monkey patch an add function, is it even a Pythonic/readable means to alter class behavior, or is this acceptable because the inherited function (OrderedDict) is untouched?</p>
0
2016-10-01T21:18:42Z
39,812,033
<p>I've extended <a href="http://stackoverflow.com/users/100297/martijn-pieters">Martijn's</a> <code>ListDict</code> so you can provide <code>default_factory</code> and have a similar to <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a>'s functionality + key ordering:</p> <pre><code>class OrderedDefaultDict(OrderedDict): def __init__(self, default_factory=None): self.default_factory = default_factory def __missing__(self, key): if self.default_factory is None: raise KeyError self[key] = self.default_factory() return self[key] list_dict = OrderedDefaultDict(list) list_dict['first'].append(1) list_dict['second'].append(2) list_dict['third'].append(3) assert list(list_dict.keys()) == ['first', 'second', 'third'] assert list(list_dict.values()) == [[1], [2], [3]] list_dict.move_to_end('first') assert list(list_dict.keys()) == ['second', 'third', 'first'] </code></pre>
0
2016-10-01T22:26:50Z
[ "python", "dictionary", "overloading", "ordereddictionary" ]
python-flask html form help/suggestions
39,811,569
<p>I'm rendering a page for users to browse ad listings on a practice site. On the 'browse' page, I have three separate forms, two are select fields and the other is a textfield. The select fields allow a user to change location or transaction type, and the text field allows them to change the thing they are searching for. I wanted to do this pure HTML and not use flask-wtf. I have successfully got the part where they can change location working, but as soon as I add code for the other options, it breaks and I get a <strong>400 bad request error</strong>. Any suggestions or guidance as to why this is isn't working when I add in the forms for changing item and transaction type?</p> <pre><code> @app.route('/find-it/', methods=['GET','POST']) def browse(): try: location = session.get('location', None) transType = session.get('transType', None) item = session.get('item', None) data = browseQuery() if request.method == 'POST': if request.form['changeLocation'] != '': print('location changed') location = request.form['changeLocation'] session['location'] = location return redirect(url_for('browse', location=location)) elif request.form['changeType'] != '': print('type changed') transType = request.form['changetype'] session['transType'] = transType return redirect('browse', transType=transType) else: if request.form['changeItem'] != '': print('item changed') item = request.form['changeItem'] session['item'] = item return redirect(url_for('browse', item=item)) return render_template('all-classifieds.html',location=location,transType=transType, data=data) except Exception as e: return (str(e)) </code></pre> <p>HTML:</p> <pre><code>&lt;form method="post" id="changeLocation" name="changeLocation" action=""&gt; &lt;select name="changeLocation" id="changeLocation" style="margin-right: 5%; float: left;"&gt; &lt;optgroup label="Where?"&gt; &lt;option selected style="display:none;color:#eee;"&gt;&lt;/option&gt; &lt;option&gt;option 1&lt;/option&gt; &lt;option&gt;option 2&lt;/option&gt; &lt;/optgroup&gt;&lt;/select&gt;&lt;/form&gt; &lt;button type="submit" id="submit" form="changeLocation" style="padding: 0 3px; float:left;" class="btn btn-info btn-sm"&gt; &lt;i class="glyphicon glyphicon-search"&gt;&lt;/i&gt; &lt;/button&gt; &lt;form method="post" name="changeType" id="changeType"&gt; &lt;select name="changeType" id="changeType" style="margin-right: 5%; float: left;"&gt; &lt;optgroup label="..."&gt; &lt;option selected style="display:none;color:#eee;"&gt;&lt;/option&gt; &lt;option&gt;option 1&lt;/option&gt; &lt;option&gt;option 2&lt;/option&gt; &lt;option&gt;option 3&lt;/option&gt; &lt;/optgroup&gt; &lt;/select&gt; &lt;form method="post" name="changeType" id="changeType"&gt; &lt;select name="changeType" id="changeType" style="margin-right: 5%; float: left;"&gt; &lt;optgroup label="Look for things that are..."&gt; &lt;option selected style="display:none;color:#eee;"&gt;&lt;/option&gt; &lt;option&gt;asdf&lt;/option&gt; &lt;option&gt;asdfasdf&lt;/option&gt; &lt;option&gt;asdfasdfasdf&lt;/option&gt; &lt;/optgroup&gt; &lt;/select&gt;&lt;/form&gt; &lt;button type="submit" id="submit" form="changeType" style="padding: 0 3px; float:left;" class="btn btn-info btn-sm"&gt; &lt;i class="glyphicon glyphicon-search"&gt;&lt;/i&gt; &lt;/button&gt; &lt;form method="post" name="changeItem" id="changeItem"&gt; &lt;input type="text" name="changeItem" value="" id="changeItem" placeholder=""/&gt; &lt;/form&gt; &lt;button type="submit" id="submit" form="changeItem" style="padding: 0 3px; float:left;" class="btn btn-info btn-sm"&gt; &lt;i class="glyphicon glyphicon-search"&gt;&lt;/i&gt; &lt;/button&gt; </code></pre>
0
2016-10-01T21:20:22Z
39,812,016
<p><strong>The problem you asked about:</strong></p> <p>With</p> <pre><code>if request.form['changeLocation'] != '': </code></pre> <p>you are probably trying to find out if that specific form was used. The problem is: when the correct form was used this check works but if a different form was used the <code>request.form</code> dictionary throws a key error. But it is not a normal <code>KeyError</code>. Flask will translate that "special" error to a <code>400 Bad Request</code>.</p> <p>To check if a certain key is present in the form data use the <code>in</code> operator</p> <pre><code>if "changeLocation" in request.form: # you can use request.form["changeLocation"] here elif "changeType" in request.form: # here request.form["changeType"] is present ... </code></pre> <p><strong>Another problem:</strong></p> <p>This line</p> <pre><code>render_template('all-classifieds.html',location=location,transType=transType, data=data) </code></pre> <p>won't work, because <code>location</code> and <code>transType</code> are defined in the <code>if</code> blocks. It will fail if the blocks are not executed.</p> <p><strong>Something different:</strong></p> <pre><code>else: if condition: do_something </code></pre> <p>can be rewritten as</p> <pre><code>elif condition: do_something </code></pre>
1
2016-10-01T22:24:48Z
[ "python", "html", "forms", "flask", "http-status-code-400" ]
Python list to string spacing
39,811,720
<p>I have a list such as this</p> <pre><code>list = ['Hi', ',', 'my', 'name', 'is', 'Bob', '!'] </code></pre> <p>I wanted to convert this to a string, and originally, I found on stackoverflow that .join() could be used. So i did:</p> <pre><code>x = ' '.join(list) print(x) </code></pre> <p>which prints</p> <pre><code>"Hi , my name is Bob !" </code></pre> <p>when what I want printed is:</p> <pre><code>"Hi, my name is Bob!" </code></pre> <p>How do I not add spaces before periods and exclamation points? I want a more general case so that I can for example read in a text file as a list, and convert it to a string.</p> <p>Thanks!</p>
-1
2016-10-01T21:41:52Z
39,811,748
<p>To solve it in a general case, use the <code>nltk</code>'s <a href="https://github.com/nltk/nltk/pull/1282" rel="nofollow">"moses" detokenizer</a>:</p> <pre><code>In [1]: l = ["Hi", ",", "my", "name", "is", "Bob", "!"] In [2]: from nltk.tokenize.moses import MosesDetokenizer In [3]: detokenizer = MosesDetokenizer() In [4]: detokenizer.detokenize(l, return_str=True) Out[4]: u'Hi, my name is Bob!' </code></pre> <p>The detokenizer is not yet a part of a stable <code>nltk</code> package. To be able to use it now, install <code>nltk</code> directly from github.</p>
2
2016-10-01T21:45:07Z
[ "python", "string", "list" ]
Python list to string spacing
39,811,720
<p>I have a list such as this</p> <pre><code>list = ['Hi', ',', 'my', 'name', 'is', 'Bob', '!'] </code></pre> <p>I wanted to convert this to a string, and originally, I found on stackoverflow that .join() could be used. So i did:</p> <pre><code>x = ' '.join(list) print(x) </code></pre> <p>which prints</p> <pre><code>"Hi , my name is Bob !" </code></pre> <p>when what I want printed is:</p> <pre><code>"Hi, my name is Bob!" </code></pre> <p>How do I not add spaces before periods and exclamation points? I want a more general case so that I can for example read in a text file as a list, and convert it to a string.</p> <p>Thanks!</p>
-1
2016-10-01T21:41:52Z
39,811,796
<p>How about this, using simple regex?</p> <pre><code>import re list = ['Hi', ',', 'my', 'name', 'is', 'Bob', '!'] x = re.sub(r' (\W)',r'\1',' '.join(list)) print(x) &gt;&gt;&gt; Hi, my name is Bob! </code></pre>
1
2016-10-01T21:52:18Z
[ "python", "string", "list" ]
Python list to string spacing
39,811,720
<p>I have a list such as this</p> <pre><code>list = ['Hi', ',', 'my', 'name', 'is', 'Bob', '!'] </code></pre> <p>I wanted to convert this to a string, and originally, I found on stackoverflow that .join() could be used. So i did:</p> <pre><code>x = ' '.join(list) print(x) </code></pre> <p>which prints</p> <pre><code>"Hi , my name is Bob !" </code></pre> <p>when what I want printed is:</p> <pre><code>"Hi, my name is Bob!" </code></pre> <p>How do I not add spaces before periods and exclamation points? I want a more general case so that I can for example read in a text file as a list, and convert it to a string.</p> <p>Thanks!</p>
-1
2016-10-01T21:41:52Z
39,811,831
<p>A little different solution:</p> <pre><code>&gt;&gt;&gt; from string import punctuation &gt;&gt;&gt; lis = ["Hi", ",", "my", "name", "is", "Bob", "!"] &gt;&gt;&gt; string = '' &gt;&gt;&gt; for i, x in enumerate(lis): if x not in punctuation and i != 0: string += ' ' + x elif x not in punctuation and i == 0: string += x else: string += x &gt;&gt;&gt; print(string) "Hi, my name is Bob!" </code></pre>
0
2016-10-01T21:57:34Z
[ "python", "string", "list" ]
How can jupyter access a new tensorflow module installed in the right path?
39,811,840
<p>Where should I stick the model folder? I'm confused because python imports modules from somewhere in anaconda (e.g. import numpy), but I can also import data (e.g. file.csv) from the folder in which my jupyter notebook is saved in.</p> <p>The TF-Slim image models library is not part of the core TF library. So I checked out the tensorflow/models repository as:</p> <pre><code> cd $HOME/workspace git clone https://github.com/tensorflow/models/ </code></pre> <p>I'm not sure what $HOME/workspace is. I'm running a ipython/jupyter notebook from users/me/workspace/ so I saved it to:</p> <pre><code>users/me/workspace/models </code></pre> <p>In jupyter, I'll write:</p> <pre><code>import tensorflow as tf from datasets import dataset_utils # Main slim library slim = tf.contrib.slim </code></pre> <p>But I get an error: </p> <pre><code>ImportError: No module named datasets </code></pre> <p>Any tips? I understand that my tensorflow code is stored in '/Users/me/anaconda/lib/python2.7/site-packages/tensorflow/<strong>init</strong>.pyc' so maybe I should save the new models folder (which contains models/datasets) there?</p>
0
2016-10-01T21:59:04Z
39,813,220
<p>From the error "ImportError: No module named datasets" <br> It seems that no package named datasets is present. You need to install datasets package and then run your script. <br> Once you install it, then you can find the package present in location <br>"/Users/me/anaconda/lib/python2.7/site-packages/" or at the <br>location "/Users/me/anaconda/lib/python2.7/" <br><br>Download the package from <a href="https://pypi.python.org/pypi/dataset" rel="nofollow">https://pypi.python.org/pypi/dataset</a> and install it.<br>This should work</p>
2
2016-10-02T02:10:31Z
[ "python", "terminal", "tensorflow", "jupyter", "jupyter-notebook" ]
Package installed by Conda, Python cannot find it
39,811,929
<p>I try to install Theano by Anaconda. It works, but when I enter the python -i, <code>import theano</code> shows <code>No module named 'theano'</code>. Do I need to switch another interpreter of Python, how? Also, for the packages installed by conda, if I don't double install them, can I find in Python? How is Python related to Python by Anaconda? Thanks!!!</p>
1
2016-10-01T22:10:59Z
39,813,246
<p>You can refer to a specific version of python by using the following at the first line of your .py file This is for python 2.7</p> <pre><code>#!/usr/bin/env python3 </code></pre> <p>This is for python 3</p> <pre><code>#!/usr/bin/env python </code></pre> <p>As other users already pointed out you need to check if your module is included in your sys path. Use code:</p> <pre><code>import sys print(sys.path) </code></pre> <p>If not you can include this in your sys.path by using the command:</p> <pre><code>sys.path.append('/path/to/the/folder/of/your/module/file') </code></pre> <p>or place it in default PYTHONPATH itself.</p> <p>Other great answers: <a href="http://stackoverflow.com/a/19305076/5381704">http://stackoverflow.com/a/19305076/5381704</a></p>
-1
2016-10-02T02:17:07Z
[ "python", "anaconda", "theano", "conda" ]
How to apply a backtracking algorithm?
39,811,963
<p>I'm doing some excercises in Python course and one of them where I'm stuck is below:</p> <pre><code>Given a digit sequence that represents a message where each uppercase letter is replaced with a number (A - 1, B - 2, ... , Z - 26) and space - 0. Find the number of the initial messages, from which that sequence could be obtained. Example: 12345 - 3 (ABCDE, LCDE, AWDE) 11 - 2 (AA, K) </code></pre> <p>The naive solution is easy and it is simple bruteforce algorithm:</p> <pre><code>import string def count_init_messages(sequence): def get_alpha(seq): nonlocal count if len(seq) == 0: count += 1 return for i in range(1, len(seq) + 1): if seq[:i] not in alph_table: break else: get_alpha(seq[i:]) alphabet = " " + string.ascii_uppercase # generate dictionary of possible digit combination alph_table = {str(n): alph for n, alph in zip(range(len(alphabet)), alphabet)} # counter for the right combination met count = 0 get_alpha(sequence) return count def main(): sequence = input().rstrip() print(count_init_messages2(sequence)) if __name__ == "__main__": main() </code></pre> <p>But as the length of an input sequence might be as long as 100 characters and there might be lots of repetition I have met a time limits. For example, one of the sample input is <code>2222222222222222222222222222222222222222222222222222222222222222222222 (possible messages number is 308061521170129)</code>. As my implementation makes too many repetition it takes ages for processing such an input. I think of using the backtracking algorithm, but I haven't realised yet how to implement the memoization for the succesive results.</p> <p>I'd be glad if it is possible to point me out to the right way how to break that task.</p>
4
2016-10-01T22:16:16Z
39,812,014
<p>The largest number in the lookup table is 26 so you never need to lookup strings of lengths greater than 2. Modify the for loop accordingly. That might be enough to make brute force viable.</p>
0
2016-10-01T22:24:13Z
[ "python", "algorithm", "backtracking" ]
How to apply a backtracking algorithm?
39,811,963
<p>I'm doing some excercises in Python course and one of them where I'm stuck is below:</p> <pre><code>Given a digit sequence that represents a message where each uppercase letter is replaced with a number (A - 1, B - 2, ... , Z - 26) and space - 0. Find the number of the initial messages, from which that sequence could be obtained. Example: 12345 - 3 (ABCDE, LCDE, AWDE) 11 - 2 (AA, K) </code></pre> <p>The naive solution is easy and it is simple bruteforce algorithm:</p> <pre><code>import string def count_init_messages(sequence): def get_alpha(seq): nonlocal count if len(seq) == 0: count += 1 return for i in range(1, len(seq) + 1): if seq[:i] not in alph_table: break else: get_alpha(seq[i:]) alphabet = " " + string.ascii_uppercase # generate dictionary of possible digit combination alph_table = {str(n): alph for n, alph in zip(range(len(alphabet)), alphabet)} # counter for the right combination met count = 0 get_alpha(sequence) return count def main(): sequence = input().rstrip() print(count_init_messages2(sequence)) if __name__ == "__main__": main() </code></pre> <p>But as the length of an input sequence might be as long as 100 characters and there might be lots of repetition I have met a time limits. For example, one of the sample input is <code>2222222222222222222222222222222222222222222222222222222222222222222222 (possible messages number is 308061521170129)</code>. As my implementation makes too many repetition it takes ages for processing such an input. I think of using the backtracking algorithm, but I haven't realised yet how to implement the memoization for the succesive results.</p> <p>I'd be glad if it is possible to point me out to the right way how to break that task.</p>
4
2016-10-01T22:16:16Z
39,812,097
<p>The recurrence relation you have to solve (where <code>s</code> is a string of digits, and <code>a</code> and <code>b</code> are single digits) is this:</p> <pre><code> S("") = 1 S(a) = 1 S(s + a + b) = S(s+a) + (S(s) if ab is between 10 and 26) </code></pre> <p>That can be computed using dynamic programming rather than backtracking. If you do it right, it's O(n) time complexity, and O(1) space complexity.</p> <pre><code>def seq(s): a1, a2 = 1, 1 for i in xrange(1, len(s)): a1, a2 = a1 + (a2 if 9 &lt; int(s[i-1:i+1]) &lt; 27 else 0), a1 return a1 print seq('2222222222222222222222222222222222222222222222222222222222222222222222') </code></pre>
4
2016-10-01T22:38:00Z
[ "python", "algorithm", "backtracking" ]
How to apply a backtracking algorithm?
39,811,963
<p>I'm doing some excercises in Python course and one of them where I'm stuck is below:</p> <pre><code>Given a digit sequence that represents a message where each uppercase letter is replaced with a number (A - 1, B - 2, ... , Z - 26) and space - 0. Find the number of the initial messages, from which that sequence could be obtained. Example: 12345 - 3 (ABCDE, LCDE, AWDE) 11 - 2 (AA, K) </code></pre> <p>The naive solution is easy and it is simple bruteforce algorithm:</p> <pre><code>import string def count_init_messages(sequence): def get_alpha(seq): nonlocal count if len(seq) == 0: count += 1 return for i in range(1, len(seq) + 1): if seq[:i] not in alph_table: break else: get_alpha(seq[i:]) alphabet = " " + string.ascii_uppercase # generate dictionary of possible digit combination alph_table = {str(n): alph for n, alph in zip(range(len(alphabet)), alphabet)} # counter for the right combination met count = 0 get_alpha(sequence) return count def main(): sequence = input().rstrip() print(count_init_messages2(sequence)) if __name__ == "__main__": main() </code></pre> <p>But as the length of an input sequence might be as long as 100 characters and there might be lots of repetition I have met a time limits. For example, one of the sample input is <code>2222222222222222222222222222222222222222222222222222222222222222222222 (possible messages number is 308061521170129)</code>. As my implementation makes too many repetition it takes ages for processing such an input. I think of using the backtracking algorithm, but I haven't realised yet how to implement the memoization for the succesive results.</p> <p>I'd be glad if it is possible to point me out to the right way how to break that task.</p>
4
2016-10-01T22:16:16Z
39,813,754
<p>You may have also recognized 308061521170129 as the 71st Fibonacci number. This relationship corresponds with the Fibonacci numbers giving "the solution to certain enumerative problems. The most common such problem is that of counting the number of compositions of 1s and 2s that sum to a given total n: there are Fn+1 ways to do this" (<a href="https://en.wikipedia.org/wiki/Fibonacci_number#Use_in_mathematics" rel="nofollow">https://en.wikipedia.org/wiki/Fibonacci_number#Use_in_mathematics</a>).</p> <p>Every contiguous subsequence in the string that can be divided into either single or double digit codes represents such an <code>n</code> with multiple possible compositions of 1s and 2s; and thus, for every such subsequence within the string, the result must be multiplied by the (subsequence's length + 1) Fibonacci number (in the case of the 70 2's, we just multiply 1 by the 71st Fibonacci number).</p>
0
2016-10-02T04:05:42Z
[ "python", "algorithm", "backtracking" ]
Exceptions in django stop the flow?
39,811,987
<p>in my view I am executing this piece of code:</p> <pre><code>try: activeterm = LeaseTerm.objects.get(lease=lease, is_active = True) except LeaseTenant.DoesNotExist: activeterm = None </code></pre> <p>And I expected there will be no value in <code>LeaseTerm</code> I will get exception but I am getting an error:</p> <blockquote> <p>LeaseTerm matching query does not exist.</p> </blockquote> <p>But I expected that I have handled the exception and flow should continue.</p> <p>What is my miss understanding?</p>
1
2016-10-01T22:19:43Z
39,812,604
<p>Please retry with:</p> <pre><code>try: activeterm = LeaseTerm.objects.get(lease=lease, is_active = True) except LeaseTerm.DoesNotExist: # LeaseTerm activeterm = None </code></pre>
0
2016-10-01T23:56:56Z
[ "python", "django" ]
File written by json.dump() not readable by json.load()
39,812,127
<p>I'm creating a setup script for my Python project. The script reads build configurations from a json file like so:</p> <pre><code>with open('setup.conf','r') as configfile: config = json.load(configfile) </code></pre> <p>which works perfectly. Later in the script, I constrain myself to a part of that object and write this part to another file:</p> <pre><code>config = config[arg] [...] with open('kivy/app.conf','w') as appconfig: json.dump(config,appconfig) </code></pre> <p>which at least does not generate any errors. Upon startup of my main app, I then want to read the file I just created:</p> <pre><code>path = os.path.dirname(os.path.abspath(__file__)) with open(path + '/app.conf','r') as configfile: config = json.load(configfile) </code></pre> <p>This, however, fails with a </p> <pre><code>simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0) </code></pre> <p>indicating that the json written by json.dump() itself is invalid from the very first character onwards. The data itself is as unsuspicious as it can get, all plain ASCII characters, no weird line endings etc.:</p> <pre><code>{"deploy_server": false, "run_server": true, "server": "127.0.0.1", "run_app": true, "deploy_iOS": false, "user": "", "debug": true, "path": "", "deploy_android": false, "port": "8000"} </code></pre> <p>I don't have the slightest idea where this could be coming from. Any help is greatly appreciated!</p> <p><strong>UPDATE</strong></p> <p>I discovered that the very same code above works in a live interpreter session. I conclude from this that there must be something strange going on in the code surrounding this, but I'm at loss here as well: There probably is an obvious elephant in the room, but I can't see it. The surrounding code looks like this:</p> <pre><code>from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from foodcalendar import CalendarWidget from kivy.resources import resource_add_path import os import requests import json [...] class MyApp(App): def __init__(self): super(MyApp,self).__init__() path = os.path.dirname(os.path.abspath(__file__)) print path with open(path + '/app.conf','r') as configfile: for r in configfile: print r config = json.loads(r) self.server = config["server"] </code></pre> <p><strong>UPDATE 2</strong></p> <p>It turns out that the error I'm facing is somehow related to the <code>requests</code> module: If I comment out <code>import requests</code>, everything works as expected, but I'm clueless as to why this happens, since the docs of the <code>json</code> and <code>requests</code> modules remain silent about any incompatibilities...</p> <p><strong>UPDATE 3</strong></p> <p>This seems to be a machine dependent issue. I ran my code on another machine, and there it ran flawlessly. Python is version 2.7.12, OS is Ubuntu 16.04 x86_64, kernel version is 4.4.0.38-generic on both machines...</p>
-1
2016-10-01T22:43:02Z
39,812,944
<p>I copied and pasted the text you supplied as being the file contents, into a variable.</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; a=""" {"deploy_server": false, "run_server": true, "server": "127.0.0.1", "run_app": true, "deploy_iOS": false, "user": "", "debug": true, "path": "", "deploy_android": false, "port": "8000"}""" &gt;&gt;&gt; json.loads(a) {'deploy_android': False, 'run_app': True, 'port': '8000', 'debug': True, 'deploy_server': False, 'server': '127.0.0.1', 'user': '', 'run_server': True, 'deploy_iOS': False, 'path': ''} &gt;&gt;&gt; </code></pre> <p>All works. You could try this also. If you get the same result as I did with this as literal text, then you can be sure the error is with the reading and writing the file. You could try a 'print' of what you are about to feed to json.loads</p>
-1
2016-10-02T01:09:23Z
[ "python", "json", "python-2.7" ]
Trouble hitting the correct dictionary key in Python
39,812,178
<p>I'm new to Python and we have an assignment working with dictionaries and pickles. We had to make a simple phonebook app, but I'm receiving a key error that I can't figure out.<br> Most of the options work, except for the first "Look up an entry". It prompts me for a name (that I have previously pickled) I receive this error:</p> <pre><code>Traceback (most recent call last): File "phonebook.py", line 95, in &lt;module&gt; look_up() File "phonebook.py", line 25, in look_up info_dict = phonebook_dict[name] KeyError: 'lelani' </code></pre> <p>I've tired writing different things for the keys and I've also tried using phonebook_dict instead of info_dict but I continue to receive a KeyError. Normally, I would run this through PythonTutor to catch my error, but since it's using dictionaries and unpickling, I can't. Maybe I'm overthinking it or looking over something obvious, but I would really appreciate any insight. </p> <p>Here's the code: </p> <pre><code>from os.path import exists filename = "phonebook2.pickle" if exists('phonebook.pickle'): print "Loading phonebook" phonebook_file = open("phonebook.pickle", "r") phonebook_dict = pickle.load(phonebook_file) phonebook_file.close() else: phonebook_dict = {} while True: #Looks up an entry def look_up(): name = raw_input("Name? ") info_dict = phonebook_dict[name] if name in info_dict: #how do i fix this?/ won't return set contacts #info_dict = phonebook_dict[name] print "Found entry for %s: " % (name) print "Cell Phone Number: %s" % (info_dict["Cell"]) print "Home Phone Number: %s" % (info_dict["Home"]) print "Work Phone Number: %s" % (info_dict["Work"]) else: print "Entry for %s not found." % name #Sets an entry def set_entry(): print "Please add the name and number to create a new entry:" name = raw_input("Name: ").strip() cell_phone = raw_input("Cell Phone Number? ") home_phone = raw_input("Home Phone Number? ") work_phone = raw_input("Work Phone Number? ") info_dict = { "Cell": cell_phone, "Home": home_phone, "Work": work_phone} phonebook_dict[name] = info_dict print "Entry stored for %s" % name #Deletes an entry def delete_entry(): print "Please enter a name to delete from the phonebook." name = raw_input("Name: ").lower() if name in phonebook_dict: del phonebook_dict[name] print "Deleted entry for %s" % name else: print "%s not found." % name #Lists all entries def list_entries(): for name, info_dict in phonebook_dict.items(): print "Found entry for %s: " % (name) print "*" * 30 print "Cell Phone Number: %s" % (info_dict["Cell"]) print "Home Phone Number: %s" % (info_dict["Home"]) print "Work Phone Number: %s" % (info_dict["Work"]) print "*" * 30 #Saves all entries def save_entries(): phonebook_file = open("phonebook.pickle", "w") pickle.dump(phonebook_dict, phonebook_file) phonebook_file.close() print "Entries saved to the phonebook." print """ Electronic Phone Book ===================== 1\. Look up an entry 2\. Set an entry 3\. Delete an entry 4\. List all entries 5\. Save entries 6\. Quit """ menu_number = int(raw_input("What do you want to do (1-6)? ")) if menu_number == 1: look_up() elif menu_number == 2: set_entry() elif menu_number == 3: delete_entry() elif menu_number == 4: list_entries() elif menu_number == 5: save_entries() elif menu_number == 6: print "Goodbye!" break elif menu_number &gt; 6: print "Invalid option. Please enter a valid option (1-6)." </code></pre> <p>Also, phonebook.pickle for reference: </p> <pre><code>(dp0 S'Autumn' p1 (dp2 S'Cell' p3 S'111-111-1111' p4 sS'Home' p5 S'222-222-2222' p6 sS'Work' p7 S'333-333-3333' p8 ssS'Lelani' p9 (dp10 g3 S'444-444-4444' p11 sg5 S'555-555-5555' p12 sg7 S'666-666-6666' </code></pre> <p>Again, any help is greatly appreciated! </p>
2
2016-10-01T22:49:09Z
39,812,226
<p>You're missing an indentation on your <code>if</code> block.</p> <pre><code>if name in info_dict: #how do i fix this? #info_dict = phonebook_dict[name] print "Found entry for %s: " % (name) print "Cell Phone Number: %s" % (info_dict["Cell"]) print "Home Phone Number: %s" % (info_dict["Home"]) print "Work Phone Number: %s" % (info_dict["Work"]) </code></pre> <p>Should be:</p> <pre><code>if name in info_dict: #how do i fix this? #info_dict = phonebook_dict[name] print "Found entry for %s: " % (name) print "Cell Phone Number: %s" % (info_dict["Cell"]) print "Home Phone Number: %s" % (info_dict["Home"]) print "Work Phone Number: %s" % (info_dict["Work"]) </code></pre> <p>Without the indentation, those print statements will always run, meaning it will try to index your dictionary whether the <code>name</code> is in the dictionary or not.</p>
1
2016-10-01T22:55:22Z
[ "python", "dictionary", "keyerror" ]
Trouble hitting the correct dictionary key in Python
39,812,178
<p>I'm new to Python and we have an assignment working with dictionaries and pickles. We had to make a simple phonebook app, but I'm receiving a key error that I can't figure out.<br> Most of the options work, except for the first "Look up an entry". It prompts me for a name (that I have previously pickled) I receive this error:</p> <pre><code>Traceback (most recent call last): File "phonebook.py", line 95, in &lt;module&gt; look_up() File "phonebook.py", line 25, in look_up info_dict = phonebook_dict[name] KeyError: 'lelani' </code></pre> <p>I've tired writing different things for the keys and I've also tried using phonebook_dict instead of info_dict but I continue to receive a KeyError. Normally, I would run this through PythonTutor to catch my error, but since it's using dictionaries and unpickling, I can't. Maybe I'm overthinking it or looking over something obvious, but I would really appreciate any insight. </p> <p>Here's the code: </p> <pre><code>from os.path import exists filename = "phonebook2.pickle" if exists('phonebook.pickle'): print "Loading phonebook" phonebook_file = open("phonebook.pickle", "r") phonebook_dict = pickle.load(phonebook_file) phonebook_file.close() else: phonebook_dict = {} while True: #Looks up an entry def look_up(): name = raw_input("Name? ") info_dict = phonebook_dict[name] if name in info_dict: #how do i fix this?/ won't return set contacts #info_dict = phonebook_dict[name] print "Found entry for %s: " % (name) print "Cell Phone Number: %s" % (info_dict["Cell"]) print "Home Phone Number: %s" % (info_dict["Home"]) print "Work Phone Number: %s" % (info_dict["Work"]) else: print "Entry for %s not found." % name #Sets an entry def set_entry(): print "Please add the name and number to create a new entry:" name = raw_input("Name: ").strip() cell_phone = raw_input("Cell Phone Number? ") home_phone = raw_input("Home Phone Number? ") work_phone = raw_input("Work Phone Number? ") info_dict = { "Cell": cell_phone, "Home": home_phone, "Work": work_phone} phonebook_dict[name] = info_dict print "Entry stored for %s" % name #Deletes an entry def delete_entry(): print "Please enter a name to delete from the phonebook." name = raw_input("Name: ").lower() if name in phonebook_dict: del phonebook_dict[name] print "Deleted entry for %s" % name else: print "%s not found." % name #Lists all entries def list_entries(): for name, info_dict in phonebook_dict.items(): print "Found entry for %s: " % (name) print "*" * 30 print "Cell Phone Number: %s" % (info_dict["Cell"]) print "Home Phone Number: %s" % (info_dict["Home"]) print "Work Phone Number: %s" % (info_dict["Work"]) print "*" * 30 #Saves all entries def save_entries(): phonebook_file = open("phonebook.pickle", "w") pickle.dump(phonebook_dict, phonebook_file) phonebook_file.close() print "Entries saved to the phonebook." print """ Electronic Phone Book ===================== 1\. Look up an entry 2\. Set an entry 3\. Delete an entry 4\. List all entries 5\. Save entries 6\. Quit """ menu_number = int(raw_input("What do you want to do (1-6)? ")) if menu_number == 1: look_up() elif menu_number == 2: set_entry() elif menu_number == 3: delete_entry() elif menu_number == 4: list_entries() elif menu_number == 5: save_entries() elif menu_number == 6: print "Goodbye!" break elif menu_number &gt; 6: print "Invalid option. Please enter a valid option (1-6)." </code></pre> <p>Also, phonebook.pickle for reference: </p> <pre><code>(dp0 S'Autumn' p1 (dp2 S'Cell' p3 S'111-111-1111' p4 sS'Home' p5 S'222-222-2222' p6 sS'Work' p7 S'333-333-3333' p8 ssS'Lelani' p9 (dp10 g3 S'444-444-4444' p11 sg5 S'555-555-5555' p12 sg7 S'666-666-6666' </code></pre> <p>Again, any help is greatly appreciated! </p>
2
2016-10-01T22:49:09Z
39,812,365
<p>You were close, you need to check if name is in the phonebook_dict</p> <pre><code>def look_up(): name = raw_input("Name? ") if name in phonebook_dict: info_dict = phonebook_dict[name] print "Found entry for %s: " % (name) print "Cell Phone Number: %s" % (info_dict["Cell"]) print "Home Phone Number: %s" % (info_dict["Home"]) print "Work Phone Number: %s" % (info_dict["Work"]) else: print "Entry for %s not found." % name </code></pre>
3
2016-10-01T23:16:55Z
[ "python", "dictionary", "keyerror" ]
How to pivot pandas DataFrame column to create binary "value table"?
39,812,275
<p>I have the following pandas dataframe:</p> <pre><code>import pandas as pd df = pd.read_csv("filename.csv") df A B C D E 0 a 0.469112 -0.282863 -1.509059 cat 1 c -1.135632 1.212112 -0.173215 dog 2 e 0.119209 -1.044236 -0.861849 dog 3 f -2.104569 -0.494929 1.071804 bird 4 g -2.224569 -0.724929 2.234213 elephant ... </code></pre> <p>I would like to create more columns based on the identity of categorical values in <code>column E</code> such that the dataframe looks like this:</p> <pre><code> df A B C D cat dog bird elephant .... 0 a 0.469112 -0.282863 -1.509059 -1 0 0 0 1 c -1.135632 1.212112 -0.173215 0 -1 0 0 2 e 0.119209 -1.044236 -0.861849 0 -1 0 0 3 f -2.104569 -0.494929 1.071804 0 0 -1 0 4 g -2.224569 -0.724929 2.234213 0 0 0 0 ... </code></pre> <p>That is, I pivot the values for column <code>E</code> to be a binary matrix based on the values of <code>E</code>, giving <code>1</code> if the value exists, and <code>0</code> for all others where it doesn't (here, I would like it to be <code>-1</code> or a "negative binary matrix")? </p> <p>I'm not sure which function in pandas best does this: maybe <code>pandas.DataFrame.unstack()</code>? </p> <p>Any insight appreciated!</p>
2
2016-10-01T23:03:06Z
39,812,309
<p>use <code>pd.concat</code>, <code>drop</code>, and <code>get_dummies</code></p> <pre><code>pd.concat([df.drop('E', 1), pd.get_dummies(df.E).mul(-1)], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/4kxQD.png" rel="nofollow"><img src="http://i.stack.imgur.com/4kxQD.png" alt="enter image description here"></a></p>
2
2016-10-01T23:07:53Z
[ "python", "pandas", "dataframe", "binary", "categorical-data" ]
Django : ProgrammingError: column "id" does not exist
39,812,384
<p>I try to use postgresql database (before I had SQLite) but I have a message when I execute <code>python manage.py migrate</code> :</p> <pre><code>Operations to perform: Apply all migrations: sessions, admin, sites, auth, contenttypes, main_app Running migrations: Rendering model states... DONE Applying main_app.0004_auto_20161002_0034...Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 482, in alter_field old_db_params, new_db_params, strict) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql/schema.py", line 110, in _alter_field new_db_params, strict, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 634, in _alter_field params, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column "id" does not exist LINE 1: ..._app_projet" ALTER COLUMN "id" TYPE integer USING "id"::inte... </code></pre> <p>So I guess this error is about my model 'Projet' but this model has ID field ! I see that in <strong>0001_initial.py</strong> :</p> <pre><code>... migrations.CreateModel( name='Projet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=30)), ('presentation', models.TextField(max_length=2500, null=True)), ... </code></pre> <p>My migration main_app.0004_auto_20161002_0034 :</p> <pre><code>class Migration(migrations.Migration): dependencies = [ ('main_app', '0003_auto_20161002_0033'), ] operations = [ migrations.AlterField( model_name='projet', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), ] </code></pre> <p>Projet model is like that :</p> <pre><code>class Group(models.Model) : name = models.CharField(max_length=30, db_index=True) class Meta : abstract = True unique_together = (("id", "name"),) class Projet(Group) : presentation = models.TextField(max_length=2500, null=True) </code></pre> <p>Realy I don't understand why I have this error... my settings configuration database is good, all others models work, ...</p> <p>If I forgot something, please don't hesitate to tell me ! I need realy your helps !</p>
0
2016-10-01T23:19:26Z
39,812,416
<p>Your model definition doesn't identify any of the fields as a primary key, therefore Django assumes a primary key column named <code>id</code>. However this column doesn't actually exist in the table.</p> <p>Change your model definition to designate one of the fields as a primary key, and Django won't try to look for an <code>id</code> column.</p>
0
2016-10-01T23:25:41Z
[ "python", "django", "postgresql" ]
Django : ProgrammingError: column "id" does not exist
39,812,384
<p>I try to use postgresql database (before I had SQLite) but I have a message when I execute <code>python manage.py migrate</code> :</p> <pre><code>Operations to perform: Apply all migrations: sessions, admin, sites, auth, contenttypes, main_app Running migrations: Rendering model states... DONE Applying main_app.0004_auto_20161002_0034...Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 482, in alter_field old_db_params, new_db_params, strict) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql/schema.py", line 110, in _alter_field new_db_params, strict, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 634, in _alter_field params, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column "id" does not exist LINE 1: ..._app_projet" ALTER COLUMN "id" TYPE integer USING "id"::inte... </code></pre> <p>So I guess this error is about my model 'Projet' but this model has ID field ! I see that in <strong>0001_initial.py</strong> :</p> <pre><code>... migrations.CreateModel( name='Projet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=30)), ('presentation', models.TextField(max_length=2500, null=True)), ... </code></pre> <p>My migration main_app.0004_auto_20161002_0034 :</p> <pre><code>class Migration(migrations.Migration): dependencies = [ ('main_app', '0003_auto_20161002_0033'), ] operations = [ migrations.AlterField( model_name='projet', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), ] </code></pre> <p>Projet model is like that :</p> <pre><code>class Group(models.Model) : name = models.CharField(max_length=30, db_index=True) class Meta : abstract = True unique_together = (("id", "name"),) class Projet(Group) : presentation = models.TextField(max_length=2500, null=True) </code></pre> <p>Realy I don't understand why I have this error... my settings configuration database is good, all others models work, ...</p> <p>If I forgot something, please don't hesitate to tell me ! I need realy your helps !</p>
0
2016-10-01T23:19:26Z
39,815,839
<pre><code>class Group(models.Model) : name = models.CharField(max_length=30, unique=True) class Meta: abstract = True class Projet(Group) : presentation = models.CharField(max_length=2500, blank=True) </code></pre> <p>Remove your migration and create a new one.</p> <p>Just adding my two cents. </p> <p>Nullable fields:</p> <blockquote> <p>Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.</p> <p>See <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#null" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/fields/#null</a></p> </blockquote> <p>max_length:</p> <blockquote> <p>If you specify a max_length attribute, it will be reflected in the Textarea widget of the auto-generated form field. However it is not enforced at the model or database level. Use a CharField for that.</p> <p><a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#textfield" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/fields/#textfield</a></p> </blockquote>
1
2016-10-02T10:01:38Z
[ "python", "django", "postgresql" ]
Dealing with missing data in Pandas read_csv
39,812,493
<p>I have not found a satisfying solution to the problem of missing data when importing CSV data into a pandas DataFrame.</p> <p>I have datasets where <em>I don't know in advance what the columns or data types are</em>. I would like pandas to do a better job inferring how to read in the data.</p> <p>I haven't found any combination of <code>na_values=...</code> that really helps. </p> <p>Consider the following csv files:</p> <p><strong>no_holes.csv</strong></p> <pre><code>letter,number a,1 b,2 c,3 d,4 </code></pre> <p><strong>with_holes.csv</strong></p> <pre><code>letter,number a,1 ,2 b, ,4 </code></pre> <p><strong>empty_column.csv</strong></p> <pre><code>letters,numbers ,1 ,2 ,3 ,4 </code></pre> <p><strong>with_NA.csv</strong></p> <pre><code>letter,number a,1 b,NA NA,3 d,4 </code></pre> <p>Here is what happens when I read them into a DataFrame (code below):</p> <pre><code>**no holes** letter number 0 a 1 1 b 2 2 c 3 3 d 4 letter object number int64 dtype: object **with holes** letter number 0 a 1 1 NaN 2 2 b 3 NaN 4 letter object number object dtype: object **empty_column** letters numbers 0 NaN 1 1 NaN 2 2 NaN 3 3 NaN 4 letters float64 numbers int64 dtype: object **with NA** letter number 0 a 1.0 1 b NaN 2 NaN 3.0 3 d 4.0 letter object number float64 dtype: object </code></pre> <p>Is there a way to tell pandas to assume empty values are of <code>object</code> type? I've tried <code>na_values=[""]</code>.</p> <p><strong>demo_holes.py</strong></p> <pre><code>import pandas as pd with_holes = pd.read_csv("with_holes.csv") no_holes = pd.read_csv("no_holes.csv") empty_column = pd.read_csv("empty_column.csv") with_NA = pd.read_csv("with_NA.csv") print("\n**no holes**") print(no_holes.head()) print(no_holes.dtypes) print("\n**with holes**") print(with_holes.head()) print(with_holes.dtypes) print("\n**empty_column**") print(empty_column.head()) print(empty_column.dtypes) print("\n**with NA**") print(with_NA.head()) print(with_NA.dtypes) </code></pre>
2
2016-10-01T23:37:21Z
39,812,709
<p>you want to use the parameter <code>skipinitialspace=True</code></p> <p><strong><em>setup</em></strong> </p> <pre><code>no_holes = """letter,number a,1 b,2 c,3 d,4""" with_holes = """letter,number a,1 ,2 b, ,4""" empty_column = """letters,numbers ,1 ,2 ,3 ,4""" with_NA = """letter,number a,1 b,NA NA,3 d,4""" from StringIO import StringIO import pandas as pd d1 = pd.read_csv(StringIO(no_holes), skipinitialspace=True) d2 = pd.read_csv(StringIO(with_holes), skipinitialspace=True) d3 = pd.read_csv(StringIO(empty_column), skipinitialspace=True) d4 = pd.read_csv(StringIO(with_NA), skipinitialspace=True) pd.concat([d1, d2, d3, d4], axis=1, keys=['no_holes', 'with_holes', 'empty_column', 'with_NA']) </code></pre> <p><a href="http://i.stack.imgur.com/mF1uf.png" rel="nofollow"><img src="http://i.stack.imgur.com/mF1uf.png" alt="enter image description here"></a></p> <hr> <p>if you want those <code>NaN</code>s to be <code>''</code> then use <code>fillna</code></p> <pre><code>d1 = pd.read_csv(StringIO(no_holes), skipinitialspace=True).fillna('') d2 = pd.read_csv(StringIO(with_holes), skipinitialspace=True).fillna('') d3 = pd.read_csv(StringIO(empty_column), skipinitialspace=True).fillna('') d4 = pd.read_csv(StringIO(with_NA), skipinitialspace=True).fillna('') pd.concat([d1, d2, d3, d4], axis=1, keys=['no_holes', 'with_holes', 'empty_column', 'with_NA']) </code></pre> <p><a href="http://i.stack.imgur.com/gqmYI.png" rel="nofollow"><img src="http://i.stack.imgur.com/gqmYI.png" alt="enter image description here"></a></p>
3
2016-10-02T00:16:06Z
[ "python", "pandas", null, "na", "missing-data" ]
How to check if a list contains a string
39,812,514
<p>I need to iterate through a list and check if the value is a string or an int. Is there any easy way to do this in python?</p> <p>For example:</p> <p><code>[1,2,3]</code> would be true.</p> <p><code>["a",2,3]</code> would be false.</p>
-3
2016-10-01T23:40:20Z
39,812,535
<p>You can use a combination of <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code></a> and <a href="https://docs.python.org/3/library/functions.html#isinstance" rel="nofollow"><code>isinstance()</code></a>:</p> <pre><code>In [1]: def contains_string(l): ...: return any(isinstance(item, basestring) for item in l) ...: In [2]: contains_string([1,2,3]) Out[2]: False In [3]: contains_string(['a',2,3]) Out[3]: True </code></pre> <p><code>basestring</code> handles both "unicode" and "str" string types:</p> <ul> <li><a href="http://stackoverflow.com/questions/1979004/what-is-the-difference-between-isinstanceaaa-basestring-and-isinstanceaaa">What is the difference between isinstance(&#39;aaa&#39;, basestring) and isinstance(&#39;aaa&#39;, str)?</a></li> </ul> <p>Note that <code>any()</code> would <em>short-circuit</em> as well once it knows the result, see more about that here:</p> <ul> <li><a href="http://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work">How do Python&#39;s any and all functions work?</a></li> </ul>
3
2016-10-01T23:43:05Z
[ "python", "list" ]
How to check if a list contains a string
39,812,514
<p>I need to iterate through a list and check if the value is a string or an int. Is there any easy way to do this in python?</p> <p>For example:</p> <p><code>[1,2,3]</code> would be true.</p> <p><code>["a",2,3]</code> would be false.</p>
-3
2016-10-01T23:40:20Z
39,812,562
<p>You could do this using <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow">all</a>, which would short circuit once a false condition is met. </p> <pre><code>&gt;&gt;&gt; my_list = [1, 2, 3] &gt;&gt;&gt; all(type(d) == int for d in my_list) True &gt;&gt;&gt; my_list = ['1', 2, 3] &gt;&gt;&gt; all(type(d) == int for d in my_list) False </code></pre> <p><a href="https://docs.python.org/3/library/functions.html#isinstance" rel="nofollow">isinstance</a> could be used when calling <code>all</code> as well: </p> <pre><code>&gt;&gt;&gt; my_list = [1, 2, 3] &gt;&gt;&gt; all(isinstance(d, int) for d in my_list) True &gt;&gt;&gt; my_list = ['1', 2, 3] &gt;&gt;&gt; all(isinstance(d, int) for d in my_list) False </code></pre>
6
2016-10-01T23:47:17Z
[ "python", "list" ]
How to check if a list contains a string
39,812,514
<p>I need to iterate through a list and check if the value is a string or an int. Is there any easy way to do this in python?</p> <p>For example:</p> <p><code>[1,2,3]</code> would be true.</p> <p><code>["a",2,3]</code> would be false.</p>
-3
2016-10-01T23:40:20Z
39,812,744
<p>Two more alternative ways using <code>lambda</code> would be:</p> <pre><code>def contains_string(ls): return (True in map(lambda x: type(x)==str,ls)) </code></pre> <p>or</p> <pre><code>def contains_string(ls): return (filter(lambda x: type(x)==str,ls)!=[]) </code></pre> <p>Sample output:</p> <pre><code>&gt;&gt;&gt; l1 = [1,2,3] &gt;&gt;&gt; l2 = [1,2,3,'a'] &gt;&gt;&gt; contains_string(l1) False &gt;&gt;&gt; contains_string(l2) True </code></pre>
0
2016-10-02T00:22:25Z
[ "python", "list" ]
How to check if a list contains a string
39,812,514
<p>I need to iterate through a list and check if the value is a string or an int. Is there any easy way to do this in python?</p> <p>For example:</p> <p><code>[1,2,3]</code> would be true.</p> <p><code>["a",2,3]</code> would be false.</p>
-3
2016-10-01T23:40:20Z
39,815,107
<p>Assuming you meant that you need to check through all the values of the list and that only if they were all integers the function would return True, this is how I'd do it:</p> <pre><code>def test(list): result=True for elem in list: if type(elem)!=int: result=False return result </code></pre>
0
2016-10-02T08:11:59Z
[ "python", "list" ]
Getting 'Refreshing due to a 401' when trying to connect using remote_api
39,812,525
<p>I am trying to connect to the production datastore running on Google App Engine based on <a href="https://cloud.google.com/appengine/docs/python/tools/remoteapi#enabling_remote_api_access_in_your_app" rel="nofollow">https://cloud.google.com/appengine/docs/python/tools/remoteapi#enabling_remote_api_access_in_your_app</a> and <a href="http://stackoverflow.com/questions/33378616/appengine-remote-api-returning-401-and-too-many-auth">AppEngine - Remote API returning 401 and too-many-auth</a> and <a href="http://stackoverflow.com/questions/32567357/gae-remote-api-and-application-default-credentials">GAE: remote_api and Application Default Credentials</a> and others.</p> <p>This is my code to connect to Google App Engine Datastore</p> <pre><code>try: import dev_appserver dev_appserver.fix_sys_path() except ImportError: print('Please make sure the App Engine SDK is in your PYTHONPATH.') raise from google.appengine.ext.remote_api import remote_api_stub import os class RemoteApi: @staticmethod def use_remote_datastore(): os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "my-appengine-default-service-account.json" project_id = 'myapp' project_address = '{}.appspot.com'.format(project_id) RemoteApi.connect2(project_address) @staticmethod def auth_func2(): return ('myuser@myemail.com','mypassword') @staticmethod def connect2(project_address): remote_api_stub.ConfigureRemoteApiForOAuth( project_address, '/_ah/remote_api', secure=True) </code></pre> <p>But I am getting the error </p> <pre><code>NotSupportedOnThisPlatform </code></pre> <p>If I then set </p> <pre><code>secure=False </code></pre> <p>I then get</p> <pre><code> INFO 2016-10-01 23:35:32,727 client.py:546] Attempting refresh to obtain initial access_token .... File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/dummy_thread.py", line 73, in allocate_lock return LockType() RuntimeError: maximum recursion depth exceeded </code></pre> <p>I tried running</p> <pre><code>gcloud auth login </code></pre> <p>and creating a new service account which are both suggested here <a href="http://stackoverflow.com/questions/33378616/appengine-remote-api-returning-401-and-too-many-auth">AppEngine - Remote API returning 401 and too-many-auth</a></p> <p>Any ideas what I am doing wrong?</p>
2
2016-10-01T23:41:47Z
39,906,108
<p>You have mentioned auth_func2 but have not used it, according to remote_api updates without this information everytime with the oauth request, a connection is not possible. </p> <p>change your <code>connect2</code> method and try this - </p> <pre><code>@staticmethod def connect2(project_address): remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api', auth_func2, project_address) </code></pre> <p>P.S - I am assuming your <code>project_address</code> is right and without 'http://'</p>
0
2016-10-06T21:47:27Z
[ "python", "google-app-engine", "google-oauth2" ]
Django - Ordering by a foreign key
39,812,563
<p>I have a class that's called Movie:</p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=511) tmdb_id = models.IntegerField(null=True, blank=True, unique=True) release = models.DateField(null=True, blank=True) poster = models.TextField(max_length=500, null=True) backdrop = models.TextField(max_length=500, null=True, blank=True) popularity = models.TextField(null=True, blank=True) </code></pre> <p>and a class named Trailer:</p> <pre><code>class Trailer(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) link = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) </code></pre> <p>How can I display all movies ordered by the date of the trailer?</p> <p>I have tried: <code>Movie.objects.order_by('trailer__date')</code> but that causes multiple duplicates and doesn't show them on the right order either, how can I avoid the duplicates and have one entry per each movies ordered by the date of the Trailer object?</p> <p><strong>Edit:</strong> I just noticed that it doesn't display all entries but just some of them</p>
0
2016-10-01T23:47:18Z
39,813,201
<p>Update: the OP wanted this sorted by the latest trailer date, and not by the earliest trailer date.</p> <p>You can use annotate here if you want:</p> <pre><code>from django.db.models import Min qs = Movie.objects.values('title').annotate(latest_trailer=Max('trailer__date')).order_by('-latest_trailer') # Add other columns you want into the `values` if you need them </code></pre> <p>Or you can use your original query and couple it with a dict.</p> <pre><code>from collections import OrderedDict qs = Movie.objects.order_by('-trailer__date') movies = OrderedDict() for x in qs: if x.id not in movies: movies[x.id] = x movies = movies.values() </code></pre> <p>It was unclear what order you wanted the movies in when they had multiple trailers, so I guessed it was based on the earliest trailer.</p>
0
2016-10-02T02:06:24Z
[ "python", "django" ]
Django - Ordering by a foreign key
39,812,563
<p>I have a class that's called Movie:</p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=511) tmdb_id = models.IntegerField(null=True, blank=True, unique=True) release = models.DateField(null=True, blank=True) poster = models.TextField(max_length=500, null=True) backdrop = models.TextField(max_length=500, null=True, blank=True) popularity = models.TextField(null=True, blank=True) </code></pre> <p>and a class named Trailer:</p> <pre><code>class Trailer(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) link = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) </code></pre> <p>How can I display all movies ordered by the date of the trailer?</p> <p>I have tried: <code>Movie.objects.order_by('trailer__date')</code> but that causes multiple duplicates and doesn't show them on the right order either, how can I avoid the duplicates and have one entry per each movies ordered by the date of the Trailer object?</p> <p><strong>Edit:</strong> I just noticed that it doesn't display all entries but just some of them</p>
0
2016-10-01T23:47:18Z
39,819,568
<p>@2ps answer was close but didn't work as I would have liked, whether it was for ascending or descending order, but I finally figured out an answer based on his:</p> <pre><code>from django.db.models import Max qs = Movie.objects.annotate(Max("trailer__date")).order_by('-trailer__date__max') </code></pre>
0
2016-10-02T17:16:31Z
[ "python", "django" ]
Concat two Pandas dataframes without sorting on initial columns
39,812,575
<p>I have two data frames:</p> <p>Dataframe A</p> <pre><code>index ID_1 ID_2 Value 0 1 1 1.0 1 1 2 1.2 2 1 3 1.3 </code></pre> <p>DataFrame B</p> <pre><code>index ID_1 ID_2 Value 0 1 2 1.0 1 1 1 1.2 2 1 3 1.3 </code></pre> <p>And each is sorted by ID_1, then by Value.</p> <p>I want to merge or concatenate the two dataframes so that I can easily determine where ID_2 in dataframe A and dataframe B are not the same - so determine when the sorting I have highlights a difference in the order of the ID_2 column.</p> <p>I have tried to use pd.concat several different ways and I always get this result:</p> <pre><code>index ID_1 ID_2 Value ID_1 ID_2 Value 0 1 1 1.0 1 1 1.2 1 1 2 1.2 1 2 1.0 2 1 3 1.3 1 3 1.3 </code></pre> <p>Rather than what I want:</p> <pre><code>index ID_1 ID_2 Value ID_1 ID_2 Value 0 1 1 1.0 1 2 1.0 1 1 2 1.2 1 1 1.2 2 1 3 1.3 1 3 1.3 </code></pre> <p>Any ideas? I have tried it with different column names, etc.</p> <p>Edit:</p> <p>The solution proposed below of course works, but one must remember to do <code>reset_index(drop=True)</code> on the dataframe to have the indexes reset after the sorting.</p>
2
2016-10-01T23:49:38Z
39,812,637
<p>this works for me<br> assuming <code>'index'</code> is the index for both <code>A</code> and <code>B</code></p> <pre><code>pd.concat([A, B], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/seaPi.png" rel="nofollow"><img src="http://i.stack.imgur.com/seaPi.png" alt="enter image description here"></a></p>
3
2016-10-02T00:04:16Z
[ "python", "pandas", "dataframe" ]
cgi module FieldStorage() function not receiving arguments
39,812,612
<p>I am trying to get a Python cgi module to work. Python file runs well, for example then I try to print out , but once it comes to recive a GET or POST argument the cgi.FieldStorage() function does not receive any input. The print statement for FieldStorage output:</p> <pre><code>FieldStorage(None, None, []) </code></pre> <p>You can find all the necessary code below. I have simplified my script to the bare minimum, trying to made it work. It won't work either via GET nor POST.</p> <pre><code>#!/usr/bin/env python print "Content-type: text/html\n\n" import cgi, cgitb cgitb.enable() form = cgi.FieldStorage() subMail = form.getfirst("mail") print form print subMail </code></pre> <p>The HTML page (nor POST nor GET are working)</p> <pre><code>&lt;form action="cgi-bin/mail.py" method="post" id="frm-landingPage1" class="form"&gt; &lt;div class="input-group"&gt; &lt;input type="text" class="form-control" placeholder="Indirizzo email" name="mail" id="frm-landingPage1-email" required value=""&gt; &lt;span class="input-group-btn"&gt; &lt;input class="btn btn-default" type="submit" value="Invia" name="_submit" id="frm-landingPage1-submit"&gt; &lt;/span&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
0
2016-10-01T23:58:53Z
39,813,146
<p>Make sure you have all pre-settings proper like CGI Environment and make sure the CGI Script is in correct path. Please read this: <a href="https://www.tutorialspoint.com/python/python_cgi_programming.htm" rel="nofollow">https://www.tutorialspoint.com/python/python_cgi_programming.htm</a></p>
0
2016-10-02T01:56:11Z
[ "python", "apache", "cgi" ]
General optimization - implementation in python
39,812,647
<p>I am currently struggling with a gradient descent implementation problem, more on the math side of it. I have a matrix of input values, for example - <code>[[1,1,0,2],[2,3,5,1],[2,1,8,0]]</code>. I want to calculate weights which will minimize the error against output vector, the minimized function is standard linear model so my hypothesis is minimize -> <code>np.dot(input,weights)-y</code>. The problem is - values of weight vector should add to specific number, say 2. Also vector of outputs is normalized such as <code>np.dot(input,weights)/sum(np.dot(input,weights))</code> - this result is then compared to a desired output vector. How should I define this task in python/numpy? </p> <p>Example of human-tuned procedure:</p> <p>1) input matrix <code>[[4,0,2,0,2,0],[2,0,0,2,2,0],[2,0,0,2,2,0],[4,0,2,0,0,0],[0,0,2,0,0,2],[0,4,0,0,0,2],[0,2,0,0,0,2],[0,2,2,0,0,0],[0,0,2,0,0,2],[4,0,2,0,0,0]]</code></p> <p>2) desired output <code>[12.94275893,8.07054252,9.281123898,10.53654162,8.698251382,14.67643103,7.158870124,10.26752354,8.324615155,10.0433418]</code></p> <p>3) weights which transform input vectors in such way that np.dot(input,weights)/sum(np.dot(input,weights)) are okay <code>[11,21,18,0,20,14]</code>- sum fixed at 84</p> <p>4) the final output, reasonably deviated from 2) <code>[15.15,7.83,7.83,10.10,8.08,14.14,8.84,9.85,8.08,10.10]</code></p>
0
2016-10-02T00:05:24Z
39,812,815
<p>For the scale of your example data, here is the solution:</p> <pre><code>import numpy as np from scipy import optimize a = np.array([[1,1,0,2],[2,3,5,1],[2,1,8,0]], dtype=float) target = np.random.randn(3) target /= target.sum() def f(p): p = np.r_[p, 2 - p.sum()] res = a.dot(p) res /= res.sum() return res - target r, _ = optimize.leastsq(f, np.zeros(3)) print(target) print(np.r_[r, 2 - r.sum()]) </code></pre> <p>output:</p> <pre><code>[-0.21987606 0.70869974 0.51117632] [ 2.15713915 7.47554671 0.38959227 -8.02227813] </code></pre> <p>Here is the code for your real data:</p> <pre><code>import numpy as np from scipy import optimize a = np.array([[4,0,2,0,2,0], [2,0,0,2,2,0], [2,0,0,2,2,0], [4,0,2,0,0,0], [0,0,2,0,0,2], [0,4,0,0,0,2], [0,2,0,0,0,2], [0,2,2,0,0,0], [0,0,2,0,0,2], [4,0,2,0,0,0]], dtype=float) target = np.array([12.94275893,8.07054252,9.281123898,10.53654162,8.698251382, 14.67643103,7.158870124,10.26752354,8.324615155,10.0433418]) target /= target.sum() def make_vector(x): return np.r_[x, 84 - x.sum()] def calc_target(x): res = a.dot(make_vector(x)) res /= res.sum() return res def error(x): return calc_target(x) - target x, _ = optimize.leastsq(error, np.zeros(a.shape[1] - 1)) print(make_vector(x)) print(calc_target(x) * 100) print((calc_target(x) - target) * 100) </code></pre> <p>the output:</p> <pre><code>[ 9.40552097 20.32874298 19.8199082 13.13991088 10.00062863 11.30528834] [ 12.90025777 8.63333209 8.63333209 10.2474406 8.25642656 13.78390749 8.39140263 10.65003363 8.25642656 10.2474406 ] [-0.04250116 0.56278957 -0.64779181 -0.28910102 -0.44182483 -0.89252354 1.23253251 0.38251009 -0.0681886 0.2040988 ] </code></pre> <p>It seems that the problem can also be solve by <code>numpy.linalg.lstsq()</code>, but it need to simplify your problem to a linear euqations.</p>
-1
2016-10-02T00:38:45Z
[ "python", "numpy", "optimization", "gradient" ]
Extract text file contents
39,812,652
<pre><code>edit 7 set gateway 118.151.209.177 set priority 1 set device "port3" set comment "Yashtel" edit 56 set dst 130.127.205.17 255.255.255.255 set distance 5 set device "Austin-Backup" set comment " www.scdhhs.gov" edit 59 set dst 10.100.100.0 255.255.252.0 set distance 5 set device "CityMD" set comment "Metronet" </code></pre> <p>The text file has above data i want to extract data from edit XX to set comment only if set device is "Austin-Backup". The file has 100's of edit commands </p> <p>Output should should be like:</p> <pre><code>edit 56 set dst 130.127.205.17 255.255.255.255 set distance 5 set device "Austin-Backup" set comment " www.scdhhs.gov" </code></pre> <p>Below is my code. string = 'set device'</p> <pre><code>word = '"Austin-Backup"' import shutil aa = open("result.txt", 'a') with open('test.txt') as oldfile, open('cript.txt', 'r+') as new: </code></pre> <p>for line in oldfile:</p> <pre><code> new.write(line) new.write('\n') if string not in line: pass elif string in line: if word in line: shutil.copy('cript.txt','result.txt') elif word not in line: print line new.seek(0) new.truncate() </code></pre> <p>After executing the code the cript.txt has only below line and result.txt is empty. </p> <p>set comment "Metronet" </p>
-1
2016-10-02T00:06:14Z
39,812,768
<p>Not sure what you were trying to use <code>shutil</code> to do. If you just want to copy a few lines, you can store them in a buffer, and when you reach the next <code>"edit"</code> line, copy the contents of the buffer to the output file.</p> <pre><code>set_device = 'set device' target = 'Austin-Backup' with open('test.txt', 'r') as infile, open('result.txt', 'w') as outfile: buffer = [] found = False for line in infile: if "edit" in line: # if buffer is worth saving if found: for line in buffer: outfile.write(line) # reset buffer buffer = [line] found = False else: buffer.append(line) if set_device in line and target in line: found = True </code></pre> <p>Though there is likely a more efficient way of approaching the problem.</p> <p>edit: I originally forgot to reset <code>found</code> to <code>False</code> after resetting <code>buffer</code>. Be sure you are using this latest version. Also <code>string</code> is generally a bad variable name because Python uses it internally, and because it isn't descriptive of its contents. </p>
0
2016-10-02T00:28:23Z
[ "python", "python-2.7" ]
Extract text file contents
39,812,652
<pre><code>edit 7 set gateway 118.151.209.177 set priority 1 set device "port3" set comment "Yashtel" edit 56 set dst 130.127.205.17 255.255.255.255 set distance 5 set device "Austin-Backup" set comment " www.scdhhs.gov" edit 59 set dst 10.100.100.0 255.255.252.0 set distance 5 set device "CityMD" set comment "Metronet" </code></pre> <p>The text file has above data i want to extract data from edit XX to set comment only if set device is "Austin-Backup". The file has 100's of edit commands </p> <p>Output should should be like:</p> <pre><code>edit 56 set dst 130.127.205.17 255.255.255.255 set distance 5 set device "Austin-Backup" set comment " www.scdhhs.gov" </code></pre> <p>Below is my code. string = 'set device'</p> <pre><code>word = '"Austin-Backup"' import shutil aa = open("result.txt", 'a') with open('test.txt') as oldfile, open('cript.txt', 'r+') as new: </code></pre> <p>for line in oldfile:</p> <pre><code> new.write(line) new.write('\n') if string not in line: pass elif string in line: if word in line: shutil.copy('cript.txt','result.txt') elif word not in line: print line new.seek(0) new.truncate() </code></pre> <p>After executing the code the cript.txt has only below line and result.txt is empty. </p> <p>set comment "Metronet" </p>
-1
2016-10-02T00:06:14Z
39,813,043
<p>Here's another solution, just in case you were curious:</p> <pre><code>target = 'set device "Austin-Backup"' buffer = [] with open('test.txt') as infile and open('crypt.txt', 'w') as outfile: for line in infile: if not line.strip(): continue if line.startswith("edit"): outfile.write(''.join(buffer)) buffer = [line] continue if not line.startswith('set device'): buffer.append(line) elif line.strip() == target: buffer.append(line) else: buffer = [] outfile.write(''.join(buffer)) </code></pre>
0
2016-10-02T01:32:02Z
[ "python", "python-2.7" ]
python memorize default parameter value or not
39,812,841
<p>From this blog, it seems Python memorize default parameter value during each function call.</p> <p><a href="http://effbot.org/zone/default-values.htm" rel="nofollow">http://effbot.org/zone/default-values.htm</a></p> <p>But I tested and it seems not? For example, the 2nd function call does not print value of x, y is still False other than memorized value?</p> <pre><code>def foo(x, y=False): if y: print x if __name__ == "__main__": foo(100, True) # print foo(300) # not print </code></pre> <p>regards, Lin</p>
-4
2016-10-02T00:45:30Z
39,812,872
<p>Python doesn't "memorize" anything during each call. It saves one <em>default</em> value once, when the function is defined. In your example, when <code>foo</code> is defined, <code>y</code> has a default value of False. In your first call, you pass in a different value for <code>y</code>. That value is used for that call, but doesn't affect the default. On your second call, you don't explicitly pass anything for <code>y</code>, so the default is used.</p> <p>The default value doesn't mean "whatever value was used most recently". It's a default value.</p>
1
2016-10-02T00:52:20Z
[ "python", "python-2.7" ]
python memorize default parameter value or not
39,812,841
<p>From this blog, it seems Python memorize default parameter value during each function call.</p> <p><a href="http://effbot.org/zone/default-values.htm" rel="nofollow">http://effbot.org/zone/default-values.htm</a></p> <p>But I tested and it seems not? For example, the 2nd function call does not print value of x, y is still False other than memorized value?</p> <pre><code>def foo(x, y=False): if y: print x if __name__ == "__main__": foo(100, True) # print foo(300) # not print </code></pre> <p>regards, Lin</p>
-4
2016-10-02T00:45:30Z
39,812,879
<p>The default object for a parameter is determined once and only once, when the function is defined. (I am ignoring the possibility of diffing into the function object from outside and somehow changing the default object.) If the default object is not mutable, as is true of False, end of story.</p> <p>If the default object <em>is</em> mutable, then its contents can be changed without changing the identity of the object. If the Lundh reference, the default object is a list and a list <em>can</em> be mutated. Each call sees the list in its current state.</p>
1
2016-10-02T00:54:15Z
[ "python", "python-2.7" ]
python memorize default parameter value or not
39,812,841
<p>From this blog, it seems Python memorize default parameter value during each function call.</p> <p><a href="http://effbot.org/zone/default-values.htm" rel="nofollow">http://effbot.org/zone/default-values.htm</a></p> <p>But I tested and it seems not? For example, the 2nd function call does not print value of x, y is still False other than memorized value?</p> <pre><code>def foo(x, y=False): if y: print x if __name__ == "__main__": foo(100, True) # print foo(300) # not print </code></pre> <p>regards, Lin</p>
-4
2016-10-02T00:45:30Z
39,813,278
<p>The default object is <em>created</em> once.</p> <p>Maybe this example will simplify the explanation:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; &gt;&gt;&gt; def func(value=random.random()): ... print value ... &gt;&gt;&gt; &gt;&gt;&gt; func() 0.941870977323 &gt;&gt;&gt; func() 0.941870977323 &gt;&gt;&gt; func(1) 1 &gt;&gt;&gt; func() 0.941870977323 &gt;&gt;&gt; </code></pre> <p>The default value is an object which is created when the function is defined. In my case, the created object was random value <code>0.941870977323</code>.</p> <p>Every time the function is called without arguments, the <strong>same default value</strong> is used.</p> <p>When it is called with an argument, then the defaut value is not used.</p> <h2>When is it relevant?</h2> <p>When the default is <code>False</code>, it does not matter, because <code>False</code> is immutable, so it does not matter whether it is an <em>old</em> <code>False</code>or a <em>new</em> <code>False</code>.</p> <p>If the default is something that can change, it is important to understand that it is created only once:</p> <ul> <li>in case of random: it is a random value, but always the same random value</li> <li>in case of <code>[]</code> an empty list is created once, but if it is modified by adding elements, the next call will not create a new empty list - it will use the same one.</li> </ul>
1
2016-10-02T02:25:21Z
[ "python", "python-2.7" ]
python subprocess.call() cannot find Windows Bash.exe
39,812,882
<p>I have a program that gets output from another program which runs on the new windows subsystem for linux. I have written a python program that runs from the windows system, but will execute the linux program using python subprocess module. If this is confusing see the example below.</p> <p>However, when I do this I find that when called through python subprocess, windows cannot find bash program.</p> <p>example on the commandline or powershell in windows:</p> <pre><code>C:\&gt;bash -c "echo hello world!" hello world! C:\&gt;python Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import subprocess as s &gt;&gt;&gt; s.call('bash -c "echo hello world"'.split()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\Python27-32\lib\subprocess.py", line 524, in call return Popen(*popenargs, **kwargs).wait() File "c:\Python27-32\lib\subprocess.py", line 711, in __init__ errread, errwrite) File "c:\Python27-32\lib\subprocess.py", line 948, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified &gt;&gt;&gt; s.call('bash -c "echo hello world"'.split(),shell=True) 'bash' is not recognized as an internal or external command, operable program or batch file. 1 </code></pre> <p>I thought maybe it wasn't loading my path settings somehow so I put in the full address of the bash program.</p> <pre><code>&gt;&gt;&gt; s.call(b,shell=True) 'C:\Windows\System32\bash.exe' is not recognized as an internal or external command, operable program or batch file. 1 </code></pre> <p>EDIT : I realize my command might be giving a problem since o am splitting on spaces and the "echo hello world" is one argument, but trying the same thing with <code>bash -c ls</code> also gives the same error </p>
0
2016-10-02T00:55:29Z
39,819,465
<p>For 32-bit programs running in the WOW64 subsystem, the "System32" directory <a href="https://msdn.microsoft.com/en-us/library/aa384187" rel="nofollow">gets redirected</a> to "SysWOW64". The WSL bash.exe loader is distributed as a 64-bit executable, so from 32-bit Python you need to use the virtual "SysNative" directory. For example:</p> <pre><code>import os import platform import subprocess is32bit = (platform.architecture()[0] == '32bit') system32 = os.path.join(os.environ['SystemRoot'], 'SysNative' if is32bit else 'System32') bash = os.path.join(system32, 'bash.exe') subprocess.check_call('"%s" -c "echo \'hello world\'"' % bash) </code></pre> <p>Note that currently Windows pipes aren't bridged to WSL pipes, so if you try to use <code>stdout=PIPE</code> or <code>subprocess.check_output</code>, the WSL bash loader will fail. You could read the console output directly via <code>ReadConsoleOutputCharacter</code> (e.g. see <a href="http://stackoverflow.com/a/38749458/205580">this answer</a>). Or, more simply, you can redirect output to a temporary file, passing the temporary file's path translated as a WSL path. For example:</p> <pre><code>import tempfile def wintolin(path): path = os.path.abspath(path) if path[1:2] == ':': drive = path[:1].lower() return '/mnt/' + drive + path[2:].replace('\\', '/') cmd = '"%s" -c "echo \'hello world\' &gt; \'%s\'"' with tempfile.NamedTemporaryFile(mode='r', encoding='utf-8') as f: subprocess.check_call(cmd % (bash, wintolin(f.name))) out = f.read() </code></pre>
1
2016-10-02T17:04:32Z
[ "python", "windows", "bash", "subprocess" ]
Retain feature names after Scikit Feature Selection
39,812,885
<p>After running a Variance Threshold from Scikit-Learn on a set of data, it removes a couple of features. I feel I'm doing something simple yet stupid, but I'd like to retain the names of the remaining features. The following code: </p> <pre><code>def VarianceThreshold_selector(data): selector = VarianceThreshold(.5) selector.fit(data) selector = (pd.DataFrame(selector.transform(data))) return selector x = VarianceThreshold_selector(data) print(x) </code></pre> <p>changes the following data (this is just a small subset of the rows):</p> <pre><code>Survived Pclass Sex Age SibSp Parch Nonsense 0 3 1 22 1 0 0 1 1 2 38 1 0 0 1 3 2 26 0 0 0 </code></pre> <p>into this (again just a small subset of the rows)</p> <pre><code> 0 1 2 3 0 3 22.0 1 0 1 1 38.0 1 0 2 3 26.0 0 0 </code></pre> <p>Using the get_support method, I know that these are Pclass, Age, Sibsp, and Parch, so I'd rather this return something more like :</p> <pre><code> Pclass Age Sibsp Parch 0 3 22.0 1 0 1 1 38.0 1 0 2 3 26.0 0 0 </code></pre> <p>Is there an easy way to do this? I'm very new with Scikit Learn, so I'm probably just doing something silly. </p>
1
2016-10-02T00:56:06Z
39,813,297
<p>There's probably better ways to do this, but for those interested here's how I did:</p> <pre><code>def VarianceThreshold_selector(data): #Select Model selector = VarianceThreshold(0) #Defaults to 0.0, e.g. only remove features with the same value in all samples #Fit the Model selector.fit(data) features = selector.get_support(indices = True) #returns an array of integers corresponding to nonremoved features features = [column for column in data[features]] #Array of all nonremoved features' names #Format and Return selector = pd.DataFrame(selector.transform(data)) selector.columns = features return selector </code></pre>
1
2016-10-02T02:28:39Z
[ "python", "pandas", "scikit-learn", "output", "feature-selection" ]
Retain feature names after Scikit Feature Selection
39,812,885
<p>After running a Variance Threshold from Scikit-Learn on a set of data, it removes a couple of features. I feel I'm doing something simple yet stupid, but I'd like to retain the names of the remaining features. The following code: </p> <pre><code>def VarianceThreshold_selector(data): selector = VarianceThreshold(.5) selector.fit(data) selector = (pd.DataFrame(selector.transform(data))) return selector x = VarianceThreshold_selector(data) print(x) </code></pre> <p>changes the following data (this is just a small subset of the rows):</p> <pre><code>Survived Pclass Sex Age SibSp Parch Nonsense 0 3 1 22 1 0 0 1 1 2 38 1 0 0 1 3 2 26 0 0 0 </code></pre> <p>into this (again just a small subset of the rows)</p> <pre><code> 0 1 2 3 0 3 22.0 1 0 1 1 38.0 1 0 2 3 26.0 0 0 </code></pre> <p>Using the get_support method, I know that these are Pclass, Age, Sibsp, and Parch, so I'd rather this return something more like :</p> <pre><code> Pclass Age Sibsp Parch 0 3 22.0 1 0 1 1 38.0 1 0 2 3 26.0 0 0 </code></pre> <p>Is there an easy way to do this? I'm very new with Scikit Learn, so I'm probably just doing something silly. </p>
1
2016-10-02T00:56:06Z
39,813,304
<p>Would something like this help? If you pass it a pandas dataframe, it will get the columns and use <code>get_support</code> like you mentioned to iterate over the columns list by their indices to pull out only the column headers that met the variance threshold.</p> <pre><code>&gt;&gt;&gt; df Survived Pclass Sex Age SibSp Parch Nonsense 0 0 3 1 22 1 0 0 1 1 1 2 38 1 0 0 2 1 3 2 26 0 0 0 &gt;&gt;&gt; def VarianceThreshold_selector(data): columns = data.columns selector = VarianceThreshold(.5) selector.fit_transform(data) labels = [columns[x] for x in selector.get_support(indices=True) if x] return pd.DataFrame(selector.fit_transform(data), columns=labels) &gt;&gt;&gt; VarianceThreshold_selector(df) Pclass Age 0 3 22 1 1 38 2 3 26 </code></pre>
1
2016-10-02T02:30:20Z
[ "python", "pandas", "scikit-learn", "output", "feature-selection" ]
how to display image uploaded in a submitted form with ploneformgen?
39,813,031
<p>I'm using <strong>ploneformgen</strong>. [edited] I'm using a <strong>custom script adapter</strong> from ploneformgen to create a page using the information from submitted forms. The problem is: the page generated when i submit, doesn't show the image. I would like to create a page/document with text AND one image. How can I do this?</p> <p>I've tried this code:</p> <pre><code>#Creating the folder in zope instance. I gave the name 'conteudo' to it. targetdir = context.conteudo #Here asking for the form, so we can access its contents form = request.form #Creating an unique ID from DateTime import DateTime uid= str(DateTime().millis()) # Creating a new Page (Document) targetdir.invokeFactory('Document',id=uid, title= 'Minha Página', image= form['foto-de-perfil_file'],text='&lt;b&gt;Nome Completo:&lt;/b&gt;&lt;br&gt;'+form ['nome-completo']+'&lt;br&gt;&lt;br&gt;'+'&lt;b&gt;Formação:&lt;/b&gt;&lt;br&gt;'+form ['formacao']+'&lt;br&gt;&lt;br&gt;'+'&lt;b&gt;Áreas de Atuação:&lt;/b&gt;&lt;br&gt;'+form['areas-de- atuacao']+'&lt;br&gt;&lt;br&gt;'+'&lt;b&gt;Links:&lt;/b&gt;&lt;br&gt;'+form['links']) # Set the reference for our new Page doc = targetdir.get('uid',targetdir) # Reindexed the Page in the site doc.reindexObject() </code></pre> <p>It only shows the text, but the picture isn't there.</p> <p>I tried using "setImage", but it shows an attribute error. I tried making another invokefactory but instead of 'Document', I put 'Image' then it only shows the image.</p> <p><strong>What should I modify on my code to display <em>both</em> the text and the picture?</strong></p> <p>Thanks in advance.</p>
0
2016-10-02T01:29:06Z
40,014,638
<p>On a standard Plone Document content type does not own any image field.</p> <p>If you are on Plone 4 using old ATContentTypes you must install and configure <a href="https://pypi.python.org/pypi/collective.contentleadimage" rel="nofollow">collective.contentleadimage</a>. On Plone 5 or if you are using Dexterity based contents you must add the new image field to your schema.</p>
0
2016-10-13T07:18:42Z
[ "python", "plone", "ploneformgen" ]
Count the number of times each element appears in a list. Then making a conditional statement from that
39,813,046
<p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains each of the integers between 1 and 6 exactly once, and False otherwise.</p> <p>This is homework and I thought I had it right, but it is now telling me that it isn't right. Here is my code.</p> <pre><code>def isItAStraight(aList): count = 0 for i in set(aList): count += 1 return aList.count(i) == 1 </code></pre> <p>for some reason even if a number appears more than once it still gives true and I can't figure out why it won't give me false unless the first or last number are changed.</p> <p>Each number has to occur only one time otherwise it is false.</p> <p>So like take [1,2,3,4,5,6] would be true. But [1,2,2,3,4,5] would be false.</p> <p>Also, I can't import things like Counter or collections (though it would be so much easier to do it isn't apart of the assignment.)</p> <p>The list is randomly generated from 1 to 6.</p>
0
2016-10-02T01:32:55Z
39,813,065
<p>You need to be careful about what's <em>inside</em> the list. What you've written is a basically the same as the pseudo-code below:</p> <pre><code>let count = 0 for every unique element in aList: Add 1 to count if count is now 1, return true. </code></pre> <p>This will <em>always</em> return true if there is at least one element in <code>aList</code>, since you're adding 1 to count and then returning immediately.</p> <p>A couple approaches to consider:</p> <ol> <li>Create a 6 element list of all zeros called <code>flags</code>. Iterate over <code>aList</code> and set the corresponding element in <code>flags</code> to <code>1</code>. If <code>flags</code> is all ones, then you return true.</li> <li>Sort the list, then check if the first six numbers are <code>1, 2, 3, 4, 5, 6</code>.</li> </ol>
2
2016-10-02T01:37:19Z
[ "python", "list", "python-3.x", "count" ]
Count the number of times each element appears in a list. Then making a conditional statement from that
39,813,046
<p>write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains each of the integers between 1 and 6 exactly once, and False otherwise.</p> <p>This is homework and I thought I had it right, but it is now telling me that it isn't right. Here is my code.</p> <pre><code>def isItAStraight(aList): count = 0 for i in set(aList): count += 1 return aList.count(i) == 1 </code></pre> <p>for some reason even if a number appears more than once it still gives true and I can't figure out why it won't give me false unless the first or last number are changed.</p> <p>Each number has to occur only one time otherwise it is false.</p> <p>So like take [1,2,3,4,5,6] would be true. But [1,2,2,3,4,5] would be false.</p> <p>Also, I can't import things like Counter or collections (though it would be so much easier to do it isn't apart of the assignment.)</p> <p>The list is randomly generated from 1 to 6.</p>
0
2016-10-02T01:32:55Z
39,813,073
<p>With a <code>return</code> inside the loop, you are only checking one value. You need to check each value. Also, instead of looping through the items of the list, you should loop through the items you're actually looking for. It would also help to make sure there are the correct number of items in the list.</p> <pre><code>def isItAStraight(aList): if len(aList) != 6: return False for i in range(1, 7): if aList.count(i) != 1: return False return True </code></pre> <p>But the easiest way to do this is to simply sort the list and check if it's what you're looking for:</p> <pre><code>def isItAStraight(aList): return sorted(aList) == list(range(1, 7)) </code></pre>
2
2016-10-02T01:39:04Z
[ "python", "list", "python-3.x", "count" ]
ImportError: No module named 'pkg_resources' in builds on readthedocs.org
39,813,055
<p>I started building docs for a project of mine with readthedocs, and it was working great for a while, but now I get this crazy error:</p> <pre><code>Collecting sphinx==1.3.5 Using cached Sphinx-1.3.5-py2.py3-none-any.whl Collecting Pygments==2.1.3 Using cached Pygments-2.1.3-py2.py3-none-any.whl Collecting setuptools==20.1.1 Using cached setuptools-20.1.1-py2.py3-none-any.whl Collecting docutils==0.12 Using cached docutils-0.12-py3-none-any.whl Collecting mkdocs==0.15.0 Using cached mkdocs-0.15.0-py2.py3-none-any.whl Collecting mock==1.0.1 Collecting pillow==2.6.1 Collecting readthedocs-sphinx-ext from git+https://github.com/rtfd/readthedocs-sphinx-ext.git@0.6-alpha#egg=readthedocs-sphinx-ext Cloning https://github.com/rtfd/readthedocs-sphinx-ext.git (to 0.6-alpha) to /tmp/pip-build-dpx17gw2/readthedocs-sphinx-ext Could not import setuptools which is required to install from a source distribution. Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/user_builds/pyee/envs/latest/local/lib/python3.4/site-packages/pip/req/req_install.py", line 372, in setup_py import setuptools # noqa File "/home/docs/checkouts/readthedocs.org/user_builds/pyee/envs/latest/local/lib/python3.4/site-packages/setuptools/__init__.py", line 11, in &lt;module&gt; from setuptools.extern.six.moves import filterfalse, map File "/home/docs/checkouts/readthedocs.org/user_builds/pyee/envs/latest/local/lib/python3.4/site-packages/setuptools/extern/__init__.py", line 1, in &lt;module&gt; from pkg_resources.extern import VendorImporter ImportError: No module named 'pkg_resources' </code></pre> <p>Do I need to install setuptools somehow? Is that even possible? My module was using setuptools before and it was fine; what changed?</p> <p><strong>EDIT:</strong> This is on the public service, not on my localhost.</p>
0
2016-10-02T01:34:44Z
39,813,095
<p>yes you can install setuptools python package or you can download the package extract it and simply place it in site-packages of your python installation directory or in the location of your pythonpath</p>
0
2016-10-02T01:44:03Z
[ "python", "read-the-docs" ]
Python error - IndexError: list index out of range
39,813,085
<p>I am learning python so this might sound simple, I am trying to run the code below but I keep getting the error message shown, any thoughts on what could be causing it?</p> <pre><code>from geopy import geocoders import csv g_api_key = 'my_google_api_key' g = geocoders.GoogleV3(g_api_key) costco = csv.reader (open('costcolimited.csv'), delimiter = ',') # Print header print "Address, City, State, Zip Code, Latitude, Longitude" for row in costco: full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4] place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0] full_addy + "," + str(lat) + "," + str(lng) </code></pre> <p>The error I am getting</p> <pre><code>Traceback (most recent call last): File "C:\Python27\geocodelocations.py", line 12, in &lt;module&gt; full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4] IndexError: list index out of range </code></pre>
0
2016-10-02T01:41:50Z
39,813,133
<p>The error is caused by referring element out of list range. From your code, it is probably because you start counting element from <code>1</code>. Remember that in python list, index starts from <code>0</code>. If this is your situation, then shift indexes in</p> <pre><code>full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4] </code></pre> <p>to</p> <pre><code>full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3] </code></pre> <p>Otherwise, check your data structure and make sure it is matched with your code.</p> <p>Thanks</p>
0
2016-10-02T01:52:18Z
[ "python", "python-2.7" ]
Python error - IndexError: list index out of range
39,813,085
<p>I am learning python so this might sound simple, I am trying to run the code below but I keep getting the error message shown, any thoughts on what could be causing it?</p> <pre><code>from geopy import geocoders import csv g_api_key = 'my_google_api_key' g = geocoders.GoogleV3(g_api_key) costco = csv.reader (open('costcolimited.csv'), delimiter = ',') # Print header print "Address, City, State, Zip Code, Latitude, Longitude" for row in costco: full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4] place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0] full_addy + "," + str(lat) + "," + str(lng) </code></pre> <p>The error I am getting</p> <pre><code>Traceback (most recent call last): File "C:\Python27\geocodelocations.py", line 12, in &lt;module&gt; full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4] IndexError: list index out of range </code></pre>
0
2016-10-02T01:41:50Z
39,813,163
<p>First of all make sure your CSV file has four columns. Try checking if <code>len(row) &gt;= 4</code>. If it contains you can go on with your code, but the first item in a Python list is referenced by 0 index.</p> <p>Try something like this:</p> <pre><code>for row in costco: if len(row) &lt; 4: print "Invalid file!" break full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3] place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0] full_addy + "," + str(lat) + "," + str(lng) </code></pre>
0
2016-10-02T01:59:03Z
[ "python", "python-2.7" ]
Error Running Flask Tutorial: Flaskr App
39,813,171
<p>Having a little trouble running this in my command prompt (I'm in my <code>flaskr</code> directory already). </p> <p><code>set FLASK_APP=flaskr</code> <code>set DEBUG_MODE=1</code> <code>flask run</code></p> <p><a href="http://flask.pocoo.org/docs/0.11/tutorial/setup/#tutorial-setup" rel="nofollow">http://flask.pocoo.org/docs/0.11/tutorial/setup/#tutorial-setup</a></p> <p>I've followed all the steps up until now. I've read up on some stuff with virtualenv and stuff, but it hasn't really made sense - should I mess around with it or is there an easier fix?</p> <p>My output/error log:</p> <pre><code>Traceback (most recent call last): File "c:\users\david\appdata\local\programs\python\python35-32\lib\runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "c:\users\david\appdata\local\programs\python\python35-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\david\AppData\Local\Programs\Python\Python35-32\Scripts\flask.exe\__main__.py", line 9, in &lt;module&gt; File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 478, in main cli.main(args=args, prog_name=name) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 345, in main return AppGroup.main(self, *args, **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 696, in main rv = self.invoke(ctx) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 1060, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 889, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 534, in invoke return callback(*args, **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args[1:], **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 534, in invoke return callback(*args, **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 388, in run_command app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 124, in __init__ self._load_unlocked() File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 148, in _load_unlocked self._app = rv = self.loader() File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 209, in load_app rv = locate_app(self.app_import_path) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 89, in locate_app __import__(module) ImportError: No module named 'flaskr' C:\Users\david\Documents\Software\Projects\Flaskr&gt;set FLASK_APP=flaskr C:\Users\david\Documents\Software\Projects\Flaskr&gt;set DEBUG_MODE=1 C:\Users\david\Documents\Software\Projects\Flaskr&gt;flask run Traceback (most recent call last): File "c:\users\david\appdata\local\programs\python\python35-32\lib\runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "c:\users\david\appdata\local\programs\python\python35-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\david\AppData\Local\Programs\Python\Python35-32\Scripts\flask.exe\__main__.py", line 9, in &lt;module&gt; File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 478, in main cli.main(args=args, prog_name=name) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 345, in main return AppGroup.main(self, *args, **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 696, in main rv = self.invoke(ctx) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 1060, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 889, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 534, in invoke return callback(*args, **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args[1:], **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 534, in invoke return callback(*args, **kwargs) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 388, in run_command app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 124, in __init__ self._load_unlocked() File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 148, in _load_unlocked self._app = rv = self.loader() File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 209, in load_app rv = locate_app(self.app_import_path) File "c:\users\david\appdata\local\programs\python\python35-32\lib\site-packages\flask\cli.py", line 89, in locate_app __import__(module) ImportError: No module named 'flaskr' </code></pre>
0
2016-10-02T02:00:28Z
39,813,943
<p>You need to install your app as a package on your virtualenv or declare the file extension like <code>FLASK_APP=flaskr.py</code></p>
0
2016-10-02T04:45:19Z
[ "python", "flask", "setup-project" ]
Python Section Sort does not function as it is told to do so
39,813,175
<p>If I input a single digit number or numbers with the same first digit (10, 11, 12, 13), the code works perfectly. However, as soon as this condition is not met, the program thinks 7 is larger than 12...</p> <p>Here is what I have tried.</p> <pre><code>def main(): mark = 0 file_name = input('Enter the name of the file: ') lst = [] for num in open(file_name): lst.append(num.strip()) print(lst) lst = sort(lst, mark) print(lst) def sort(lst, mark): while mark &lt;= len(lst) - 1: minval = lst[mark] for i in range(len(lst)): if lst[i] &gt; minval: lst[i], lst[mark] = lst[mark], lst[i] minval = lst[mark] mark += 1 sort(lst, mark) return lst main() </code></pre>
0
2016-10-02T02:01:09Z
39,813,203
<p>It sounds like you're sorting the numbers as strings instead of as integers. In fact, the string "7" is larger than the string "12" in the same way that the string "g" would come after the string "ab" in the dictionary.</p> <p>You can avoid this by casting your inputs to ints:</p> <pre><code>num = int(input_string) </code></pre>
0
2016-10-02T02:06:29Z
[ "python" ]
How to multiply scalar by ListVector in rpy2
39,813,186
<p>I'm running the following analysis and trying to plot the inverse logit of my model:</p> <pre><code>R.plot(formula, data=data, ylab = 'P(outcome = 1 | outcome)', xlab = 'SURVRATE: Probability of Survival after 5 Years', xaxp = c(0, 95, 19)) a = R.coef(mod1)[0] b = R.coef(mod1)[1] R.curve(invlogit(a + b*R.x)) </code></pre> <p><code>invlogit</code> is an R function that I am accessing via STAP.</p> <p>Everything works great, but when I run the <code>curve</code> function, I get an error that <code>TypeError: unsupported operand type(s) for *: 'float' and 'ListVector'</code>...</p> <p>I've tried various ways of handling this, like using <code>np.multiply</code> among others, all to no avail. How do I handle multiplication of a scalar by a ListVector within python?</p>
0
2016-10-02T02:03:24Z
39,818,575
<p>Kludgey solution is to just use the <code>rmagic</code> commands. It appears to be the path of least resistance to convert all my R code to the rpy2 equivalent.</p>
0
2016-10-02T15:30:56Z
[ "python", "rpy2", "scalar", "vector-multiplication" ]
Identifying and adding values from dict to another dict, while both contain the similar keys
39,813,267
<p>Let's say I had these two dictionaries, both containing similar keys to each other:</p> <pre><code>d_1 = {'a': 3, 'b': 4, 'c': 1} d_2 = {'a': 5, 'b': 6, 'c': 9, 'd': 7} </code></pre> <p>Now, let's say I want to take the values of <code>d_1</code> and add them to the corresponding values of <code>d_2</code>. How would I add the values of <code>d_1</code>'s <code>a</code> key to the respective key in <code>d_2</code> w/o individually saying <code>d_2['a'] += d_1['a']</code> for each key? How could I go about writing a function that can take two dicts, compare their keys, and add those values to the identical existing key values in another dict? </p> <p>For example, if I had a class named <code>player</code> and it has an attribute of <code>skills</code> which contains several skills and their values, e.g. <code>strength: 10</code> or <code>defense: 8</code>, etc. Now, if that <code>player</code> were to come across an armor set, or whatever, that buffed specific skills, how could I take that buff dictionary, see what keys it has in common with the <code>player</code>'s <code>skills</code> attribute, and add the respective values?</p>
1
2016-10-02T02:22:43Z
39,813,384
<p>For every key in d_2, check if them in d_1, if so, add them up.</p> <p><code>for key in d_2: if key in d_1: d_2[key] += d_1[key]</code></p> <p>It seems you want to built a game, then you might not want to mess with the player's attribute. add them up and put the outcome to a new dict would be better. What's more, you can add more than two dict together, as you might have more than one buff.</p> <p><code>for key in player: outcome[key] = 0 for buff in buffs: if key in buff: outcome[key] += buff[key] outcome[key] += player[key]</code></p>
3
2016-10-02T02:47:14Z
[ "python", "dictionary" ]
Iterating through a list of links and scraping with Selenium
39,813,284
<p>When I try to iterate a through a list of links and visit them with Selenium with this code:</p> <pre><code># create link list urlList = [] with open('my.txt','r') as f: for i in f: urlList.append(i) # navigate to URL for i in (urlList): getUrl = driver.get(i) driver.implicitly_wait(3) </code></pre> <p>I receive this error:</p> <blockquote> <blockquote> <blockquote> <p>selenium.common.exceptions.WebDriverException: Message: unknown error: unhandled inspector error: {"code":-32603,"message":"Cannot navigate to invalid URL"} (Session info: chrome=51.0.2704.106) (Driver info: chromedriver=2.9.248304,platform=Linux 4.2.0-16-generic x86_64</p> </blockquote> </blockquote> </blockquote> <p>Apparently the for loop is generating newline characters from the list and feeding them into the driver.get method. How do I get it to feed urls instead?</p>
0
2016-10-02T02:26:34Z
39,813,340
<p>If your urls read from the file are getting newlines mixed in, try:</p> <pre><code>with open('my.txt','r') as f: for i in f: urlList.append(i.strip()) </code></pre> <p>This will remove leading and trailing whitespace from each <code>i</code>. Also, the <code>\n</code>s are not being generated by the loop, they exist in your file which probably has a url on each line, and a <code>'\n'</code> at the end of each line.</p>
1
2016-10-02T02:38:04Z
[ "python", "selenium", "screen-scraping" ]
Iterating through a list of links and scraping with Selenium
39,813,284
<p>When I try to iterate a through a list of links and visit them with Selenium with this code:</p> <pre><code># create link list urlList = [] with open('my.txt','r') as f: for i in f: urlList.append(i) # navigate to URL for i in (urlList): getUrl = driver.get(i) driver.implicitly_wait(3) </code></pre> <p>I receive this error:</p> <blockquote> <blockquote> <blockquote> <p>selenium.common.exceptions.WebDriverException: Message: unknown error: unhandled inspector error: {"code":-32603,"message":"Cannot navigate to invalid URL"} (Session info: chrome=51.0.2704.106) (Driver info: chromedriver=2.9.248304,platform=Linux 4.2.0-16-generic x86_64</p> </blockquote> </blockquote> </blockquote> <p>Apparently the for loop is generating newline characters from the list and feeding them into the driver.get method. How do I get it to feed urls instead?</p>
0
2016-10-02T02:26:34Z
39,813,440
<p>I run your program on my computer, But I don not get any error?</p> <p>This is <code>my.txt</code> file, there are two china website url in it:</p> <pre><code>https://www.baidu.com/ https://www.sogou.com/ </code></pre> <p>This is <code>test.py</code> file, It will <code>get</code> the websites in <code>my.txt</code>:</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time from selenium import webdriver driver = webdriver.Chrome() # Optional argument, if not specified will search path. urlList = [] with open('my.txt', 'r') as f: for i in f: urlList.append(i) for i in (urlList): print(i) getUrl = driver.get(i) time.sleep(3) driver.implicitly_wait(3) </code></pre> <p>These are the output of my program:</p> <pre><code>➜ /tmp/selenium $ python3 test.py https://www.baidu.com/ https://www.sogou.com/ </code></pre> <p>So I think there may be other mistakes in your program. Can you show the content of the <code>my.txt</code> and the complete code?</p>
0
2016-10-02T02:58:56Z
[ "python", "selenium", "screen-scraping" ]
Creating a python object in C++ and calling its method
39,813,301
<p>In the following document about python embedding, it is well described how to embed python methods in "C" code. <a href="https://docs.python.org/2/extending/embedding.html" rel="nofollow">https://docs.python.org/2/extending/embedding.html</a></p> <p>I tested the above code, it works well with the g++ compiler as well.</p> <p>But the above shows examples of calling the global methods not the class methods.</p> <p>Could anyone show an example about how to create a Python object and call its method from C++?</p>
-2
2016-10-02T02:29:32Z
39,840,385
<p>By doing some investigation, I found that this can be done using the following fourAPIs in series.</p> <ul> <li><p>PyModule_GetDict ; Gets items belonging to the python module. *</p></li> <li><p>PyDict_GetItemString ; Gets the item corresponding to Python class name. </p></li> <li>PyObject_CallObject; Creates the Python object. *</li> <li>PyObject_CallMethod; Class a method of the object.</li> </ul> <p>The following is the sample code that I created even though it still needs to be improved.</p> <pre><code>// Refer to the following website for more information about embedding the // Python code in C++. // https://docs.python.org/2/extending/embedding.html int main() { PyObject *module_name, *module, *dict, *python_class, *object; // Initializes the Python interpreter Py_Initialize(); module_name = PyString_FromString( "work.embedding_python_in_cpp.example.adder"); // Load the module object module = PyImport_Import(module_name); if (module == nullptr) { PyErr_Print(); std::cerr &lt;&lt; "Fails to import the module.\n"; return 1; } Py_DECREF(module_name); // dict is a borrowed reference. dict = PyModule_GetDict(module); if (dict == nullptr) { PyErr_Print(); std::cerr &lt;&lt; "Fails to get the dictionary.\n"; return 1; } Py_DECREF(module); // Builds the name of a callable class python_class = PyDict_GetItemString(dict, "Adder"); if (python_class == nullptr) { PyErr_Print(); std::cerr &lt;&lt; "Fails to get the Python class.\n"; return 1; } Py_DECREF(dict); // Creates an instance of the class if (PyCallable_Check(python_class)) { object = PyObject_CallObject(python_class, nullptr); Py_DECREF(python_class); } else { std::cout &lt;&lt; "Cannot instantiate the Python class" &lt;&lt; std::endl; Py_DECREF(python_class); return 1; } int sum = 0; int x; for (size_t i = 0; i &lt; 5; i++) { x = rand() % 100; sum += x; PyObject *value = PyObject_CallMethod(object, "add", "(i)", x); if (value) Py_DECREF(value); else PyErr_Print(); } PyObject_CallMethod(object, "printSum", nullptr); std::cout &lt;&lt; "the sum via C++ is " &lt;&lt; sum &lt;&lt; std::endl; std::getchar(); Py_Finalize(); return (0); } </code></pre>
0
2016-10-03T21:02:58Z
[ "python", "c++" ]
Is SQLAlchemy/psycopg2 connection to PostgreSQL database encrypted
39,813,312
<p>When I use SQLAlchemy with an external postgreSQL server, is the connection secured/encrypted?</p> <p><code> from sqlalchemy.engine import create_engine engine = create_engine('postgresql://scott:tiger@ip:5432/mydatabase') </code></p> <p>What about psycopg2?</p>
1
2016-10-02T02:31:32Z
39,813,463
<p>Your connection string does not indicate secure connection. However, sometimes connection might be secure nevertheless, but it is unlikely.</p> <p>To have a secure connection to PostgreSQL database you can use <code>sslmode</code> parameter.</p> <pre><code> engine = create_engine('postgresql://scott:tiger@ip:5432/mydatabase?sslmode=verify-full') </code></pre> <p><code>verify-full</code> is the highest level SSL connection validation where the client performs full SSL certificate check for the connection.</p> <p>More info:</p> <ul> <li><a href="https://www.postgresql.org/docs/current/static/libpq-ssl.html" rel="nofollow">https://www.postgresql.org/docs/current/static/libpq-ssl.html</a></li> </ul>
1
2016-10-02T03:03:55Z
[ "python", "postgresql", "sqlalchemy", "psycopg2" ]
> returning == in python 3 triangle exercise
39,813,378
<p>I'm new to programming and this is my first time asking a question, so apologies in advance if I'm breaking any protocols. I tried searching for an answer before posting, but I didn't find any matching results.</p> <p>I'm working my way through Think Python 2, and here is my solution to exercise 5.3, the triangle exercise.</p> <pre><code>def is_tri(): print('Give me 3 lengths') a = int(input('first?\n')) b = int(input('second?\n')) c = int(input('third?\n')) if a &gt; b + c or b &gt; a + c or c &gt; a + b: print('Not a triangle') else: print("Yes, it's a triangle") is_tri() </code></pre> <p>What I noticed is that if I give 3 answers wherein 2 of the lengths equal the third when added together, i.e. (1,1,2), the program returns Yes. But 2 is not greater than 2. I even added a series of 'and' statements requiring that the sum of any two sides must not equal the third, and it still returns Yes:</p> <p>if (a > b + c or b > a + c or c > a + b) and (a != b + c and b != a + c and c != a + b):</p> <p>The author mentions that the sum of two sides equaling the third is a 'degenerate triangle', perhaps anticipating this outcome. But why? Don't the '>' and '>=' operators provide different functions? Am I missing something? How can I constrain the operator to exclude degenerate triangles?</p>
2
2016-10-02T02:45:31Z
39,813,397
<p>Your condition clearly states that the line lengths do not form a triangle only if one length is strictly greater than the sum of the other two. That's not the condition you're looking for. You want to disqualify the input if one is greater <strong>or equal to</strong> the sum of the other two. </p> <p>This would work:</p> <pre><code>if a &gt;= b + c or b &gt;= a + c or c &gt;= a + b: </code></pre>
0
2016-10-02T02:49:57Z
[ "python", "python-3.x" ]
> returning == in python 3 triangle exercise
39,813,378
<p>I'm new to programming and this is my first time asking a question, so apologies in advance if I'm breaking any protocols. I tried searching for an answer before posting, but I didn't find any matching results.</p> <p>I'm working my way through Think Python 2, and here is my solution to exercise 5.3, the triangle exercise.</p> <pre><code>def is_tri(): print('Give me 3 lengths') a = int(input('first?\n')) b = int(input('second?\n')) c = int(input('third?\n')) if a &gt; b + c or b &gt; a + c or c &gt; a + b: print('Not a triangle') else: print("Yes, it's a triangle") is_tri() </code></pre> <p>What I noticed is that if I give 3 answers wherein 2 of the lengths equal the third when added together, i.e. (1,1,2), the program returns Yes. But 2 is not greater than 2. I even added a series of 'and' statements requiring that the sum of any two sides must not equal the third, and it still returns Yes:</p> <p>if (a > b + c or b > a + c or c > a + b) and (a != b + c and b != a + c and c != a + b):</p> <p>The author mentions that the sum of two sides equaling the third is a 'degenerate triangle', perhaps anticipating this outcome. But why? Don't the '>' and '>=' operators provide different functions? Am I missing something? How can I constrain the operator to exclude degenerate triangles?</p>
2
2016-10-02T02:45:31Z
39,813,658
<p>If you need to declare that triangles that have the largest side equal to the sum of the others are invalid you are using the wrong operator, you should use <code>==</code> in conjunction to <code>&gt;</code>, so your condition would look like:</p> <pre><code>if (a &gt; b + c or a == b + c) or (b &gt; a + c or b == a + c ) or (c &gt; a + b or c == a + b): </code></pre> <p>Which is exactly the same as to making it like this:</p> <pre><code>if a &gt;= b + c or b &gt;= a + c or c &gt;= a + b: </code></pre> <p>One nice way of doing it is sorting the list to get the largest element and then comparing to the sum of the others using slices, for this you would need the inputs to be in a list:</p> <pre><code>triangle_sides = [int(input('first?\n')), int(input('second?\n')), int(input('third?\n'))] triangle_sides = sorted(triangle_sides, reverse=True) if triangle_sides[0] &gt;= sum(triangle_sides[1:]): print("Absolutelly not a triangle") else: print("Congratulations, its a triangle") </code></pre> <p>I would also recommend you to get your inputs from outside the function, separating the "user interface" from the logic, your script would look like:</p> <pre><code>def is_valid_triangle(triangle_sides): triangle_sides = sorted(triangle_sides, reverse=True) if triangle_sides[0] &gt;= sum(triangle_sides[1:]): return False return True def triangle_validator(): print('Give me 3 lengths') triangle_sides = [ int(input('first?\n')), int(input('second?\n')), int(input('third?\n')) ] if is_valid_triangle(triangle_sides): print('Yes, it\'s a triangle') else: print('Not a triangle') if __name__ == '__main__': triangle_validator() </code></pre>
1
2016-10-02T03:47:26Z
[ "python", "python-3.x" ]
Why are dictionaries faster than lists in Python?
39,813,433
<pre><code>&gt;&gt;&gt; timeit.timeit('test.append("test")', setup='test = []') 0.09363977164165221 &gt;&gt;&gt; timeit.timeit('test[0] = ("test")', setup='test = {}') 0.04957961010914147 </code></pre> <p>I even tried again with a loop, and same thing:</p> <pre><code>&gt;&gt;&gt; timeit.timeit('for i in range(10): test.append(i)', setup='test = []') 1.3737744340367612 &gt;&gt;&gt; timeit.timeit('for i in range(10): test[i] = i', setup='test = {}') 0.8633718070233272 </code></pre> <p>Why is the list slower?</p>
4
2016-10-02T02:57:29Z
39,813,481
<p>First of all, <code>list.append</code> and <code>dict.__setitem__</code> are both O(1) average case. Of course they will have different coefficients, but there is not really any blanket reason to say that one or the other will be the faster. The coefficients may change depending on implementation detail, too.</p> <p>Secondly, a more fair comparison would be to remove the attribute resolution overhead:</p> <pre><code>&gt;&gt;&gt; timeit.timeit('test[0] = ("test")', setup='test = {}') 0.0813908576965332 &gt;&gt;&gt; timeit.timeit('test_append("test")', setup='test = []; test_append = test.append') 0.06907820701599121 </code></pre> <p>The lookup of the method name on the instance is relatively expensive, when you are looking at an extremely cheap operation such as <code>append</code>. </p> <p>I also see lists being consistently a little faster, once there is some data inside. This example is python 3.5.2:</p> <pre><code>&gt;&gt;&gt; dict_setup = 'import random; test = {random.random(): None for _ in range(1000)}' &gt;&gt;&gt; list_setup = 'import random; test = [random.random() for _ in range(1000)]; test_append=test.append' &gt;&gt;&gt; timeit.timeit('test[0] = "test"', setup=dict_setup) 0.06155529400166415 &gt;&gt;&gt; timeit.timeit('test_append("test")', setup=list_setup) 0.057089386998995906 </code></pre>
4
2016-10-02T03:07:50Z
[ "python", "dictionary" ]
Tkinter - widget with 'grid_remove' built in as part of class
39,813,435
<p>I am doing some experimentation with tkinter and have run into a bit of trouble with grid_remove. I can use it fine with a simple button that links to a command that removes a specific widget, but I can't seem to get it to work when it is part of a class.</p> <p>When I try and run this:</p> <pre><code>class Text(object): def __init__(self, label_text, r, c): self.label_text = label_text self.r = r self.c = c self.label = Label(root, text = self.label_text).grid(row = self.r, column = self.c) def hide(self): self.grid_remove() def show(self): self.grid() </code></pre> <p>I get the error:</p> <pre><code>AttributeError: 'Text' object has no attribute 'grid_remove' </code></pre> <p>I also want to have a button controlling the visibility of the widgets, so how should I specify a command for the button? At the moment I have:</p> <pre><code>button = Button(root, text = 'Hide', command = one.hide()).grid(row = 2) </code></pre>
-3
2016-10-02T02:57:48Z
39,822,146
<p>So, for others who have come across this problem, here's what I needed to change in order to get my script to work.</p> <p>First of all, writing <code>.grid()</code> right after creating the <code>Label</code> was assigning the value of <code>grid</code> to <code>self.label</code> instead of assigning <code>Label</code> to it. The value of <code>grid</code> is a value of none so that was creating the first error. After fixing that part of the code it looks like:</p> <pre><code>self.label = Label(root, text = self.label_text) self.label.grid(row = self.r, column = self.c) </code></pre> <p>The next problem was defining the <code>hide</code> and <code>show</code> functions. I was trying to <code>grid_remove</code> the whole <code>Text</code> class. However, the <code>Text</code> class comprises of many different things, one of which is a <code>Label</code>. I needed to specify to apply <code>grid_remove</code> to only the <code>Label</code> instead of the whole class. After fixing the definitions they look like this:</p> <pre><code>def hide(self): self.label.grid_remove() def show(self): self.label.grid() </code></pre> <p>And the last error was the command in the buttons. I had written <code>command = one.hide()</code>. However, for some reason that is not known to me, I instead had to write only <code>command = one.hide</code> without the parentheses. After fixing that the buttons look like:</p> <pre><code>button = Button(root, text = 'Hide', command = one.hide).grid(row = 2) </code></pre> <p>So the reason my script wasn't working was not due to one simple error but a combination of all of these. I hope this will help someone else in the future!</p>
0
2016-10-02T22:00:33Z
[ "python", "python-3.x", "tkinter" ]
F test with python, finding the critical value
39,813,470
<p>Using python, Is it possible to calculate the critical value on F distribution with x and y degrees of freedom? In other words, I need to calculate the critical value given a x degrees of freedom and a confidence level 5%, but i do not see the table from statistical books, is it posible to get it with any function from python?</p> <p>For example, I want to find the critical value for a F distribution with 3 an 39 degrees of freedom for 5% of confidence level. The answer should be: 2.85</p>
0
2016-10-02T03:05:49Z
39,813,722
<p>IIUC, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.f.html" rel="nofollow"><code>scipy.stats.f.ppf</code></a>, which gives the inverse of the cdf:</p> <pre><code>&gt;&gt;&gt; import scipy.stats &gt;&gt;&gt; scipy.stats.f.ppf(q=1-0.05, dfn=3, dfd=39) 2.8450678052793514 &gt;&gt;&gt; crit = _ &gt;&gt;&gt; scipy.stats.f.cdf(crit, dfn=3, dfd=39) 0.95000000000000007 </code></pre>
1
2016-10-02T03:59:36Z
[ "python" ]
How do I store this in an adjacency list for graphs in python?
39,813,525
<p>Suppose I have a text file containing this:</p> <pre><code>0 1 4 0 2 3 1 4 7 5 3 8 </code></pre> <p>The columns represent:</p> <ol> <li>a vertex</li> <li>another vertex</li> <li>the distance between these two vertices. </li> </ol> <p>For example, in the first line in the text file, 4 is the distance between points 0 and 1. </p> <p>So how would I store the vertices and distances in an adjacency list in python?</p>
0
2016-10-02T03:17:29Z
39,813,765
<p>In graph theory, an <a href="https://en.wikipedia.org/wiki/Adjacency_list" rel="nofollow">adjacent-list</a>, is a collection of unordered lists used to represent a graph. Each list describes the set of neighbors of a vertex in the graph.</p> <p>Since you are talking about adjacent list of weighted graph, you need to define a structure to store both <code>vertex</code> and <code>weight</code>. A graph theory or data structure way to implement adjacent list is like this:</p> <pre><code>class Node(): def __init__(self, v, w, next=None): self.v = v self.w = w self.next = next ... class LinkedList(): def __init__(self, head=None) self.head = head def add_node(): pass ... </code></pre> <p>Here <code>Node</code> class is the base element to compose <code>LinkedList</code> and <code>LinkedList</code> is used to represent adjacent list of one vertex. I do not implement the whole classes for you. See <a href="https://www.codefellows.org/blog/implementing-a-singly-linked-list-in-python/" rel="nofollow">python-linked-list</a>. </p> <p>Assuming your graph is <strong>directed</strong>, the adjacent list of this graph is:</p> <pre><code>0 -&gt; [1:4]-&gt; [2:3] 1 -&gt; [4:7] 2 -&gt; [] 3 -&gt; [] 4 -&gt; [] 5 -&gt; [3:8] </code></pre> <p>in which, <code>0 -&gt; [1:4] -&gt; [2:3]</code> represents the adjacent list of vertex <code>0</code>, which contains two edges: <code>0-&gt;1</code> with weight <code>4</code> and <code>0-&gt;2</code> with weight <code>3</code>. <code>[1:4]</code> could be described by class <code>Node</code>, and the whole row could be represented by class <code>LinkedList</code>. Check <a href="http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/11-Graph/weighted.html" rel="nofollow">weighted-graph-adjacent-list</a> for more information.</p> <p>To represent the whole graph, you can simply use a list of <code>LinkedList</code>, e.g., </p> <pre><code>g = [LinkedList_for_0, LinkedList_for_1, ...] </code></pre> <p>In this approach, <code>g[i]</code> will be the adjacent list of vertex <code>i</code>. </p> <p>To build the whole graph, you can iterate over all edges:</p> <pre><code>g = [[] for v in range(number_of_vertex)] for f, t, w in edges: g[f].add_node(Node(t,w)) </code></pre> <p>In above, as I said, <strong>it's a more data structure way</strong> to implement the adjacent list. If you would to practice your understanding of data structure and graph theory knowledge, you can try this way. But, actually, unlike <code>C/C++</code> <code>array</code> type (fixed size), python <code>list</code> is a mutable type, you can do operations like add, delete on a python <code>list</code>. So <code>LinkedList</code> is actually unnecessarily needed. We can redefine the these classes in a <strong>pythonic way</strong>:</p> <pre><code>class Node(): def __init__(self, v, w): self.v = v self.w = w </code></pre> <p>Here, the <code>Node</code> class do not contain <code>next</code> member. So the adjacent list can be represented as a list of <code>Node</code>, e.g., adjacent list of vertex <code>0</code>:</p> <pre><code>[Node(1,4), Node(2,3)] </code></pre> <p>And the whole graph can be represented as a two dimensional list (Here we assume this is a <strong>undirected</strong> graph.):</p> <pre><code>[ [Node(1,4), Node(2,3)], [Node(0,4), Node(4,7)], [Node(0,3)], [Node(5,8)], [Node(1,7)], [Node(3,8)] ] </code></pre> <p>The python way algorithm:</p> <pre><code>g = [[] for v in range(number_of_vertex)] for f,t,w in edges: g[f].append(Node(t,w)) g[t].append(Node(f,w)) </code></pre> <p>Note: you need to add a new node for <strong>both ends of an edge</strong>.</p> <p>In practice, when handling graph problems, I believe edge-list or sparse matrix is the most common representation. So if it possible, I would suggest you used this kind of representation. </p> <p>Thanks.</p>
1
2016-10-02T04:08:33Z
[ "python", "adjacency-list" ]
How do I store this in an adjacency list for graphs in python?
39,813,525
<p>Suppose I have a text file containing this:</p> <pre><code>0 1 4 0 2 3 1 4 7 5 3 8 </code></pre> <p>The columns represent:</p> <ol> <li>a vertex</li> <li>another vertex</li> <li>the distance between these two vertices. </li> </ol> <p>For example, in the first line in the text file, 4 is the distance between points 0 and 1. </p> <p>So how would I store the vertices and distances in an adjacency list in python?</p>
0
2016-10-02T03:17:29Z
39,821,419
<p>Nested dictionaries are a natural way to represent adjacency lists. Dictionaries are convenient in this situation because they can represent sparse mappings better than lists, and allow efficient lookups.</p> <pre><code>adjacency_list = {} for line in open(file): from, to, weight = map(int, line.split()) adjacency_list.setdefault(from, {})[to] = weight adjacency_list.setdefault(to, {})[from] = weight # for undircted graph add reverse edges </code></pre> <p>To get the weight of an edge between node <code>i</code> and <code>j</code>, you'd lookup <code>adjacency_list.get(i, {}).get(j)</code> (which will return <code>None</code> if the edge doesn't exist).</p> <p>If you didn't want to deal with <code>setdefault</code> and <code>get</code>, you might want to use a <code>defaultdict</code> for at least the top-level dictionary. If you initialize with <code>adjacency_list = defaultdict(dict)</code>, then setting the weights would just be <code>adjacency_list[from][to] = weight</code> (the inner dictionaries will be created automatically whenever they're needed).</p>
0
2016-10-02T20:32:31Z
[ "python", "adjacency-list" ]
How do I store this in an adjacency list for graphs in python?
39,813,525
<p>Suppose I have a text file containing this:</p> <pre><code>0 1 4 0 2 3 1 4 7 5 3 8 </code></pre> <p>The columns represent:</p> <ol> <li>a vertex</li> <li>another vertex</li> <li>the distance between these two vertices. </li> </ol> <p>For example, in the first line in the text file, 4 is the distance between points 0 and 1. </p> <p>So how would I store the vertices and distances in an adjacency list in python?</p>
0
2016-10-02T03:17:29Z
39,821,526
<p>Take a look at <a href="https://networkx.github.io/" rel="nofollow">NetworkX</a> library, it's awesome and easy to use.</p> <p>From <a href="https://networkx.readthedocs.io/en/stable/reference/introduction.html#nodes-and-edges" rel="nofollow">the docs</a>, you can have edge attributes storing any value of interest - distance, in your case:</p> <blockquote> <p>Edges often have data associated with them. <strong><em>Arbitrary data can associated with edges as an edge attribute. If the data is numeric and the intent is to represent a weighted graph then use the ‘weight’ keyword for the attribute.</em></strong> Some of the graph algorithms, such as Dijkstra’s shortest path algorithm, use this attribute name to get the weight for each edge.</p> </blockquote> <p>A possible implementation in your case would be:</p> <pre><code>import networkx as nx G=nx.Graph() for line in file: a, b, w = map(int, line.strip().split(' ')) G.add_edge(a, b, weight=w) </code></pre>
0
2016-10-02T20:44:15Z
[ "python", "adjacency-list" ]
Winning and loosing with roulette wheel
39,813,575
<pre><code>#This is a roulette wheel import random import time #Randomiser green = [0] red = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35] black = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36] spin = random.randint (0,36) #Program bet = int(input("Enter your Bets: ")) colour = input("Pick your Colour: ") print ("The wheel is spinning") if spin in green: print ("The ball stopped on green") print ("You won",bet*100,"!") if spin in red: print ("The ball stopped on red") print ("You won",bet*2,"!") if spin in black: print ("The ball stopped on black") print ("You won",bet*2,"!") </code></pre> <p>It tells if someone won. But it can't tell if someone lost. I've been learning python for a couple of months and was wondering if anyone can help me out. Thanks!</p>
1
2016-10-02T03:27:10Z
39,813,632
<pre><code>if spin in green: winning_color = "green" print("The ball landed on", winning_color) if spin in red: winning_color = "red" print("The ball landed on", winning_color) if spin in black: winning_color = "black" print("The ball landed on", winning_color) if winning_color == colour: print("Congrats you won!") print("You won", bet*2, "!") else: print("Sorry you lose") </code></pre> <p>Something to be aware of, you should use </p> <pre><code>if somethingHappens: doSomething elif somethingElseHappens: #Stands for else if, must be after the first if doThisInstead else: #This is Pythons catchall if the conditions above fail, this will run doThisIfNothingElse </code></pre>
-1
2016-10-02T03:39:40Z
[ "python" ]
Winning and loosing with roulette wheel
39,813,575
<pre><code>#This is a roulette wheel import random import time #Randomiser green = [0] red = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35] black = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36] spin = random.randint (0,36) #Program bet = int(input("Enter your Bets: ")) colour = input("Pick your Colour: ") print ("The wheel is spinning") if spin in green: print ("The ball stopped on green") print ("You won",bet*100,"!") if spin in red: print ("The ball stopped on red") print ("You won",bet*2,"!") if spin in black: print ("The ball stopped on black") print ("You won",bet*2,"!") </code></pre> <p>It tells if someone won. But it can't tell if someone lost. I've been learning python for a couple of months and was wondering if anyone can help me out. Thanks!</p>
1
2016-10-02T03:27:10Z
39,813,653
<p>Maybe I do not know the rules for roulette, but it seems like you have coded it to always print "congrats you won!"</p> <p>First you need to assign the players choice (colour) to a testable value, which in our case is the lists you set up:</p> <pre><code>if "red" in colour: colour = red </code></pre> <p>you would obviously add the other colors here.</p> <p>next you need to test the player's choice against the spin value, something like this will work, you will obviously need to modify it to fit your program though:</p> <pre><code>if spin in colour: print("you win") else: print("you lose") </code></pre> <p>then modify win results as necessary</p>
0
2016-10-02T03:45:52Z
[ "python" ]
Winning and loosing with roulette wheel
39,813,575
<pre><code>#This is a roulette wheel import random import time #Randomiser green = [0] red = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35] black = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36] spin = random.randint (0,36) #Program bet = int(input("Enter your Bets: ")) colour = input("Pick your Colour: ") print ("The wheel is spinning") if spin in green: print ("The ball stopped on green") print ("You won",bet*100,"!") if spin in red: print ("The ball stopped on red") print ("You won",bet*2,"!") if spin in black: print ("The ball stopped on black") print ("You won",bet*2,"!") </code></pre> <p>It tells if someone won. But it can't tell if someone lost. I've been learning python for a couple of months and was wondering if anyone can help me out. Thanks!</p>
1
2016-10-02T03:27:10Z
39,813,682
<p>It looks like aside from <code>0</code>, odd numbers are red and even numbers are green. So this would work even better for you:</p> <pre><code>import random bet = int(input("Enter your Bets: ")) colour = input("Pick your Colour: ") print ("The wheel is spinning") spin = random.randrange(0,37) if spin == 0: print ("The ball stopped on green") print ("You won",bet*100,"!") print ("The ball stopped on", ['black', 'red'][spin%2]) elif ['black', 'red'][spin%2] == color: print ("You won",bet*2,"!") else: print ("You lost!") </code></pre>
0
2016-10-02T03:52:02Z
[ "python" ]
Python import module error
39,813,581
<p>I have a problem in import of modules in my project. I was creating tests and I cant import my main to test one end point of my application, from the test file <code>teste_ex.py</code>. This is my project structure:</p> <pre><code>backend_api/ api/ __init__.py main.py testes/ __init__.py test_ex.py </code></pre> <p>In my test_ex.py Im trying to import <code>main</code> in this way:</p> <pre><code>import api.main from webtest import TestApp def test_functional_concursos_api(): app = TestApp(main.app) assert app.get('/hello').status == '200 OK' </code></pre> <p>I omly get <code>ImportError: No module named 'api'</code></p> <ul> <li>What can be done to import my main to my test file?</li> </ul>
1
2016-10-02T03:29:13Z
39,813,638
<p>Here's my best guess as to what might help:</p> <p>You should make sure that the path to the directory in which your <code>main.py</code> file resides can be found in <code>sys.path</code>. You can check this yourself by running this snippet in <code>test_ex.py</code>:</p> <pre><code>import sys for line in sys.path: print line </code></pre> <p>If the directory in which <code>main.py</code> is found is <em>not</em> included in your <code>path</code>, you can append that path to <code>sys.path</code>, like this (include this snippet in <code>test_ex.py</code>):</p> <pre><code>import sys sys.path.append("/path/to/your/module/backendapi/api/") </code></pre>
1
2016-10-02T03:40:25Z
[ "python", "import" ]
(Python) Help in modfiying a string from the clipboard
39,813,636
<p>Basically I'm copying a bunch of lists from <a href="https://en.wikipedia.org/wiki/List_of_lists_of_lists" rel="nofollow">https://en.wikipedia.org/wiki/List_of_lists_of_lists</a> into my clipboard. When I run my program, it will add bullets after and before each line.</p> <p>For example: </p> <pre><code>Lists of Iranian films </code></pre> <p>Would convert into:</p> <pre><code>•• Lists of Iranian films •• </code></pre> <p>And so forth. The program works when I add bullets before the line but when I put them after it it just prints one long string without any newline characters. Can anyone tell me what am I doing wrong?</p> <p>Here's the code:</p> <pre><code>#bulletPointAdder.py - Adds Wikipedia bullet points to the start and end #of each line of text on the clipboard import pyperclip text=pyperclip.paste() #paste a big string of text from clipboard into the 'text' string # Separate lines and add stars lines = text.split('\n') #'lines' contains a list of all the individual lines up until '\n' #lines= ['list of iserael films', 'list of italian films' ...] for i in range(len(lines)): #loop through all indexes in the "lines" list lines[i] = '••' + lines[i] + '••' #add bullets before and after each line text = '\n'.join(lines) #put a '\n' in between the list members (joins them) into a single string pyperclip.copy(text) </code></pre> <p>In my clipboard:</p> <pre><code>List of Israeli films before 1960 List of Israeli films of the 1960s List of Israeli films of the 1970s List of Israeli films of the 1980s </code></pre> <p>Clipboard pasted in Notepad:</p> <pre><code>••List of Israeli films before 1960••••List of Israeli films of the 1960s••••List of Israeli films of the 1970s••••List of Israeli films of the 1980s•• </code></pre>
0
2016-10-02T03:40:16Z
39,813,668
<p>Make a small change to your code (use <a href="https://docs.python.org/2/library/os.html#os.linesep" rel="nofollow">os.linesep</a> instead of <code>'\n'</code>):</p> <pre><code>import os import pyperclip text=pyperclip.paste() #paste will paste a big string of text in 'text' string # Separate lines and add stars lines = text.split(os.linesep) #lines contains a list of all the individual lines up cut before newline #lines= ['list of iserael films', 'list of italian films' ...] for i in range(len(lines)): #loop through all indexes in the "lines" list lines[i] = '••' + lines[i] + '••' #add bullets before and after each line text = os.linesep.join(lines) #put a newline in between the list members (joins them) into a single string pyperclip.copy(text) </code></pre> <p>Generally, a "new line" refers to any set of characters that is commonly interpreted as signaling a new line, which can include:</p> <ul> <li>CR LF on DOS/Windows</li> <li>CR on older Macs</li> <li>LF on Unix variants, including modern Macs</li> </ul> <p>CR is the Carriage Return ASCII character (Code 0x0D), usually represented as \r. LF is the Line Feed character (Code 0x0A), usually represented as \n.</p> <p>Also, read this: <a href="https://blog.codinghorror.com/the-great-newline-schism/" rel="nofollow">https://blog.codinghorror.com/the-great-newline-schism/</a></p> <p>I just wanted you to write an platform-agnostic solution. Hence <code>os.linesep</code></p>
1
2016-10-02T03:48:59Z
[ "python", "clipboard" ]
Retrieve a value in Json based on a nested value
39,813,641
<p>I would like is to retrieve the vote cast given a specific id, the data (compliments to <a href="https://www.govtrack.us/" rel="nofollow">govtrack.us</a>) is stored in json and I am writing in python and intend to use <a href="https://stedolan.github.io/jq/" rel="nofollow">js</a>.</p> <p>For example the input "Y000062" should yield "Aye"</p> <pre><code>{ "bill": { "congress": 114, "type": "hr" }, "category": "passage", "votes": { "Aye": [ { "display_name": "Abraham", "id": "A000374", }, { "display_name": "Yarmuth", "id": "Y000062", } ], "Nay": [ { "display_name": "Clyburn", "id": "C000537", }, ]}} </code></pre> <p>In terminal a solution is cat /ccc/114/votes/2015/H384/data.json | egrep 'Nay|Not Voting|Present|Yea|Aye|Y000062' | grep -B 1 'Y000062' | head -1 but relaying that into a python subprocess seems like a clunky solution.</p> <p>Noted: In Json {} is an Object, [] is an Array</p>
0
2016-10-02T03:41:31Z
39,813,672
<pre><code>&gt;&gt;&gt; d = { ... "bill": { ... "congress": 114, ... "type": "hr" ... }, ... "category": "passage", ... "votes": { ... "Aye": [ ... { ... "display_name": "Abraham", ... "id": "A000374", ... }, ... { ... "display_name": "Yarmuth", ... "id": "Y000062", ... } ... ], ... "Nay": [ ... { ... "display_name": "Clyburn", ... "id": "C000537", ... }, ... ]}} &gt;&gt;&gt; &gt;&gt;&gt; # store lookup value in variable to more easily change later ... lookup_value = 'Y000062' &gt;&gt;&gt; &gt;&gt;&gt; # you're only concerned with the data in d['votes'] ... for key, value in d['votes'].items(): ... # for each 'display_name' in the each vote type ('Aye' or 'Nay') ... for element in value: ... if element['id'] == lookup_value: ... print(key) ... Aye &gt;&gt;&gt; </code></pre>
0
2016-10-02T03:49:52Z
[ "python", "json", "jq" ]
Retrieve a value in Json based on a nested value
39,813,641
<p>I would like is to retrieve the vote cast given a specific id, the data (compliments to <a href="https://www.govtrack.us/" rel="nofollow">govtrack.us</a>) is stored in json and I am writing in python and intend to use <a href="https://stedolan.github.io/jq/" rel="nofollow">js</a>.</p> <p>For example the input "Y000062" should yield "Aye"</p> <pre><code>{ "bill": { "congress": 114, "type": "hr" }, "category": "passage", "votes": { "Aye": [ { "display_name": "Abraham", "id": "A000374", }, { "display_name": "Yarmuth", "id": "Y000062", } ], "Nay": [ { "display_name": "Clyburn", "id": "C000537", }, ]}} </code></pre> <p>In terminal a solution is cat /ccc/114/votes/2015/H384/data.json | egrep 'Nay|Not Voting|Present|Yea|Aye|Y000062' | grep -B 1 'Y000062' | head -1 but relaying that into a python subprocess seems like a clunky solution.</p> <p>Noted: In Json {} is an Object, [] is an Array</p>
0
2016-10-02T03:41:31Z
39,813,879
<p>Below is the sample function to achieve this:</p> <pre><code>def get_vote_cast_from_id(id): global my_json for name, nested_values in my_json['votes'].items(): if any(nested_value['id'] == id for nested_value in nested_values): return name else: return None get_vote_cast_from_id("A000374") # returns: "Aye" get_vote_cast_from_id("random_id") # returns: None </code></pre> <p>where <code>my_json</code> is global variable storing your <code>JSON</code>object.</p>
0
2016-10-02T04:30:55Z
[ "python", "json", "jq" ]
Retrieve a value in Json based on a nested value
39,813,641
<p>I would like is to retrieve the vote cast given a specific id, the data (compliments to <a href="https://www.govtrack.us/" rel="nofollow">govtrack.us</a>) is stored in json and I am writing in python and intend to use <a href="https://stedolan.github.io/jq/" rel="nofollow">js</a>.</p> <p>For example the input "Y000062" should yield "Aye"</p> <pre><code>{ "bill": { "congress": 114, "type": "hr" }, "category": "passage", "votes": { "Aye": [ { "display_name": "Abraham", "id": "A000374", }, { "display_name": "Yarmuth", "id": "Y000062", } ], "Nay": [ { "display_name": "Clyburn", "id": "C000537", }, ]}} </code></pre> <p>In terminal a solution is cat /ccc/114/votes/2015/H384/data.json | egrep 'Nay|Not Voting|Present|Yea|Aye|Y000062' | grep -B 1 'Y000062' | head -1 but relaying that into a python subprocess seems like a clunky solution.</p> <p>Noted: In Json {} is an Object, [] is an Array</p>
0
2016-10-02T03:41:31Z
39,814,084
<p>Here are three solutions using jq. If an individual is constrained to vote exactly once, then the results should be the same; otherwise, they may differ, e.g if an individual is recorded as voting both Aye and Nay.</p> <p>The first solution assumes that each person votes at most once. If this assumption is satisfied, then it is also the most efficient because it uses <code>any/1</code>, which has "short-circuit" semantics:</p> <pre><code>$ jq --arg id Y000062 '.votes | if any( .Aye[]; select(.id == $id) ) then "Aye" elif any( .Nay[]; select(.id == $id) ) then "Nay" else "none" end' votes.json </code></pre> <p>The next solution reports "Aye" for each occurrence of the individual on the Ayes list, and only proceeds to do likewise for the Nays list if no occurrences on the Ayes list were found:</p> <pre><code>$ jq --arg id Y000062 '.votes | ((.Aye[] | select(.id == $id) | "Aye") // (.Nay[] | select(.id == $id) | "Nay")) ' votes.json </code></pre> <p>The third solution might be appropriate if there are no constraints on how many times an individual can appear on the two lists. It first constructs a stream of [ VOTE, ID ] pairs, and then selects the IDs of interest:</p> <pre><code>$ jq --arg id Y000062 '.votes | ((.Nay[] | ["Nay", .id]), (.Aye[] | ["Aye", .id]))) | select(.[1] == $id) | .[0]' votes.json </code></pre> <p>With the given input (altered slightly to make it valid JSON), the output of all three solutions is:</p> <pre><code>"Aye" </code></pre> <p>(You can use a command-line tool such as <code>hjson</code> to convert the JSON-with-extra-commas to JSON.)</p>
0
2016-10-02T05:15:10Z
[ "python", "json", "jq" ]
How to use a self defined Distance Metric in Sklearn
39,813,669
<p>I have written the code to compute distance between two rows of input matrices and plan on running KNeighborsClassifier on it. How do I use a different distance metric in Sklearn KNeighborsClassifier?</p> <p><em>For example:</em></p> <pre><code>def distanceMetric(a, b): distance = &lt;some distance&gt; return distance </code></pre> <p>Also which Classifiers offer the ability to define a new distance function?</p>
0
2016-10-02T03:49:03Z
39,814,014
<p>Sklearn has a bunch of built in distance metrics. But if you would like to use your own you do the following:</p> <pre><code>NearestNeighbors(metric='pyfunc', func=distanceMetric) </code></pre> <p>Check out the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html" rel="nofollow">distance metric page</a> in sklearn for a full list of options. </p>
1
2016-10-02T04:58:13Z
[ "python", "machine-learning", "scikit-learn", "distance", "knn" ]
Issue with int/input/print in homework
39,813,686
<p>This is a three part question that I am having issues with....</p> <ol> <li><p>My output is not giving me the option to input my integer, it is printing "none" on the following line and skipping the option</p></li> <li><p>Ending the file trigger is not working properly</p></li> <li><p>counting the players that I have recorded data for....I honestly don't know where to start on counting inputs</p></li> </ol> <p>--------------------My Output---------------------- You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: None ------------------My Output END--------------------</p> <h2>My code;</h2> <pre><code>def main(): #introduction to user explaining required information to be entered print("You will be asked to enter players names and scores") print("When you have no more names, enter End") #double blank space print("\n") #defined y/n anotherPlayer = "y" #define file path to save user input usersFile = open('golf.txt', 'w') # while anotherPlayer == "y": playerName = input("Enter Player's Name or End to exit program: ") score = int(input(print("Enter", playerName, "'s golf score: "))) usersFile.write(playerName + "," + str(score) + "\n") anotherPlayer = input("Is there another player? y / End: ") End = usersFile.close() main() </code></pre> <p>-----------------end my code--------------------</p> <p>I need it to say;</p> <p>---------Assignment output Needed-----------------</p> <p>You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: 50</p> <p>Enter Player's Name or End to exit program: End You have written 1 players records to golf.txt</p> <p>---------End assignment output----------------</p>
0
2016-10-02T03:52:38Z
39,813,721
<pre><code>score = int(input(print("Enter", playerName, "'s golf score: "))) </code></pre> <p>Should be changed to </p> <pre><code>score = int(input("Enter {0}'s golf score: ".format(playerName))) </code></pre> <p>for opening and closing a file in python the efficient method is as follows:</p> <pre><code>with open("filename", "w") as userFile: userFile.write(data) </code></pre> <p>using the with open method will close the file for you when the loop is complete. </p>
0
2016-10-02T03:59:36Z
[ "python", "input", "integer" ]
Issue with int/input/print in homework
39,813,686
<p>This is a three part question that I am having issues with....</p> <ol> <li><p>My output is not giving me the option to input my integer, it is printing "none" on the following line and skipping the option</p></li> <li><p>Ending the file trigger is not working properly</p></li> <li><p>counting the players that I have recorded data for....I honestly don't know where to start on counting inputs</p></li> </ol> <p>--------------------My Output---------------------- You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: None ------------------My Output END--------------------</p> <h2>My code;</h2> <pre><code>def main(): #introduction to user explaining required information to be entered print("You will be asked to enter players names and scores") print("When you have no more names, enter End") #double blank space print("\n") #defined y/n anotherPlayer = "y" #define file path to save user input usersFile = open('golf.txt', 'w') # while anotherPlayer == "y": playerName = input("Enter Player's Name or End to exit program: ") score = int(input(print("Enter", playerName, "'s golf score: "))) usersFile.write(playerName + "," + str(score) + "\n") anotherPlayer = input("Is there another player? y / End: ") End = usersFile.close() main() </code></pre> <p>-----------------end my code--------------------</p> <p>I need it to say;</p> <p>---------Assignment output Needed-----------------</p> <p>You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: 50</p> <p>Enter Player's Name or End to exit program: End You have written 1 players records to golf.txt</p> <p>---------End assignment output----------------</p>
0
2016-10-02T03:52:38Z
39,813,738
<p>You don't need to use <code>print</code> here.</p> <pre><code>score = int(input(print("Enter", playerName, "'s golf score: "))) </code></pre> <p>Use this</p> <pre><code>score = int(input("Enter {}'s golf score: ".format(playerName))) </code></pre>
0
2016-10-02T04:03:40Z
[ "python", "input", "integer" ]
Issue with int/input/print in homework
39,813,686
<p>This is a three part question that I am having issues with....</p> <ol> <li><p>My output is not giving me the option to input my integer, it is printing "none" on the following line and skipping the option</p></li> <li><p>Ending the file trigger is not working properly</p></li> <li><p>counting the players that I have recorded data for....I honestly don't know where to start on counting inputs</p></li> </ol> <p>--------------------My Output---------------------- You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: None ------------------My Output END--------------------</p> <h2>My code;</h2> <pre><code>def main(): #introduction to user explaining required information to be entered print("You will be asked to enter players names and scores") print("When you have no more names, enter End") #double blank space print("\n") #defined y/n anotherPlayer = "y" #define file path to save user input usersFile = open('golf.txt', 'w') # while anotherPlayer == "y": playerName = input("Enter Player's Name or End to exit program: ") score = int(input(print("Enter", playerName, "'s golf score: "))) usersFile.write(playerName + "," + str(score) + "\n") anotherPlayer = input("Is there another player? y / End: ") End = usersFile.close() main() </code></pre> <p>-----------------end my code--------------------</p> <p>I need it to say;</p> <p>---------Assignment output Needed-----------------</p> <p>You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: 50</p> <p>Enter Player's Name or End to exit program: End You have written 1 players records to golf.txt</p> <p>---------End assignment output----------------</p>
0
2016-10-02T03:52:38Z
39,813,768
<p>You have a problem in the line </p> <pre><code>score = int(input(print("Enter", playerName, "'s golf score: "))) </code></pre> <p>You cant put a print function inside the input function and you also can not do it like this:</p> <pre><code>score = int(input("Enter", playerName, "'s golf score: ")) </code></pre> <p>Because <code>input</code> does not work the same way <code>print</code> does. You should read about <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">formatting</a> in python and do it like this:</p> <pre><code>score = int(input("Enter {0}'s golf score: ".format(playerName))) </code></pre>
0
2016-10-02T04:09:06Z
[ "python", "input", "integer" ]
Issue with int/input/print in homework
39,813,686
<p>This is a three part question that I am having issues with....</p> <ol> <li><p>My output is not giving me the option to input my integer, it is printing "none" on the following line and skipping the option</p></li> <li><p>Ending the file trigger is not working properly</p></li> <li><p>counting the players that I have recorded data for....I honestly don't know where to start on counting inputs</p></li> </ol> <p>--------------------My Output---------------------- You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: None ------------------My Output END--------------------</p> <h2>My code;</h2> <pre><code>def main(): #introduction to user explaining required information to be entered print("You will be asked to enter players names and scores") print("When you have no more names, enter End") #double blank space print("\n") #defined y/n anotherPlayer = "y" #define file path to save user input usersFile = open('golf.txt', 'w') # while anotherPlayer == "y": playerName = input("Enter Player's Name or End to exit program: ") score = int(input(print("Enter", playerName, "'s golf score: "))) usersFile.write(playerName + "," + str(score) + "\n") anotherPlayer = input("Is there another player? y / End: ") End = usersFile.close() main() </code></pre> <p>-----------------end my code--------------------</p> <p>I need it to say;</p> <p>---------Assignment output Needed-----------------</p> <p>You will be asked to enter players names and scores When you have no more names, enter End</p> <p>Enter Player's Name or End to exit program: Randy Enter Randy 's golf score: 50</p> <p>Enter Player's Name or End to exit program: End You have written 1 players records to golf.txt</p> <p>---------End assignment output----------------</p>
0
2016-10-02T03:52:38Z
39,813,837
<p>Try this:</p> <pre><code>def main(): # introduction to user explaining required information to be entered print("You will be asked to enter players names and scores") print("When you have no more names, enter End") # double blank space print("\n") # defined y/n anotherPlayer = "y" # define file path to save user input usersFile = open('golf.txt', 'w') # while anotherPlayer == "y": playerName = raw_input("Enter Player's Name or End to exit program: ") score=input("Enter "+ str(playerName)+"'s golf score: ") usersFile.write(playerName + "," + str(score) + "\n") anotherPlayer = raw_input("Is there another player? y / End: ") End = usersFile.close() main() </code></pre>
0
2016-10-02T04:21:11Z
[ "python", "input", "integer" ]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 46: ordinal not in range
39,813,725
<p>I know there're many UnicodeDecodeError around, but I can't find anyone explaining my issue.. And this error randomly jumped from an environment that I can't reproduce..</p> <p>What I want is to just to compare two strings byte to byte (I don't want any encoding and decoding).</p> <p>Note that I'm using python2.7 and str1 is from open('..', 'r').read() on linux.</p> <p>Hope for your advices..</p> <pre><code> def diff_str(str1, str2): minlen = min(len(str1), len(str2)) if str1 == str2: return "All %d bytes same" %minlen for diff_pos in xrange(minlen): if str1[diff_pos] != str2[diff_pos]: break k = 100 to_ret = "(%d vs %d) chars\n" % (len(str1), len(str2)) to_ret += "diff starts at %d:\n" % diff_pos # error jumps out at here.. to_ret += str1[diff_pos:diff_pos+k] + "\n" to_ret += str2[diff_pos:diff_pos+k] + "\n" return to_ret </code></pre>
0
2016-10-02T04:00:36Z
39,813,775
<p>Firstly, please paste your string(or file) you want to compare and make the errors.</p> <p>Have a try:</p> <pre><code>for uchar in your_string.decode('utf-8'): # compare chars </code></pre> <p>Do you want a binary comparsion? Then give it a try:</p> <pre><code>oneBuf = bytes(yourfile.read(1024)) </code></pre> <p>Then compare the byte bufs.</p>
0
2016-10-02T04:10:18Z
[ "python" ]
Python: If elif
39,813,733
<p>i am trying to create a function that creates an empty coloured picture given the numbers of tiles from createSquareTile(numTiles, prefix)</p> <pre><code>def createSquareTile(numTiles, prefix): current = 1 if current == 1: numTiles = requestNumber("Please input a positive number") numTilesI = int(numTiles) while (numTilesI &lt; 0): showError("Your input number" + str(numTiles)+ "is not valid. Do it again!") numTiles = requestNumber("Please input a positive number") if (numTilesI &gt; 0): current = current + 1 color = pickAColor() return makeEmptyPicture(numTilesI), numTilesI), color) elif current &gt; 1: previousChoice = requestString("Same size as pervious tile? (Y/N)") while (previous != "N") and (previous != "Y"): showError("Your input character" + previousChoice + "is not valid. Do it again!") previousChoice = requestString("Same size as previous tile? (Y/N)") if (previousChoice == "Y"): color = pickAColor() return makeEmptyPicture(numTilesI, numTilesI, color) current = current + 1 elif (previousChoice == "N"): numTilesN = requestNumber("Please input a positive number") numTIlesNI = int(numTilesN) colorN = pickAColor() return makeEmptyPicture(numTilesNI, numTilesNI, colorN) current = current + 1 </code></pre> <p>According to python, there was a spacing error at</p> <pre><code>elif current &gt; 1: </code></pre> <p>Could somebody please help me what is wrong with my elif statement? Thanks in advance!</p>
-2
2016-10-02T04:01:48Z
39,813,744
<p>Possible reasons:</p> <ul> <li>The line above it has wrong white spaces.</li> <li>You mixed <code>tab</code> with <code>space</code>.</li> <li>You have some hidden characters by accident.</li> </ul> <p>Why not first try to remove the white line above it? If all possibilities won't work, please make a comment.</p>
1
2016-10-02T04:04:15Z
[ "python", "if-statement", "while-loop" ]
Python: If elif
39,813,733
<p>i am trying to create a function that creates an empty coloured picture given the numbers of tiles from createSquareTile(numTiles, prefix)</p> <pre><code>def createSquareTile(numTiles, prefix): current = 1 if current == 1: numTiles = requestNumber("Please input a positive number") numTilesI = int(numTiles) while (numTilesI &lt; 0): showError("Your input number" + str(numTiles)+ "is not valid. Do it again!") numTiles = requestNumber("Please input a positive number") if (numTilesI &gt; 0): current = current + 1 color = pickAColor() return makeEmptyPicture(numTilesI), numTilesI), color) elif current &gt; 1: previousChoice = requestString("Same size as pervious tile? (Y/N)") while (previous != "N") and (previous != "Y"): showError("Your input character" + previousChoice + "is not valid. Do it again!") previousChoice = requestString("Same size as previous tile? (Y/N)") if (previousChoice == "Y"): color = pickAColor() return makeEmptyPicture(numTilesI, numTilesI, color) current = current + 1 elif (previousChoice == "N"): numTilesN = requestNumber("Please input a positive number") numTIlesNI = int(numTilesN) colorN = pickAColor() return makeEmptyPicture(numTilesNI, numTilesNI, colorN) current = current + 1 </code></pre> <p>According to python, there was a spacing error at</p> <pre><code>elif current &gt; 1: </code></pre> <p>Could somebody please help me what is wrong with my elif statement? Thanks in advance!</p>
-2
2016-10-02T04:01:48Z
39,813,902
<p>here is your issue: return makeEmptyPicture(numTilesI), numTilesI), color)</p> <p>you should remove the <code>)</code> from <code>numTilesI), color)</code> and should work because actually your program stops at this line and not moving forward. Performed debug and checks out: </p> <blockquote> <p>Connected to pydev debugger (build 162.1967.10) Process finished with exit code 0</p> </blockquote> <p><strong>correct will be:</strong> makeEmptyPicture(numTilesI), numTilesI, color</p>
0
2016-10-02T04:35:08Z
[ "python", "if-statement", "while-loop" ]
Scrapy .css select element with a specific attribute name and value
39,813,847
<p>How can Scrapy be used to select the text of an element that has a particular attribute name and value?</p> <p>For example,</p> <pre><code>&lt;span property="city"&gt;Montreal&lt;/span&gt; </code></pre> <p>I tried the following but received a <code>None</code></p> <pre><code>response.css('.span[property="city"]::text').extract_first() </code></pre>
0
2016-10-02T04:23:03Z
39,813,871
<p>You are making a small mistake. You need to drop the <code>'.'</code> before <code>'span'</code>:</p> <pre><code>In [6]: response.css('span[property="city"]::text').extract_first() Out[6]: u'Montreal' </code></pre>
2
2016-10-02T04:28:40Z
[ "python", "python-2.7", "scrapy" ]
Function that calculates the percentage in a list
39,813,886
<p>I need to make a function that calculates the lower percentage to a value within a list. For example, there a 70.5% lower than val elements in the list. The code incomplete:</p> <pre><code>from collections import Counter l = [1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 10] p = [(i, Counter(l)[i] / float(len(l)) * 100.0) for i in Counter(l)] l.sort() newList = l[int(len(l) * .70)] print newList, p </code></pre> <p>I have a 70%, but I need make this in function with value, I'm using python 2.7</p>
0
2016-10-02T04:32:31Z
39,814,077
<p>If you need the percentage of items in a list that are less than an input, you could sort the list, get the number of items before the first occurrence of the number, divide it by the total number of items and multiply it by 100. Like so:</p> <pre><code>list = [23, 22, 3, 4, 5, 11, 23, 2, 3, 3, 3, 3, 4] sorted_li = sorted(li) val = int(input()) len(sorted_li[:sorted_li.index(val)]) / float(len(sorted_li)) * 100 </code></pre>
0
2016-10-02T05:13:27Z
[ "python" ]
Python find sum of prime factors without loop
39,813,924
<p>I'm trying to produce the sum of all prime factors of a number without using loop. However if the result of prime_factor(m, k) bigger than 2, when go to main(n) after factor=prime_factor(m, k), factor will be None</p> <pre><code>def prime_factor(m, k): if m%k==0: return k else: prime_factor(m, k+1) def main(n): if n&lt;2: return 0 if n==2: return n else: factor=prime_factor(n, 2) return factor+main(n//factor) </code></pre>
-2
2016-10-02T04:41:14Z
39,813,981
<p>Your <code>prime_factor</code> function is not doing anything with the result of the recursive call. You need to return it:</p> <pre><code>def prime_factor(m, k): if m%k==0: return k else: return prime_factor(m, k+1) # need the return here </code></pre> <p>Also minor optimization but you could adjust your values so you start at 3 and do prime_factor(m, k+2) in the recursive call instead of k+1.</p>
0
2016-10-02T04:52:45Z
[ "python", "recursion", "sieve-of-eratosthenes", "prime-factoring" ]
Detect if characters in string are in list1 or list2
39,813,939
<p>I want to be able to search a string for characters in different lists.</p> <pre><code>For example: list1=['a'] list2=['b'] </code></pre> <p>If a user enters in 'a' for example. Python should print 'list1' and for 'b' list2.</p> <p>Right now i'm trying to use this function to query the list, but I have to query each list in two separate if statements, like this.</p> <pre><code>def char_search(input_str): for char in input_str: if char in list1: print("lower") if char in list2: print("Upper") </code></pre> <p>I want to be able to combine the two if statements, and only print something if both conditions are True.</p> <p><strong>Update</strong> Thanks for the prompt replies, however I need to combine if statements.</p> <p>Example: Only print a response if a string contains characters from both list 1 and 2</p> <p>Input='a' should not work, nor Input='b', but if user enters 'ab', the repsonse should be something like 'both lists have been matched'. Sorry if I didn't make that clear at the start. The above code was only meant to represent the two different if statements.</p>
1
2016-10-02T04:43:34Z
39,813,950
<pre><code>choice = input("choose a letter") if choice in list1: print(list1) elif choice in list2: print(list2) else: print("choice not listed") </code></pre>
0
2016-10-02T04:46:20Z
[ "python", "list", "if-statement" ]
Detect if characters in string are in list1 or list2
39,813,939
<p>I want to be able to search a string for characters in different lists.</p> <pre><code>For example: list1=['a'] list2=['b'] </code></pre> <p>If a user enters in 'a' for example. Python should print 'list1' and for 'b' list2.</p> <p>Right now i'm trying to use this function to query the list, but I have to query each list in two separate if statements, like this.</p> <pre><code>def char_search(input_str): for char in input_str: if char in list1: print("lower") if char in list2: print("Upper") </code></pre> <p>I want to be able to combine the two if statements, and only print something if both conditions are True.</p> <p><strong>Update</strong> Thanks for the prompt replies, however I need to combine if statements.</p> <p>Example: Only print a response if a string contains characters from both list 1 and 2</p> <p>Input='a' should not work, nor Input='b', but if user enters 'ab', the repsonse should be something like 'both lists have been matched'. Sorry if I didn't make that clear at the start. The above code was only meant to represent the two different if statements.</p>
1
2016-10-02T04:43:34Z
39,813,973
<p>Example</p> <pre><code>list_1 = ['a', 'b', 'c'] list_2 = ['d', 'e', 'f'] input = 'b' if input in list_1: print "list1" if input in list_2: print "list2" </code></pre> <p>The output will be "list1"</p>
0
2016-10-02T04:50:54Z
[ "python", "list", "if-statement" ]
Detect if characters in string are in list1 or list2
39,813,939
<p>I want to be able to search a string for characters in different lists.</p> <pre><code>For example: list1=['a'] list2=['b'] </code></pre> <p>If a user enters in 'a' for example. Python should print 'list1' and for 'b' list2.</p> <p>Right now i'm trying to use this function to query the list, but I have to query each list in two separate if statements, like this.</p> <pre><code>def char_search(input_str): for char in input_str: if char in list1: print("lower") if char in list2: print("Upper") </code></pre> <p>I want to be able to combine the two if statements, and only print something if both conditions are True.</p> <p><strong>Update</strong> Thanks for the prompt replies, however I need to combine if statements.</p> <p>Example: Only print a response if a string contains characters from both list 1 and 2</p> <p>Input='a' should not work, nor Input='b', but if user enters 'ab', the repsonse should be something like 'both lists have been matched'. Sorry if I didn't make that clear at the start. The above code was only meant to represent the two different if statements.</p>
1
2016-10-02T04:43:34Z
39,829,719
<pre><code>list1 = ['a'] list2 = ['b'] if (input[0] in list1 or input[1] in list1) and (input[0] in list2 or input[1] in list2): print "Choice listed" </code></pre> <p>This works if you want to check that both characters are in at least one list. For more input characters you can add some simple loop logic</p>
1
2016-10-03T10:42:54Z
[ "python", "list", "if-statement" ]
How to run python script in docker with the script being sent dynamically to docker container?
39,813,992
<p>How to run python script in docker with the script being sent dynamically to docker container ?</p> <p>Also, it should handle multiple simultaneous connections. For example, if two run is executed by two people at once, it should not override the file created by one person by the another. </p>
1
2016-10-02T04:54:39Z
39,814,550
<p>Normally, you <a href="https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-host-file-as-a-data-volume" rel="nofollow">Mount a host file as a data volume</a>, or, in your case, a <a href="https://docs.docker.com/engine/tutorials/dockervolumes/#/mount-a-host-directory-as-a-data-volume" rel="nofollow">host directory</a>.<br> See the <a href="https://hub.docker.com/_/python/" rel="nofollow">python image</a>:</p> <pre><code>docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:3 python your-daemon-or-script.py </code></pre> <p>That way, if a file is created in that mounted folder, it will be created on the host hard-drive, and won't be overridden by another user executing the same script in his/her own container.</p> <hr> <p>For an Ubutu image, you need</p> <ul> <li>an initial copy of the Git repo, cloned as a bare repo (<code>git clone --mirror</code>). </li> <li>an Apache installed, listening for Git request</li> </ul> <p>When you fetch a PR, you can run a new container, and push that PR branch to the container Git repo. A post-receive hook on that container repo can trigger a python script. - then you can</p>
1
2016-10-02T06:45:27Z
[ "python", "docker" ]
How to convert ascii codes to text?
39,814,033
<p>I need to be able to take an input, remove special characters, make all capital letters lowercase, convert to ascii code with an offset of 5 and then convert those now offset values back to characters to form a word. I keep getting TypeError: 'int' object is not iterable at the end </p> <pre><code>string=(str(raw_input("The code is:"))) #change it to lower case string_lowercase=string.lower() print "lower case string is:", string_lowercase #strip special characters specialcharacters="1234567890~`!@#$%^&amp;*()_-+={[}]|\:;'&lt;,&gt;.?/" for char in specialcharacters: string_lowercase=string_lowercase.replace(char,"") print "With the specials stripped out the string is:", string_lowercase #input offset offset=(int(raw_input("enter offset:"))) #converstion of text to ASCII code for i in string_lowercase: code=ord(i) result=code-offset #converstion from ASCII code to text for number in result: message=repre(unichr(number)) print message </code></pre>
0
2016-10-02T05:03:55Z
39,814,173
<p>You are getting <code>TypeError: 'int' object is not iterable at the end</code> because you are declaring <code>result</code> each time over the loop as an int. <code>result</code> should be a list and every code appended to it over the loop, like this:</p> <pre><code>#converstion of text to ASCII code result = [] for i in string_lowercase: code=ord(i) result.append(code-offset) </code></pre>
0
2016-10-02T05:35:55Z
[ "python", "ascii" ]
removing blank lines after text on a file python
39,814,058
<p>I have a python program with generates a file.<br> I want to remove the lines with spaces at the end<br> my program outputs a file like this:</p> <pre><code>&gt; cat output some text some text &gt; </code></pre> <p>The output that I need is:</p> <pre><code>&gt; cat output some text some text &gt; </code></pre> <p>Thanks in advance</p>
-1
2016-10-02T05:10:01Z
39,814,100
<p>How about this?</p> <pre><code>name = "filename" f = open(name, 'r') out = []; for line in f: if line.trim() != "": out.append(line); f.close() f = open(name,'w') for line in out: f.write(line) </code></pre>
0
2016-10-02T05:18:47Z
[ "python", "file" ]
removing blank lines after text on a file python
39,814,058
<p>I have a python program with generates a file.<br> I want to remove the lines with spaces at the end<br> my program outputs a file like this:</p> <pre><code>&gt; cat output some text some text &gt; </code></pre> <p>The output that I need is:</p> <pre><code>&gt; cat output some text some text &gt; </code></pre> <p>Thanks in advance</p>
-1
2016-10-02T05:10:01Z
39,814,149
<p>I believe that underneath your print("") statement there are a few blank lines inserted. Try to check if that is the case, if not just paste your code so I can check it out.</p>
0
2016-10-02T05:28:57Z
[ "python", "file" ]
How to know which ad was clicked and send that data to a singles page
39,814,081
<p>I'm practicing with a flask website that is sort of a mock classifieds website. On a browse page, I am displaying all results for whatever a user searches for. How can I track which ad was clicked by the user so I can redirect them to a 'singles' page where it will show in greater detail the item they clicked on...?</p> <p>My first instinct was to use sessions, but I just couldn't quite figure out the logic. I am rendering the data dynamically, where in the HTML template, data contains all the query results:</p> <pre><code>&lt;ul class="list"&gt; {% for row in data %} &lt;a href="/iLike/"&gt; &lt;li&gt; &lt;img src="{{ url_for('static', filename='images/logo.png') }}" title="" alt=""/&gt; &lt;section class="list-left"&gt; &lt;h5 class="title"&gt;{{ row[1] }}&lt;/h5&gt; &lt;p class="catpath"&gt; &lt;Strong&gt;Condition&lt;/strong&gt;: {{ row[3] }}&lt;/p&gt; &lt;p class="catpath"&gt;&lt;Strong&gt;details&lt;/strong&gt;: {{ row[2] }}&lt;/p&gt; &lt;p class="catpath"&gt;&lt;strong&gt;Looking for&lt;/strong&gt;: {{ row[5] }}&lt;/p&gt; &lt;/section&gt; &lt;section class="list-right"&gt; &lt;span class="date"&gt;{{ transType }}&lt;/span&gt; &lt;/section&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;/li&gt; &lt;/a&gt; </code></pre>
0
2016-10-02T05:14:24Z
39,814,888
<p>Add some argument to link - ie <code>href="/iLike/?ad_number=1"</code> or <code>href="/iLike/1"</code> (second version needs argument in route/function)</p>
1
2016-10-02T07:38:52Z
[ "python", "flask", "e-commerce" ]
Web Scraping not working?
39,814,107
<p>So i was looking for the best thing i like about software . Then i found out about web scraping I found it really amazing so with my python experience i got some hands-on at some Beautiful soup and requests and here's the Code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import html5lib import requests from bs4 import BeautifulSoup as BS # Get all the a strings , next siblings and next siblings def makeSoup(urls): url = requests.get(urls).text return BS(url,"html5lib") def something(soup): for anchor in soup.findAll("a",{"data-type":"externalLink"}): print(anchor.string) next_sibling = anchor.nextSibling water = str(next_sibling.string) water = water[0:5] while water != "(202)": next_sibling = next_sibling.nextSibling if next_sibling == None: continue if next_sibling.string != None: print(next_sibling.string) water = str(next_sibling.string) water = water[0:5] soup = makeSoup("http://dc.about.com/od/communities/a/EmbassyGuide.htm") something(soup) soup = makeSoup("http://dc.about.com/od/communities/a/EmbassyGuide_2.htm") something(soup) soup = makeSoup("http://dc.about.com/od/communities/a/EmbassyGuide_3.htm") something(soup) &lt;!-- begin snippet: js hide: false console: true babel: false --&gt;</code></pre> </div> </div> </p> <p>But sadly all programmers nightmare ERRORS . <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Traceback (most recent call last): File "C:\Users\Raj\Desktop\kunal projects\Python\listing_out_all_embassies.py", line 26, in &lt;module&gt; something(soup) File "C:\Users\Raj\Desktop\kunal projects\Python\listing_out_all_embassies.py", line 17, in something next_sibling = next_sibling.nextSibling AttributeError: 'NoneType' object has no attribute 'nextSibling'</code></pre> </div> </div> </p> <p>What wrong am i doing and i am a newbie to programming as well as web-scraping . So what are some Good practices that i am not following Anyway.thanks for reading till the end.</p>
0
2016-10-02T05:20:20Z
39,814,807
<p>You have to check <code>next_sibling == None</code> before you can use <code>next_sibling.nextSibling</code> (and <code>break</code> when it is <code>None</code>)</p> <pre><code>def something(soup): for anchor in soup.findAll("a",{"data-type":"externalLink"}): print(anchor.string) next_sibling = anchor.nextSibling water = str(next_sibling.string) water = water[0:5] while water != "(202)": if next_sibling == None: break next_sibling = next_sibling.nextSibling if next_sibling == None: break if next_sibling.string != None: print(next_sibling.string) water = str(next_sibling.string) water = water[0:5] </code></pre> <p>But I could write it shorter</p> <pre><code>def something(soup): for anchor in soup.findAll("a",{"data-type":"externalLink"}): water = None # create variable to use it first time in "while" while anchor and water != "(202)": if anchor.string: print(anchor.string) water = anchor.string[:5] anchor = anchor.nextSibling </code></pre>
0
2016-10-02T07:28:03Z
[ "python", "web" ]
substring matching / list comparision in python
39,814,174
<p>I have two different lists and I need to find the index number of the list have more similar pattern for example</p> <pre><code>list_1=['abdsc 23h', 'nis 4hd qad', '234 apple 54f','abdsc 2300h'] list_2=['abdsc 23', 'abdsc 230'] </code></pre> <p>a comparison is to be done for both the list, if element of <code>list_2</code> matches with <code>list_1</code> then it should return the index of list_1 where that element is present 1. note: for 2nd element of <code>list_2</code> that is <code>abdsc 230</code> it must return 4 since it has highest match with 4th element of <code>list_1</code></p> <h1>here is the code I am trying to solve</h1> <pre><code>from bs4 import BeautifulSoup import urllib import pandas as pd from difflib import SequenceMatcher as SM def maxmatching_algo2(data, counter): data_word=[] data_word=str(data).split(" ") k=[] for i in processsorList_global: k+=str(i).split(",") temp=0 rank_list=[] while temp&lt;len(k): t=[] t+=str(k[temp]).split(" ") union_set=set(t)&amp;set(data_word) rank_list+= [len(union_set)] temp+=1 index= rank_list.index(max(rank_list)) if index==0: df1.ix[counter, cl]="na" else: df1.ix[counter, cl]=index def processor_list_online(): processsorList = [] url = "http://www.notebookcheck.net/Smartphone-Processors-Benchmark-List.149513.0.html" htmlfile = urllib.urlopen(url) soup = BeautifulSoup(htmlfile, 'html.parser') count = 1 temp_count=0 x=str() while True: if x=="Qualcomm Snapdragon S1 MSM7227": break else: for i in soup.find_all('tr'): count+=1 temp=0 for j in i.find_all('td', attrs={'class': 'specs'}): if temp==1: processsorList += [j.text] x=j.text temp+=1 temp_count+=1 print temp_count return processsorList ############################################################################################################################### ############################################################################################################################### df1 = pd.read_csv('proddata2.csv') x = list(df1.columns.values) ####################### name of column cl = len(x) ####################### column Length rl = len(df1.index) ####################### row length df1["Processor Rank"] = "" counter = 0 count = [] processsorList_global = processor_list_online() for i in processsorList_global: print i counter=0 while counter &lt; cl: if x[counter] == "processor_type": count = counter break counter += 1 counter = 0 data = [] while counter &lt; rl: data = df1.ix[counter, count] #print data if data=="na": df1.ix[counter, cl]="na" else: # maxmatching_algo(data, counter) maxmatching_algo2(data, counter) counter +=1 #print df1 #df1.to_csv('final_processor_rank.csv', sep=',') print "process completed" </code></pre>
0
2016-10-02T05:36:20Z
39,814,311
<p>You would have to do something like this: </p> <pre><code>def compare_substrings_in_list(first_list, compared_list): for element in first_list: last_match = 0 for idx, compared_list_element in enumerate(compared_list): if element in compared_list_element: last_match = idx + 1 return last_match </code></pre> <p>Where you iterate over each element of the list of "searches" and try to find matches on each element of the second list using the <a href="https://docs.python.org/3/reference/expressions.html#membership-test-details" rel="nofollow">in operator</a>.</p>
0
2016-10-02T06:03:09Z
[ "python", "string", "list", "python-2.7" ]
substring matching / list comparision in python
39,814,174
<p>I have two different lists and I need to find the index number of the list have more similar pattern for example</p> <pre><code>list_1=['abdsc 23h', 'nis 4hd qad', '234 apple 54f','abdsc 2300h'] list_2=['abdsc 23', 'abdsc 230'] </code></pre> <p>a comparison is to be done for both the list, if element of <code>list_2</code> matches with <code>list_1</code> then it should return the index of list_1 where that element is present 1. note: for 2nd element of <code>list_2</code> that is <code>abdsc 230</code> it must return 4 since it has highest match with 4th element of <code>list_1</code></p> <h1>here is the code I am trying to solve</h1> <pre><code>from bs4 import BeautifulSoup import urllib import pandas as pd from difflib import SequenceMatcher as SM def maxmatching_algo2(data, counter): data_word=[] data_word=str(data).split(" ") k=[] for i in processsorList_global: k+=str(i).split(",") temp=0 rank_list=[] while temp&lt;len(k): t=[] t+=str(k[temp]).split(" ") union_set=set(t)&amp;set(data_word) rank_list+= [len(union_set)] temp+=1 index= rank_list.index(max(rank_list)) if index==0: df1.ix[counter, cl]="na" else: df1.ix[counter, cl]=index def processor_list_online(): processsorList = [] url = "http://www.notebookcheck.net/Smartphone-Processors-Benchmark-List.149513.0.html" htmlfile = urllib.urlopen(url) soup = BeautifulSoup(htmlfile, 'html.parser') count = 1 temp_count=0 x=str() while True: if x=="Qualcomm Snapdragon S1 MSM7227": break else: for i in soup.find_all('tr'): count+=1 temp=0 for j in i.find_all('td', attrs={'class': 'specs'}): if temp==1: processsorList += [j.text] x=j.text temp+=1 temp_count+=1 print temp_count return processsorList ############################################################################################################################### ############################################################################################################################### df1 = pd.read_csv('proddata2.csv') x = list(df1.columns.values) ####################### name of column cl = len(x) ####################### column Length rl = len(df1.index) ####################### row length df1["Processor Rank"] = "" counter = 0 count = [] processsorList_global = processor_list_online() for i in processsorList_global: print i counter=0 while counter &lt; cl: if x[counter] == "processor_type": count = counter break counter += 1 counter = 0 data = [] while counter &lt; rl: data = df1.ix[counter, count] #print data if data=="na": df1.ix[counter, cl]="na" else: # maxmatching_algo(data, counter) maxmatching_algo2(data, counter) counter +=1 #print df1 #df1.to_csv('final_processor_rank.csv', sep=',') print "process completed" </code></pre>
0
2016-10-02T05:36:20Z
39,814,327
<p>The below solution might work for you. </p> <pre><code>&gt;&gt;&gt; for i,val in enumerate(sorted(list_2, key= len, reverse = True)): ... for j,val2 in enumerate(list_1): ... if val in val2: ... print j+1 ... exit() ... 4 </code></pre> <p>Note that, if you have multiple matches, this solution is't enough. But that entirely depend on your use cases. </p> <p>For now, this should be okay. </p>
0
2016-10-02T06:06:01Z
[ "python", "string", "list", "python-2.7" ]
substring matching / list comparision in python
39,814,174
<p>I have two different lists and I need to find the index number of the list have more similar pattern for example</p> <pre><code>list_1=['abdsc 23h', 'nis 4hd qad', '234 apple 54f','abdsc 2300h'] list_2=['abdsc 23', 'abdsc 230'] </code></pre> <p>a comparison is to be done for both the list, if element of <code>list_2</code> matches with <code>list_1</code> then it should return the index of list_1 where that element is present 1. note: for 2nd element of <code>list_2</code> that is <code>abdsc 230</code> it must return 4 since it has highest match with 4th element of <code>list_1</code></p> <h1>here is the code I am trying to solve</h1> <pre><code>from bs4 import BeautifulSoup import urllib import pandas as pd from difflib import SequenceMatcher as SM def maxmatching_algo2(data, counter): data_word=[] data_word=str(data).split(" ") k=[] for i in processsorList_global: k+=str(i).split(",") temp=0 rank_list=[] while temp&lt;len(k): t=[] t+=str(k[temp]).split(" ") union_set=set(t)&amp;set(data_word) rank_list+= [len(union_set)] temp+=1 index= rank_list.index(max(rank_list)) if index==0: df1.ix[counter, cl]="na" else: df1.ix[counter, cl]=index def processor_list_online(): processsorList = [] url = "http://www.notebookcheck.net/Smartphone-Processors-Benchmark-List.149513.0.html" htmlfile = urllib.urlopen(url) soup = BeautifulSoup(htmlfile, 'html.parser') count = 1 temp_count=0 x=str() while True: if x=="Qualcomm Snapdragon S1 MSM7227": break else: for i in soup.find_all('tr'): count+=1 temp=0 for j in i.find_all('td', attrs={'class': 'specs'}): if temp==1: processsorList += [j.text] x=j.text temp+=1 temp_count+=1 print temp_count return processsorList ############################################################################################################################### ############################################################################################################################### df1 = pd.read_csv('proddata2.csv') x = list(df1.columns.values) ####################### name of column cl = len(x) ####################### column Length rl = len(df1.index) ####################### row length df1["Processor Rank"] = "" counter = 0 count = [] processsorList_global = processor_list_online() for i in processsorList_global: print i counter=0 while counter &lt; cl: if x[counter] == "processor_type": count = counter break counter += 1 counter = 0 data = [] while counter &lt; rl: data = df1.ix[counter, count] #print data if data=="na": df1.ix[counter, cl]="na" else: # maxmatching_algo(data, counter) maxmatching_algo2(data, counter) counter +=1 #print df1 #df1.to_csv('final_processor_rank.csv', sep=',') print "process completed" </code></pre>
0
2016-10-02T05:36:20Z
39,814,503
<p>This solves your problem,</p> <pre><code>list_1=['abdsc 23h', 'nis 4hd qad', '234 apple 54f','abdsc 2300h'] list_2=['abdsc 23', 'abdsc 230'] for strings in list_2: print "-list1val--",strings for other in list_1: print '--list2val---',other occurence = other.find(strings); if occurence==0: ind = list_1.index(other) print "the index of ",strings,"in list_1 is ",ind break </code></pre>
0
2016-10-02T06:36:10Z
[ "python", "string", "list", "python-2.7" ]
substring matching / list comparision in python
39,814,174
<p>I have two different lists and I need to find the index number of the list have more similar pattern for example</p> <pre><code>list_1=['abdsc 23h', 'nis 4hd qad', '234 apple 54f','abdsc 2300h'] list_2=['abdsc 23', 'abdsc 230'] </code></pre> <p>a comparison is to be done for both the list, if element of <code>list_2</code> matches with <code>list_1</code> then it should return the index of list_1 where that element is present 1. note: for 2nd element of <code>list_2</code> that is <code>abdsc 230</code> it must return 4 since it has highest match with 4th element of <code>list_1</code></p> <h1>here is the code I am trying to solve</h1> <pre><code>from bs4 import BeautifulSoup import urllib import pandas as pd from difflib import SequenceMatcher as SM def maxmatching_algo2(data, counter): data_word=[] data_word=str(data).split(" ") k=[] for i in processsorList_global: k+=str(i).split(",") temp=0 rank_list=[] while temp&lt;len(k): t=[] t+=str(k[temp]).split(" ") union_set=set(t)&amp;set(data_word) rank_list+= [len(union_set)] temp+=1 index= rank_list.index(max(rank_list)) if index==0: df1.ix[counter, cl]="na" else: df1.ix[counter, cl]=index def processor_list_online(): processsorList = [] url = "http://www.notebookcheck.net/Smartphone-Processors-Benchmark-List.149513.0.html" htmlfile = urllib.urlopen(url) soup = BeautifulSoup(htmlfile, 'html.parser') count = 1 temp_count=0 x=str() while True: if x=="Qualcomm Snapdragon S1 MSM7227": break else: for i in soup.find_all('tr'): count+=1 temp=0 for j in i.find_all('td', attrs={'class': 'specs'}): if temp==1: processsorList += [j.text] x=j.text temp+=1 temp_count+=1 print temp_count return processsorList ############################################################################################################################### ############################################################################################################################### df1 = pd.read_csv('proddata2.csv') x = list(df1.columns.values) ####################### name of column cl = len(x) ####################### column Length rl = len(df1.index) ####################### row length df1["Processor Rank"] = "" counter = 0 count = [] processsorList_global = processor_list_online() for i in processsorList_global: print i counter=0 while counter &lt; cl: if x[counter] == "processor_type": count = counter break counter += 1 counter = 0 data = [] while counter &lt; rl: data = df1.ix[counter, count] #print data if data=="na": df1.ix[counter, cl]="na" else: # maxmatching_algo(data, counter) maxmatching_algo2(data, counter) counter +=1 #print df1 #df1.to_csv('final_processor_rank.csv', sep=',') print "process completed" </code></pre>
0
2016-10-02T05:36:20Z
39,814,659
<p>One approach is to create a function to return position of the sub_string from <code>list_1</code>. And, then call the function on every element of <code>list_2</code> using <code>map()</code></p> <pre><code>list_1=['abdsc 23h', 'nis 4hd qad', '234 apple 54f','abdsc 2300h'] list_2=['abdsc 23', 'abdsc 230'] def get_position_from_list(item, l): for i, val in enumerate(l): if item in val: return i + 1 else: return None map(lambda x: get_position_from_list(x, list_1), list_2) # returns: [1, 4] </code></pre>
0
2016-10-02T07:04:34Z
[ "python", "string", "list", "python-2.7" ]
Can't Find or create a new virtualenv
39,814,281
<p>I just got Python 3.5.2 and wanted to create a virtualenv.</p> <p>I have done this before. Right now, I have a virtualenv on a Python2.7 project that I can still open with source bin/activate. </p> <p>But try as I might, from /home, or from /path/to/virtualenv, or /path/to/virtualenv-$, with or without sudo and python prepended on the command line, I only get one response: no such file or directory.</p> <p>This was with the -p flag so it would use 3.5.2, because 2.7.12 is still my default. If it is broken, why does the virtualenv I created for 2.7 still activate?</p> <p>Then I tried pyvenv and venv (which I've never used before) from the 3.5.2 interpreter:</p> <pre><code>&gt;&gt;&gt; pyvenv /home/malikarumi/Projects/aishah Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'pyvenv' is not defined &gt;&gt;&gt; venv /home/malikarumi/Projects/aishah Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'venv' is not defined </code></pre> <p>and from bash:</p> <pre><code>malikarumi@Tetuoan2:~$ malikarumi@Tetuoan2:/usr/local/bin$ python3.5 pyvenv ~/Projects/aishah bash: malikarumi@Tetuoan2:/usr/local/bin$: No such file or directory malikarumi@Tetuoan2:~$ malikarumi@Tetuoan2:/usr/local/bin$ python3.5 venv ~/Projects/aishah bash: malikarumi@Tetuoan2:/usr/local/bin$: No such file or directory </code></pre> <p>What am I doing wrong?</p>
0
2016-10-02T05:57:22Z
39,816,175
<h1>Using virtualenv</h1> <p>First of all you should verify that virtualenv is really installed for Python 3.5:</p> <p><code>python3.5 -m pip list</code></p> <p>If it's not then install it either with the package manager of your distribution or by running <code>python3.5 -m pip install virtualenv</code>.</p> <p>Then you can run <code>python3.5 -m virtualenv &lt;newvenv&gt;</code> and it should create a new virtualenv using Python 3.5 for you.</p> <h1>Using venv that is already part of the standard library in Python 3.5</h1> <p>Simply running <code>python3.5 -m venv &lt;newvenv&gt;</code> should do the job.</p>
1
2016-10-02T10:43:00Z
[ "python", "bash", "virtualenv", "python-venv" ]
PyQt5: get index of cell widgets and their chosen values
39,814,304
<p>I am using Python 3.5, and I have a simple code which creates a table with a few combo-boxes inside of it. Here is the code:</p> <pre><code>from PyQt5 import QtCore from PyQt5 import QtWidgets import sys app = QtWidgets.QApplication(sys.argv) ########################## Create table ############################## tableWidget = QtWidgets.QTableWidget() tableWidget.setGeometry(QtCore.QRect(200, 200, 250, 300)) tableWidget.setColumnCount(2) tableWidget.setRowCount(9) tableWidget.show() ################# Create tablecontent &amp; comboboxes ################### names = ['Name 1', 'Name 2', 'Name 3', 'Name 4'] i = 0 for j in names: tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(j)) comboBox = QtWidgets.QComboBox() combo_option_list = ["Choose...", "Option 1", "Option 2", "Option 3", "Option 4"] for t in combo_option_list: comboBox.addItem(t) tableWidget.setCellWidget(i, 1, comboBox) i += 1 sys.exit(app.exec_()) </code></pre> <p>I want to work with these combo-boxes, but I have several problems. It already starts with the fact that I can only use the last created combo-box with the following command:</p> <pre><code>comboBox.activated[str].connect(do_something) </code></pre> <p>I need to know the following things:</p> <ul> <li>How to connect signals for all the combo-boxes?</li> <li>How to get the index of the selected combo-box?</li> <li>How to get the index of the selected combo-box option after it was chosen?</li> </ul>
1
2016-10-02T06:01:37Z
39,821,284
<p>Description below code</p> <pre><code>from PyQt5 import QtCore from PyQt5 import QtWidgets import sys app = QtWidgets.QApplication(sys.argv) ########################## Create table ############################## tableWidget = QtWidgets.QTableWidget() tableWidget.setGeometry(QtCore.QRect(200, 200, 250, 300)) tableWidget.setColumnCount(2) tableWidget.setRowCount(9) tableWidget.show() ################# Create tablecontent &amp; comboboxes ################### def dosomething(index): widget = app.sender() print('widget object:', widget) print('widget myname:', widget.my_name) print('widget index:', combo_list.index(widget)) print('option index:', index) #--------------------------------------------------------------------- names = ['Name 1', 'Name 2', 'Name 3', 'Name 4'] combo_option_list = ["Choose...", "Option 1", "Option 2", "Option 3", "Option 4"] combo_list = [] for i, name in enumerate(names): tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(name)) combobox = QtWidgets.QComboBox() combobox.addItems(combo_option_list) combobox.my_name = name + ' (i=' + str(i) + ')' combobox.currentIndexChanged.connect(dosomething) combo_list.append(combobox) tableWidget.setCellWidget(i, 1, combobox) #--------------------------------------------------------------------- sys.exit(app.exec_()) </code></pre> <p>Inside <code>dosomething</code> you can use <code>app.sender()</code> to get widget which was clicked - and then you can use it to do something with this widget.</p> <p>PyQt executes <code>dosomething</code> with argument - it is index of selected option in combobox.</p> <p>To get index of <code>widget</code> in <code>combo_list</code> you can use standard list method <code>combo_list.index(widget)</code></p> <p>But you can also create own variable in combobox (ie. <code>my_name</code>) to keep index or other value</p> <pre><code>combobox.my_name = some_value </code></pre> <p>and later you can get in <code>dosomething</code></p> <pre><code>value = widget.my_name </code></pre> <hr> <p>BTW: </p> <p>instead of <code>addItem(one_option)</code> and <code>for</code> loop you can use <code>addItems(option_list)</code> </p> <p>You can use <code>enumerate(names)</code> and you will not need <code>i = 0</code> and <code>i += 1</code></p> <pre><code>for i, j in enumerate(names): </code></pre> <p>You can create <code>combo_option_list</code> before <code>for</code> loop.</p>
1
2016-10-02T20:19:35Z
[ "python", "pyqt", "signals-slots", "qtablewidget", "qcombobox" ]
PyQt5: get index of cell widgets and their chosen values
39,814,304
<p>I am using Python 3.5, and I have a simple code which creates a table with a few combo-boxes inside of it. Here is the code:</p> <pre><code>from PyQt5 import QtCore from PyQt5 import QtWidgets import sys app = QtWidgets.QApplication(sys.argv) ########################## Create table ############################## tableWidget = QtWidgets.QTableWidget() tableWidget.setGeometry(QtCore.QRect(200, 200, 250, 300)) tableWidget.setColumnCount(2) tableWidget.setRowCount(9) tableWidget.show() ################# Create tablecontent &amp; comboboxes ################### names = ['Name 1', 'Name 2', 'Name 3', 'Name 4'] i = 0 for j in names: tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(j)) comboBox = QtWidgets.QComboBox() combo_option_list = ["Choose...", "Option 1", "Option 2", "Option 3", "Option 4"] for t in combo_option_list: comboBox.addItem(t) tableWidget.setCellWidget(i, 1, comboBox) i += 1 sys.exit(app.exec_()) </code></pre> <p>I want to work with these combo-boxes, but I have several problems. It already starts with the fact that I can only use the last created combo-box with the following command:</p> <pre><code>comboBox.activated[str].connect(do_something) </code></pre> <p>I need to know the following things:</p> <ul> <li>How to connect signals for all the combo-boxes?</li> <li>How to get the index of the selected combo-box?</li> <li>How to get the index of the selected combo-box option after it was chosen?</li> </ul>
1
2016-10-02T06:01:37Z
39,837,123
<p>The tricky part here is getting the index of the combo-box within the table, because a cell-widget cannot know its own index. One way to solve this is to use the <code>indexAt()</code> method of the table, which can get an index from a <code>QPoint</code>. A cell-widget <em>does</em> know its own position relative to its parent, so this can be passed to <code>indexAt()</code> to get its index within the table.</p> <p>Below is a simple demo that shows how to connect up the signals and get all the information that you want:</p> <pre><code>from PyQt5 import QtCore, QtWidgets class Window(QtWidgets.QWidget): def __init__(self): super(Window, self).__init__() self.table = QtWidgets.QTableWidget(9, 2, self) layout = QtWidgets.QVBoxLayout(self) layout.addWidget(self.table) names = ['Name 1', 'Name 2', 'Name 3', 'Name 4'] options = ["Choose...", "Option 1", "Option 2", "Option 3", "Option 4"] for index, name in enumerate(names): self.table.setItem(index, 0, QtWidgets.QTableWidgetItem(name)) comboBox = QtWidgets.QComboBox() comboBox.activated.connect(self.comboActivated) comboBox.addItems(options) self.table.setCellWidget(index, 1, comboBox) def comboActivated(self, option): combo = self.sender() print('option: %s, "%s"' % (option, combo.itemText(option))) index = self.table.indexAt(combo.pos()) print('row: %s, column: %s' % (index.row(), index.column())) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) window = Window() window.setGeometry(600, 200, 300, 300) window.show() sys.exit(app.exec_()) </code></pre>
0
2016-10-03T17:26:18Z
[ "python", "pyqt", "signals-slots", "qtablewidget", "qcombobox" ]
recursion Think Python 2 exercise 5.5
39,814,341
<p>This question regarding exercise 5.5 from Think Python 2 has been <a href="https://stackoverflow.com/questions/21048933/understanding-recursion-in-python-2-think-python-exercise-5">asked and answered already</a>, but I still don't understand how this function works. Here's the function in question:</p> <pre><code>def draw(t, length, n): if n == 0: return angle = 50 t.fd(length*n) t.lt(angle) draw(t, length, n-1) t.rt(2*angle) draw(t, length, n-1) t.lt(angle) t.bk(length*n) </code></pre> <p>I see a recursive loop here:</p> <pre><code>def draw(t, length, n): if n == 0: return angle = 50 t.fd(length*n) t.lt(angle) draw(t, length, n-1) </code></pre> <p>After the function calls itself a sufficient number of times to cause n == 0, how does it move on to the next step, namely t.rt(2*angle)? Once n == 0, shouldn't the function return None and simply end? If not, where is returning to? The same thing happens again the next time it calls itself, and then the function continues to perform work long after the state n == 0 has been satisfied (twice!). I'm obviously missing a key concept here and would appreciate any light anyone can shed on this topic. Thanks in advance~</p>
1
2016-10-02T06:07:51Z
39,814,559
<p>The return statement returns execution of the program back to the line where the function that returned was called.</p> <p>If you're not familiar with what a call stack is, think of it as a stack of functions - whenever something gets called, it's placed on top of the stack and that's what's running. When that returns, it's removed from the stack and so the function that called it (one below in the stack) is now the top, so that's where execution picks up again.</p> <p>That particular function will return when n == 0 (so that's your base case), so once its recursive call <code>draw(t, length, n-1)</code> - and, by consequence, its subsequent recursive calls, since it won't finish execution until they do - reach that point, it'll move over to the next line.</p> <p>Take a simpler function <code>foo(sum, n)</code> instead:</p> <pre><code>def foo(sum, n): if (n == 0): return sum sum += foo(sum, n-1) sum /= 2 return foo(sum, n-1) </code></pre> <p>Whenever you call that, it won't move from <code>sum += foo(sum, n-1)</code> until that call and all of the recursive calls made return. This function is structurally comparable to the one you showed and it might help you visualize a little better what's going on.</p>
1
2016-10-02T06:46:14Z
[ "python", "python-3.x", "recursion" ]