title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
How to manage different labels in a bar chart, taking data from a text file? | 40,002,896 | <p>I'm new in using matplotlib, so I'm having some problems. I must create a bar chart with different labels, for each website that I have.
The file is like the following:</p>
<pre><code>1001 adblock 12
1001 badger 11
1001 disconnect 15
1001 ghostery 15
1001 nottrack 14
1001 origin 15
1001 policy 16
1001 ultimate 14
4ruote adblock 12
4ruote badger 1
4ruote disconnect 14
4ruote ghostery 27
4ruote nottrack 9
4ruote origin 26
4ruote policy 34
4ruote ultimate 20
...... ........ ...
</code></pre>
<p>My goal is to create a bar chart in which I have:</p>
<ol>
<li><p>on the x axis sites (first column of the file), is a string</p></li>
<li><p>on the y axis the values (third column of the file) for that site (that are 8 times repeated inside the file), so 8 integer values</p></li>
<li><p>labels that, for a specific site, are present in the second column (strings).</p></li>
</ol>
<p>I read different answers but each one didn't threat this comparison between labels, for a same variable.
What I'm doing is read the file, splitting the row and taking the first and third column, but how can I manage the labels?</p>
| 0 | 2016-10-12T15:46:36Z | 40,003,947 | <p>Let's assume that you have read the websites into 8 different datasets (adblock, badger, disconnect, etc). You can then use the logic below to plot each series and show their labels on a legend. </p>
<pre><code>import numpy
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
#this is your number of datasets
x = numpy.arange(8)
width = 0.1
#plot each dataset here, offset by the width of the preceding bars
b1 = ax.bar(x, adblock, width, color='r')
b2 = ax.bar(x + width, badger, color='g')
b3 = ax.bar(x + width*2, disconnect, color='m')
legend([b1[0], b2[0], b3[0]], ['adblock', 'badger',
'disconnect'])
plt.show()
</code></pre>
| 0 | 2016-10-12T16:41:29Z | [
"python",
"matplotlib"
] |
How to manage different labels in a bar chart, taking data from a text file? | 40,002,896 | <p>I'm new in using matplotlib, so I'm having some problems. I must create a bar chart with different labels, for each website that I have.
The file is like the following:</p>
<pre><code>1001 adblock 12
1001 badger 11
1001 disconnect 15
1001 ghostery 15
1001 nottrack 14
1001 origin 15
1001 policy 16
1001 ultimate 14
4ruote adblock 12
4ruote badger 1
4ruote disconnect 14
4ruote ghostery 27
4ruote nottrack 9
4ruote origin 26
4ruote policy 34
4ruote ultimate 20
...... ........ ...
</code></pre>
<p>My goal is to create a bar chart in which I have:</p>
<ol>
<li><p>on the x axis sites (first column of the file), is a string</p></li>
<li><p>on the y axis the values (third column of the file) for that site (that are 8 times repeated inside the file), so 8 integer values</p></li>
<li><p>labels that, for a specific site, are present in the second column (strings).</p></li>
</ol>
<p>I read different answers but each one didn't threat this comparison between labels, for a same variable.
What I'm doing is read the file, splitting the row and taking the first and third column, but how can I manage the labels?</p>
| 0 | 2016-10-12T15:46:36Z | 40,008,433 | <p><code>seaborn</code> does this neatly:</p>
<pre><code>from pandas import read_csv
from matplotlib.pyplot import show
from seaborn import factorplot
fil = read_csv('multi_bar.txt', sep=r'\s*', engine='python', header=None)
fil.columns=['site','type','value']
factorplot(data=fil, x='site', y='value', hue='type', kind='bar')
show()
</code></pre>
<p><a href="https://i.stack.imgur.com/UtEPr.png" rel="nofollow"><img src="https://i.stack.imgur.com/UtEPr.png" alt="enter image description here"></a></p>
| 0 | 2016-10-12T21:11:55Z | [
"python",
"matplotlib"
] |
pandas: How to format timestamp axis labels nicely in df.plt()? | 40,002,953 | <p>I have a dataset that looks like this:</p>
<pre><code> prod_code month items cost
0 040201060AAAIAI 2016-05-01 5 572.20
1 040201060AAAKAK 2016-05-01 164 14805.19
2 040201060AAALAL 2016-05-01 13465 14486.07
</code></pre>
<p>Doing <code>df.dtypes</code> shows that the <code>month</code> column is a <code>datetime64[ns]</code> type. </p>
<p>I am now trying to plot the cost per month for a particular product: </p>
<pre><code>df[df.bnf_code=='040201060AAAIAI'][['month', 'cost']].plot()
plt.show()
</code></pre>
<p>This works, but the x-axis isn't a timestamp as I'd expect:</p>
<p><a href="https://i.stack.imgur.com/aQjwR.png" rel="nofollow"><img src="https://i.stack.imgur.com/aQjwR.png" alt="enter image description here"></a></p>
<p>How can I format the x-axis labels nicely, with month and year labels?</p>
<p>Update: I also tried this, to get a bar chart, which does output timestamps on the x-axis, but in a very long unwieldy format: </p>
<pre><code>df[df.bnf_code=='040201060AAAIAI'].plot.bar(x='month', y='cost', title='Spending on 040201060AAAIAI')
</code></pre>
| 2 | 2016-10-12T15:49:48Z | 40,003,927 | <p>If you set the dates as index, the x-axis should be labelled properly:</p>
<pre><code>df[df.bnf_code=='040201060AAAIAI'][['month', 'cost']].set_index('month').plot()
</code></pre>
<p>I have simply added <code>set_index</code> to your code.</p>
| 2 | 2016-10-12T16:40:01Z | [
"python",
"pandas",
"matplotlib"
] |
How to elegantly create a pyspark Dataframe from a csv file and convert it to a Pandas Dataframe? | 40,003,021 | <p>I'm having a CSV file which I want to read into an RDD or DataFrame. This is working so far, but if I collect the data and convert it into a pandas DataFrame for plotting the table is "malformed".</p>
<p>Here is how I read the CSV file:</p>
<pre><code>NUMERIC_DATA_FILE = os.path.join(DATA_DIR, "train_numeric.csv")
numeric_rdd = sc.textFile(NUMERIC_DATA_FILE)
numeric_rdd = numeric_rdd.mapPartitions(lambda x: csv.reader(x, delimiter=","))
numeric_df = sqlContext.createDataFrame(numeric_rdd)
numeric_df.registerTempTable("numeric")
</code></pre>
<p>The result looks like this:</p>
<p><a href="https://i.stack.imgur.com/fRwjI.png" rel="nofollow"><img src="https://i.stack.imgur.com/fRwjI.png" alt="enter image description here"></a></p>
<p>Is there an easy way to correctly set the first row of the CSV data to columns and the first column as index?</p>
<hr>
<p>This problem goes further as I try to select data from the <code>DataFrame</code>:</p>
<pre><code>numeric_df.select("SELECT Id FROM numeric")
</code></pre>
<p>which gives me:</p>
<pre><code>AnalysisException: u"cannot resolve 'SELECT Id FROM numeric' given input columns _799, _640, _963, _70, _364, _143, _167,
_156, _553, _835, _780, _235, ...
</code></pre>
| 1 | 2016-10-12T15:53:29Z | 40,004,222 | <h2>Setting a schema for your PySpark DataFrame</h2>
<p>Your PySpark DataFrame does not have a schema assigned to it. You should replace your code with the snippet below:</p>
<pre><code>from pyspark.sql.types import *
NUMERIC_DATA_FILE = sc.textFile(os.path.join(DATA_DIR, "train_numeric.csv"))
# Extract the header line
header = NUMERIC_DATA_FILE.first()
# Assuming that all the columns are numeric, let's create a new StructField for each column
fields = [StructField(field_name, FloatType(), True) for field_name in header]
</code></pre>
<p>Now, we can construct our schema, </p>
<pre><code>schema = StructType(fields)
# We have the remove the header from the textfile rdd
# Extracting the header (first line) from the RDD
dataHeader = NUMERIC_DATA_FILE.filter(lambda x: "Id" in x)
# Extract the data without headers. We can make use of the `subtract` function
dataNoHeader = NUMERIC_DATA_FILE.subtract(dataHeader)
numeric_temp_rdd = dataNoHeader.mapPartitions(lambda x: csv.reader(x, delimiter=","))
</code></pre>
<p>The Schema is passed in as a parameter into the <code>createDataFrame()</code> function</p>
<pre><code>numeric_df = sqlContext.createDataFrame(numeric_temp_rdd,schema)
numeric_df.registerTempTable("numeric")
</code></pre>
<p>Now, if you wish to convert this DataFrame to a Pandas dataframe, use the <code>toPandas()</code> function:</p>
<pre><code>pandas_df = numeric_df.limit(5).toPandas()
</code></pre>
<h2>The following statement will work as well:</h2>
<pre><code>numeric_df.select("Id")
</code></pre>
<h2>If you want to use pure SQL, you need to use SQLContext to query your table</h2>
<pre><code>from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
sqlContext.sql('SELECT Id from numeric')
</code></pre>
| 0 | 2016-10-12T16:55:46Z | [
"python",
"pandas",
"pyspark"
] |
Why does __slots__ = ('__dict__',) produce smaller instances? | 40,003,067 | <pre><code>class Spam(object):
__slots__ = ('__dict__',)
</code></pre>
<p>Produces instances smaller than those of a "normal" class. Why is this?</p>
<p>Source: <a href="https://twitter.com/dabeaz/status/785948782219231232" rel="nofollow">David Beazley's recent tweet</a>. </p>
| 5 | 2016-10-12T15:55:31Z | 40,003,530 | <p>To me, it looks like the memory savings come from the lack of a <code>__weakref__</code> on the instance.</p>
<p>So if we have:</p>
<pre><code>class Spam1(object):
__slots__ = ('__dict__',)
class Spam2(object):
__slots__ = ('__dict__', '__weakref__')
class Spam3(object):
__slots__ = ('foo',)
class Eggs(object):
pass
objs = Spam1(), Spam2(), Spam3(), Eggs()
for obj in objs:
obj.foo = 'bar'
import sys
for obj in objs:
print(type(obj).__name__, sys.getsizeof(obj))
</code></pre>
<p>The results (on python 3.5.2) are:</p>
<pre><code>Spam1 48
Spam2 56
Spam3 48
Eggs 56
</code></pre>
<p>We see that <code>Spam2</code> (which has a <code>__weakref__</code>) is the same size as <code>Eggs</code> (a traditional class).</p>
<p>Note that normally, this savings is going to be completely insignificant (and prevents you from using weak-references in your slots enabled classes). Generally, savings from <code>__slots__</code> come from the fact that they don't create a <code>__dict__</code> in the first place. Since <code>__dict__</code> are implemented using a somewhat sparse table (in order to help avoid hash collisions and maintain O(1) lookup/insert/delete), there's a fair amount of space that isn't used for each dictionary that your program creates. If you add <code>'__dict__'</code> to your <code>__slots__</code> though, you miss out on this optimization (a dict is still created). </p>
<p>To explore this a little more, we can add more slots:</p>
<pre><code>class Spam3(object):
__slots__ = ('foo', 'bar')
</code></pre>
<p>Now if we re-run, we see that it takes:</p>
<pre><code>Spam1 48
Spam2 56
Spam3 56
Eggs 56
</code></pre>
<p>So each slot takes 8 bytes on the <em>instance</em> (for me -- likely because 8 bytes is <code>sizeof(pointer)</code> on my system). Also note that <code>__slots__</code> is implemented by making descriptors (which live on the <em>class</em>, not the instance). So, the instance (even though you might find <code>__slots__</code> listed via <code>dir(instance)</code>) isn't actually carrying around a <code>__slots__</code> value) -- That's being carried around by the <em>class</em>.</p>
<p>This also has the consequence that your slots enabled class can't set "default" values... e.g. the following code doesn't work:</p>
<pre><code>class Foo(object):
__slots__ = ('foo',)
foo = 'bar'
</code></pre>
<p>So to boil it down:</p>
<ul>
<li>each "slot" on an instance takes up the size of a pointer on your system.</li>
<li>without <code>__slots__ = ('__dict__',)</code> a <code>__dict__</code> slot and a <code>__weakref__</code> slot is created on the instance</li>
<li>with <code>__slots__ = ('__dict__',)</code>, a <code>__dict__</code> slot is created but a <code>__weakref__</code> slot is not create on the instance.</li>
<li>In neither case is <code>__slots__</code> actually put on the <em>instance</em>. It lives on the <em>class</em> (even though you might see it from <code>dir(instance)</code>).</li>
<li>The savings you reap from using <code>__slots__</code> in this way is likely to be insignificant. Real savings from <code>__slots__</code> happen when you do not create a <code>dict</code> for the instance (since <code>dict</code> take up a more storage than the sum of the storage required for their contents due to somewhat sparse packing data in the data-structure). On top of that, there are downsides to using slots this way (e.g. no weak-references to your instances).</li>
</ul>
| 7 | 2016-10-12T16:18:18Z | [
"python",
"class",
"python-3.x"
] |
Create List without similar crossovers | 40,003,094 | <p>I am trying to build a list of length = 120, which shall include 4 numbers.
The tricky thing is that the numbers shall not appear in a row and each number should occur exactly to the same amount.</p>
<p>This is my script. </p>
<pre><code>import random
List = [1,2,3,4]
seq_CG = random.sample(List,len(List))
for i in range(121):
randomList = random.sample(List, len(List))
if randomList[0]!=seq_CG[-1]:
seq_CG.append(randomList)
i = len(seq_CG)
print List, randomList, seq_CG
</code></pre>
<p>I am pretty close. However something does not work. And maybe there is even a shorter and more random solution?</p>
<p>In the big list seq_CG i do not want that numbers appear in a row. In my example it is filled with a lot of smaller lists. However it would be even nicer to have a random list of 120 numbers with an equal distribution of each number, where numbers do not appear in a row. </p>
| 2 | 2016-10-12T15:57:14Z | 40,003,830 | <p>A slightly naive approach is to have an infinite loop, then scrunch up duplicate values, using <code>islice</code> to cap the total required output, eg:</p>
<pre><code>from itertools import groupby
from random import choice
def non_repeating(values):
if not len(values) > 1:
raise ValueError('must have more than 1 value')
candidates = iter(lambda: choice(values), object())
# Python 3.x -- yield from (k for k, g in groupby(candidates))
# Python 2.x
for k, g in groupby(candidates):
yield k
data = [1, 2, 3, 4]
sequence = list(islice(non_repeating(data), 20))
# [3, 2, 1, 4, 1, 4, 1, 4, 2, 1, 2, 1, 4, 1, 4, 3, 2, 3, 4, 3]
# [3, 2, 3, 4, 1, 3, 1, 4, 1, 4, 2, 1, 2, 3, 2, 4, 1, 4, 2, 3]
# etc...
</code></pre>
| 2 | 2016-10-12T16:35:11Z | [
"python",
"python-2.7",
"open-sesame"
] |
Create List without similar crossovers | 40,003,094 | <p>I am trying to build a list of length = 120, which shall include 4 numbers.
The tricky thing is that the numbers shall not appear in a row and each number should occur exactly to the same amount.</p>
<p>This is my script. </p>
<pre><code>import random
List = [1,2,3,4]
seq_CG = random.sample(List,len(List))
for i in range(121):
randomList = random.sample(List, len(List))
if randomList[0]!=seq_CG[-1]:
seq_CG.append(randomList)
i = len(seq_CG)
print List, randomList, seq_CG
</code></pre>
<p>I am pretty close. However something does not work. And maybe there is even a shorter and more random solution?</p>
<p>In the big list seq_CG i do not want that numbers appear in a row. In my example it is filled with a lot of smaller lists. However it would be even nicer to have a random list of 120 numbers with an equal distribution of each number, where numbers do not appear in a row. </p>
| 2 | 2016-10-12T15:57:14Z | 40,020,074 | <p>Here are a couple of solutions. </p>
<p>The first algorithm maintains an index <code>idx</code> into the sequence and on each call <code>idx</code> is randomly modified to a different index so it's impossible for a yielded value to equal the previous value. </p>
<pre><code>from random import randrange
from itertools import islice
from collections import Counter
def non_repeating(seq):
m = len(seq)
idx = randrange(0, m)
while True:
yield seq[idx]
idx = (idx + randrange(1, m)) % m
seq = [1, 2, 3, 4]
print(''.join(map(str, islice(non_repeating(seq), 60))))
ctr = Counter(islice(non_repeating(seq), 12000))
print(ctr)
</code></pre>
<p><strong>typical output</strong></p>
<pre><code>313231412323431321312312131413242424121414314243432414241413
Counter({1: 3017, 4: 3012, 3: 2993, 2: 2978})
</code></pre>
<p>The distribution of values produced by that code looks fairly uniform, but I haven't analysed it mathematically, and I make no guarantees as to its uniformity.</p>
<p>The following code is more complex, but it does give a uniform distribution. Repeated values are not discarded, they are temporarily added to a pool of repeated values, and the algorithm tries to use values in the pool as soon as possible. If it can't find a suitable value in the pool it generates a new random value.</p>
<pre><code>from random import choice
from itertools import islice
from collections import Counter
def non_repeating(seq):
pool = []
prev = None
while True:
p = set(pool).difference([prev])
if p:
current = p.pop()
pool.remove(current)
else:
current = choice(seq)
if current == prev:
pool.append(current)
continue
yield current
prev = current
seq = [1, 2, 3, 4]
print(''.join(map(str, islice(non_repeating(seq), 60))))
ctr = Counter(islice(non_repeating(seq), 12000))
print(ctr)
</code></pre>
<p><strong>typical output</strong></p>
<pre><code>142134314121212124343242324143123212323414131323434212124232
Counter({4: 3015, 2: 3005, 3: 3001, 1: 2979})
</code></pre>
<p>If the length of the input sequence is only 2 or 3 the pool can get quite large, but for longer sequences it generally only holds a few values.</p>
<hr>
<p>Finally, here's a version that gives an <em>exactly</em> uniform distribution. Do not attempt to use it on an input sequence of 2 (or fewer) elements because it's likely to get stuck in an infinite loop; of course, there are only 2 solutions for such an input sequence anyway. :)</p>
<p>I'm not proud of this rather ugly code, but at least it does the job. I'm creating an output list of length 60 so that it fits nicely on the screen, but this code has no trouble generating much larger sequences.</p>
<pre><code>from random import shuffle
from itertools import groupby
from collections import Counter
def non_repeating(seq, copies=3):
seq = seq * copies
while True:
shuffle(seq)
result, pool = [], []
for k, g in groupby(seq):
result.append(k)
n = len(list(g)) - 1
if n:
pool.extend(n * [k])
for u in pool:
for i in range(len(result) - 1):
if result[i] != u != result[i + 1]:
result.insert(i+1, u)
break
else:
break
else:
return result
# Test that sequence doesn't contain repeats
def verify(seq):
return all(len(list(g)) == 1 for _, g in groupby(seq))
seq = [1, 2, 3, 4]
result = non_repeating(seq, 15)
print(''.join(map(str, result)))
print(verify(result))
print(Counter(result))
</code></pre>
<p><strong>typical output</strong></p>
<pre><code>241413414241343212423232123241234123124342342141313414132313
True
Counter({1: 15, 2: 15, 3: 15, 4: 15})
</code></pre>
| 3 | 2016-10-13T11:45:49Z | [
"python",
"python-2.7",
"open-sesame"
] |
How do I complete this function? | 40,003,197 | <p>For your assignment you must write a compare function that returns 1 if a > b , 0 if a == b , and -1 if a < b . The user must be prompted for the values of a and b. The compare function must have arguments for a and b. To demonstrate your compare function, you must call the compare function three times, once for each condition, from within your program and display (using print statement) the return code of the function.</p>
<p>This is what I have so far...</p>
<pre><code>#-----define the compare function
def compare(a,b):
if (a == b):
return 0
elif (a > b):
return 1
else:
return -1
</code></pre>
<p>What do I do next?</p>
| -1 | 2016-10-12T16:02:26Z | 40,003,389 | <p>For asking user for an input</p>
<ul>
<li>Use <code>input</code> function if you are using Python 3 </li>
<li>Use <code>raw_input</code> function for Python 2.x</li>
</ul>
<p>Convert the input into integer since the input values will be string.</p>
<p>Then call the compare function and get the value returned from compare function into variable and print it.</p>
<pre><code>def compare(a,b):
if (a == b):
return 0
elif (a > b):
return 1
else:
return -1
x=input("Enter first number :")
y=input("Enter first number :")
z=compare(int(x),int(y))
print(z)
</code></pre>
<p>I hope this will be helpful.</p>
| 0 | 2016-10-12T16:11:51Z | [
"python"
] |
How do I complete this function? | 40,003,197 | <p>For your assignment you must write a compare function that returns 1 if a > b , 0 if a == b , and -1 if a < b . The user must be prompted for the values of a and b. The compare function must have arguments for a and b. To demonstrate your compare function, you must call the compare function three times, once for each condition, from within your program and display (using print statement) the return code of the function.</p>
<p>This is what I have so far...</p>
<pre><code>#-----define the compare function
def compare(a,b):
if (a == b):
return 0
elif (a > b):
return 1
else:
return -1
</code></pre>
<p>What do I do next?</p>
| -1 | 2016-10-12T16:02:26Z | 40,003,506 | <p>Here is a menu driven solution that will run three times as desired.</p>
<pre><code> def compare(a,b):
if (a == b):
return 0
elif (a > b):
return 1
else:
return -1
counter =0
while counter < 3:
response=raw_input("Enter a Value for a and b [e.g. (4,5) ] : ")
a , b = str(response).split(",")
result = compare(a,b)
print result
counter += 1
</code></pre>
<p><strong>Output:</strong></p>
<pre><code> Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Enter a Value for a and b [e.g. (4,5) ]: 4,5
-1
Enter a Value for a and b [e.g. (4,5) ]: 5,4
1
Enter a Value for a and b [e.g. (4,5) ]: 5,5
0
>>>
</code></pre>
| 0 | 2016-10-12T16:17:20Z | [
"python"
] |
Calling script in standard project directory structure (Python path for bin subdirectory) | 40,003,221 | <p>I am experimenting with putting my Python code into the standard directory structure used for deployment with <code>setup.py</code> and maybe PyPI. for a Python library called mylib it would be something like this:</p>
<pre><code>mylibsrc/
README.rst
setup.py
bin/
some_script.py
mylib/
__init.py__
foo.py
</code></pre>
<p>There's often also a <code>test/</code> subdirectory but I haven't tried writing unit tests yet. The recommendation to have scripts in a <code>bin/</code> subdirectory can be found in the <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html" rel="nofollow">official Python packaging documentation</a>. </p>
<p>Of course, the scripts start with code that looks like this:</p>
<pre><code>#!/usr/bin/env python
from mylib.foo import something
something("bar")
</code></pre>
<p>This works well when it eventually comes to deploying the script (e.g. to devpi) and then installing it with pip. But if I run the script directly from the source directory, as I would while developing new changes to the library/script, I get this error:</p>
<pre><code>ImportError: No module named 'mylib'
</code></pre>
<p>This is true even if the current working directory is the root <code>mylibsrc/</code> and I ran the script by typing <code>./bin/some_script.py</code>. This is because Python starts searching for packages in the directory of the script being run (i.e. from <code>bin/</code>), not the current working directory.</p>
<p>What is a good, permament way to make it easy to run scripts while developing packages? </p>
<p>Here is a <a href="http://Related%20question%20(especially%20comments%20to%20first%20answer):%20http://stackoverflow.com/questions/193161/what-is-the-best-project-structure-for-a-python-application" rel="nofollow">relevant other question</a> (especially comments to the first answer).</p>
<p>Here are some alternatives I've found so far, but none of them are ideal:</p>
<ul>
<li>Install the package using setup.py into a virtual environment. This seems like overkill if I'm just testing a change that I'm not sure is even syntactically correct yet. Some of the project I'm working on aren't even meant to be installed as packages but I want to use the same directory structure for everything, and this would mean writing a setup.py just so I could test them!</li>
<li>Use the <code>setup.py develop</code> command designed for this purpose. This partially installs the package to a virtual environment, but instead of copying the files it makes a hard link to the development directory. <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode" rel="nofollow">Here are the relevant setuptools docs.</a> (Suggested by logc in their answer below) This has the disadvantage that you still need to create a <code>setup.py</code> for packages you never intend to fully install, and doesn't work very will with PyCharm (which has a menu entry to run the <code>develop</code> command but no easy way to run the scripts that it copies to the virtual environment).</li>
<li>Manually add <code>mylibsrc</code> to my <code>PYTHONPATH</code> environment variable. This would mean that every time I check out a project I have to remember to manually change my environment before I can run any code in it.</li>
<li>Add <code>.</code> to the start of my <code>PYTHONPATH</code> environment variable. As I understand it this could have some security problems. This would actually be my favoured trick if I was the only person to use my code, but I'm not, and I don't want to ask others to do this.</li>
<li>While looking at answers on the internet, for files in a <code>test/</code> directory I've seen recommendations that they all (indirectly) include a line of code <code>sys.path.insert(0, os.path.abspath('..'))</code> (e.g. in <a href="http://docs.python-guide.org/en/latest/writing/structure/" rel="nofollow">structuring your project</a>). Yuck! This seems like a bearable hack for files that are only for testing, but not those that will be installed with the package.</li>
<li>As a last resort: Just dump all of the scripts in the root <code>mylibsrc/</code> directory instead of a <code>bin/</code> subdirectory. Unfortunately, this seems like the only feasible option at the moment.</li>
</ul>
| 1 | 2016-10-12T16:03:37Z | 40,021,910 | <p>The simplest way is to use <code>setuptools</code> in your <code>setup.py</code> script, and use the <code>entry_points</code> keyword, see the documentation of <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation" rel="nofollow">Automatic Script Creation</a>.</p>
<p>In more detail: you create a <code>setup.py</code> that looks like this</p>
<pre><code>from setuptools import setup
setup(
# other arguments here...
entry_points={
'console_scripts': [
'foo = my_package.some_module:main_func',
'bar = other_module:some_func',
],
'gui_scripts': [
'baz = my_package_gui:start_func',
]
}
)
</code></pre>
<p>then create other Python packages and modules underneath the directory where this <code>setup.py</code> exists, e.g. following the above example:</p>
<pre><code>.
âââ my_package
â  âââ __init__.py
â  âââ some_module.py
âââ my_package_gui
â  âââ __init__.py
âââ other_module.py
âââ setup.py
</code></pre>
<p>and then run</p>
<pre><code>$ python setup.py install
</code></pre>
<p>or</p>
<pre><code>$ python setup.py develop
</code></pre>
<p>Either way, new Python scripts (executable scripts without the <code>.py</code> suffix) are created for you that point to the entry points you have described in <code>setup.py</code>. Usually, they are at the Python interpreter's notion of "directory where executable binaries should be", which is usually on your PATH already. If you are using a virtual env, then <code>virtualenv</code> tricks the Python interpreter into thinking this directory is <code>bin/</code> under wherever you have defined that the virtualenv should be. Following the example above, in a virtualenv, running the previous commands should result in:</p>
<pre><code>bin
âââ bar
âââ baz
âââ foo
</code></pre>
| 1 | 2016-10-13T13:07:18Z | [
"python",
"setup.py"
] |
how to create auto increment field in odoo 9 | 40,003,289 | <p>In my model, I want to create auto increment field, I 've tried to follow some tuts unfortunately all tutorials just working in odoo 8 to under.
I just follow instruction from some threat in odoo 9 in this link
<a href="http://stackoverflow.com/questions/39266106/auto-increment-internal-reference-odoo9">auto increment - internal reference odoo9</a>
It was working by answer of <a href="http://stackoverflow.com/users/3734244/danidee">http://stackoverflow.com/users/3734244/danidee</a>
but still not working for me. Here is my model:</p>
<pre><code>class cashadvance(osv.osv):
_name = 'comben.cashadvance'
_columns = {
'sequence_id': fields.char(string='Sequence ID', help="Auto Generate"),
}
@api.model
def create(self, vals):
vals['sequence_id'] = self.env['ir.sequence'].get('seq.cashadvance')
return super(cashadvance, self).create(vals)
</code></pre>
<p>and this is my xml :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<openerp>
<data noupdate="1">
<record id="cashadvance_seq" model="ir.sequence">
<field name="name">No_PD</field>
<field name="padding">3</field>
<field name="code">seq.cashadvance</field>
</record>
</data>
</openerp>
</code></pre>
<p>the code above showing no error but the sequence_id field keep empty when I click save button.
Help me Please...</p>
| 1 | 2016-10-12T16:07:03Z | 40,003,443 | <p>Try with following code.</p>
<p>Replace <em>create</em> method with</p>
<pre><code>@api.model
def create(self, vals):
vals['sequence_id'] = self.env['ir.sequence'].get('comben.cashadvance')
return super(cashadvance, self).create(vals)
</code></pre>
<p>Replace <em>xml</em> file with</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<openerp>
<data noupdate="1">
<record id="cashadvance_seq" model="ir.sequence">
<field name="name">No_PD</field>
<field name="padding">3</field>
<field name="code">comben.cashadvance</field>
</record>
</data>
</openerp>
</code></pre>
<p>Afterwards restart odoo server and upgrade your module.</p>
<p>NOTE:</p>
<p>When you upgrade module and it has <em>.xml</em> file with <em></em> will not upgrade. So first remove <em>noupdate="1"</em> attribute and upgrade module. Check flow. It should work fine. Don't forget to place again <em>noupdate="1"</em> on sequence view file.</p>
<p>Make sure you have given .xml file in __ <em>openerp</em>__.py file </p>
| 1 | 2016-10-12T16:14:48Z | [
"python",
"python-2.7",
"openerp",
"odoo-9"
] |
Redirect subprocess.Popen stderr to console | 40,003,301 | <p>I am executing a make command using subprocess.Popen. But when the make fails I do not get the exact error from make and th escript just continues to run. How do I get the script to stop and show the console exactly the output of the make command</p>
<pre><code>def app(self, build, soc, target):
command = "make BUILD=%s SOC=%s TARGET=%s" % (build, soc, target)
subprocess.Popen(command.split(), shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
</code></pre>
| 0 | 2016-10-12T16:07:58Z | 40,004,630 | <p>Could you try replacing:</p>
<pre><code>subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
</code></pre>
<p>with:</p>
<pre><code>p = subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print p.communicate()
print p.returncode
</code></pre>
<p>And let us know what the printed output looks like.</p>
| 2 | 2016-10-12T17:19:05Z | [
"python"
] |
Redirect subprocess.Popen stderr to console | 40,003,301 | <p>I am executing a make command using subprocess.Popen. But when the make fails I do not get the exact error from make and th escript just continues to run. How do I get the script to stop and show the console exactly the output of the make command</p>
<pre><code>def app(self, build, soc, target):
command = "make BUILD=%s SOC=%s TARGET=%s" % (build, soc, target)
subprocess.Popen(command.split(), shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
</code></pre>
| 0 | 2016-10-12T16:07:58Z | 40,004,792 | <p>If you want the make output to actually go to the console, don't use <code>subprocess.PIPE</code> for stdout/stderr. By default, the called process will use the Python process's stdout/stderr handles. In that case, you can use the <code>subprocess.check_call()</code> function to raise a <code>subprocess.CalledProcessError</code> if the called process returns a non-zero exit code:</p>
<pre><code>subprocess.check_call(command.split())
</code></pre>
<p>However, if you need to capture the make output for use in your script, you can use the similar <code>subprocess.check_output()</code> function:</p>
<pre><code>try:
output = subprocess.check_output(command.split(), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
output = e.output
# error handling here
</code></pre>
<p>Note that this combines the stdout and stderr output into a single value. If you need them separately, you would need to use the <code>subprocess.Popen</code> constructor in conjunction with the <code>.communicate()</code> method and manually checking the <code>returncode</code> attribute of the <code>Popen</code> object:</p>
<pre><code>p = subprocess.Popen(command.split(), stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
# raise exception or other error handling here
</code></pre>
| 0 | 2016-10-12T17:27:28Z | [
"python"
] |
How can I replace all occurrences of a substring using regex? | 40,003,311 | <p>I have a string, <code>s = 'sdfjoiweng%@$foo$fsoifjoi'</code>, and I would like to replace <code>'foo'</code> with <code>'bar'</code>. </p>
<p>I tried <code>re.sub(r'\bfoo\b', 'bar', s)</code> and <code>re.sub(r'[foo]', 'bar', s)</code>, but it doesn't do anything. What am I doing wrong?</p>
| 0 | 2016-10-12T16:08:14Z | 40,003,366 | <p>You can replace it directly:</p>
<pre><code>>>> import re
>>> s = 'sdfjoiweng%@$foo$fsoifjoi'
>>> print re.sub('foo','bar',s)
sdfjoiweng%@$bar$fsoifjoi
</code></pre>
<p>It will also work for more occurrences of <code>foo</code> like below:</p>
<pre><code>>>> s = 'sdfjoiweng%@$foo$fsoifoojoi'
>>> print re.sub('foo','bar',s)
sdfjoiweng%@$bar$fsoibarjoi
</code></pre>
<p>If you want to replace only the 1st occurrence of <code>foo</code> and not all the <code>foo</code> occurrences in the string then alecxe's answer does exactly that.</p>
| 3 | 2016-10-12T16:10:36Z | [
"python",
"regex"
] |
How can I replace all occurrences of a substring using regex? | 40,003,311 | <p>I have a string, <code>s = 'sdfjoiweng%@$foo$fsoifjoi'</code>, and I would like to replace <code>'foo'</code> with <code>'bar'</code>. </p>
<p>I tried <code>re.sub(r'\bfoo\b', 'bar', s)</code> and <code>re.sub(r'[foo]', 'bar', s)</code>, but it doesn't do anything. What am I doing wrong?</p>
| 0 | 2016-10-12T16:08:14Z | 40,003,398 | <blockquote>
<p><code>re.sub(r'\bfoo\b', 'bar', s)</code></p>
</blockquote>
<p>Here, the <code>\b</code> defines <a href="http://www.regular-expressions.info/wordboundaries.html" rel="nofollow">the word boundaries</a> - positions between a word character (<code>\w</code>) and a non-word character - exactly what you have matching for <code>foo</code> inside the <code>sdfjoiweng%@$foo$fsoifjoi</code> string. Works for me:</p>
<pre><code>In [1]: import re
In [2]: s = 'sdfjoiweng%@$foo$fsoifjoi'
In [3]: re.sub(r'\bfoo\b', 'bar', s)
Out[3]: 'sdfjoiweng%@$bar$fsoifjoi'
</code></pre>
| 2 | 2016-10-12T16:12:26Z | [
"python",
"regex"
] |
How can I replace all occurrences of a substring using regex? | 40,003,311 | <p>I have a string, <code>s = 'sdfjoiweng%@$foo$fsoifjoi'</code>, and I would like to replace <code>'foo'</code> with <code>'bar'</code>. </p>
<p>I tried <code>re.sub(r'\bfoo\b', 'bar', s)</code> and <code>re.sub(r'[foo]', 'bar', s)</code>, but it doesn't do anything. What am I doing wrong?</p>
| 0 | 2016-10-12T16:08:14Z | 40,003,531 | <p>You can use replace function directly instead of using regex.</p>
<pre><code>>>> s = 'sdfjoiweng%@$foo$fsoifjoifoo'
>>>
>>> s.replace("foo","bar")
'sdfjoiweng%@$bar$fsoifjoibar'
>>>
>>>
</code></pre>
| 2 | 2016-10-12T16:18:23Z | [
"python",
"regex"
] |
Extracting particular data with BeautifulSoup with span tags | 40,003,342 | <p>I have this structure.</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><div id="one" class="tab-pane active">
<div class="item-content">
<a href="/mobilni-uredjaji.4403.html">
<div class="item-primary">
<div class="sticker-small">
<span class=""></span>
</div>
<div class="sticker-small-lte">
<span class="lte"></span>
</div>
<div class="item-photo">
<img src="/upload/images/thumbs/devices/SAMG935F/SAMG935F_image001_220x230.png" alt="Samsung Galaxy S7 edge">
</div>
<div class="item-labels">
<span class="item-manufacturer">Samsung</span>
<span class="item-title">Galaxy S7 edge</span>
</div>
</div>
<div class="item-secondary">
<span class="item-price">94.000<span class="currency">currency!</span></span>
<span class="item-package"> uz! Sigurica 1500</span>
<span class="item-installments">na! 24 rate_po!</span>
<span class="value">100 currency!</span>
<span class="item-available">device_is_available_on_webshop_list!</span>
</div>
</a>
</div>
<div class="item-content">
<a href="/mobilni-uredjaji.4403.html">
<div class="item-primary">
<div class="sticker-small">
<span class=""></span>
</div>
<div class="sticker-small-lte">
<span class="lte"></span>
</div>
<div class="item-photo">
<img src="/upload/images/thumbs/devices/SAMG935F/SAMG935F_image001_220x230.png" alt="Samsung Galaxy S7 edge">
</div>
<div class="item-labels">
<span class="item-manufacturer">Samsung</span>
<span class="item-title">Galaxy S7 edge</span>
</div>
</div>
<div class="item-secondary">
<span class="item-price">94.000<span class="currency">currency!</span></span>
<span class="item-package"> uz! Sigurica 1500</span>
<span class="item-installments">na! 24 rate_po!</span>
<span class="value">100 currency!</span>
<span class="item-available">device_is_available_on_webshop_list!</span>
</div>
</a>
</div>
-----same structure ----
</div> </code></pre>
</div>
</div>
</p>
<p>My target is div with class="item-labels" with corresponding data:</p>
<ul>
<li>Samsung</li>
<li>Galaxy S7 edge</li>
</ul>
<p>and div with class "item-secondary" with data under the span tag with class="item-price", 94.000.</p>
<p>I need my output to be exactly:</p>
<ul>
<li>Samsung</li>
<li>Galaxy S7 edge</li>
<li>94000</li>
</ul>
<p>So far with this code i am getting first two data without price under the span. I am kinda stuck here because i haven't done scraping quite a while.
Please hint?
Code is: </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>from bs4 import BeautifulSoup
import re
import pymysql
import MySQLdb
import urllib
#rl = "http://www.vipmobile.rs/mobilni-uredjaji.2631.html#tarifgroup-1|devicetype-1|minprice-0|maxprice-124800|brand-0|model-0"
url = "file:///C:/Users/zika/Desktop/one.html"
html = urllib.urlopen(url)
page = html.read()
#print(page)
# db = MySQLdb.connect(host = 'localhost',
# user = 'root',
# passwd = '123456',
# db = 'lyrics')
soup = BeautifulSoup(page, 'html.parser')
#mobData = soup.find("div", {"class": "bxslider items"}).find_all("div", {"class": "item-content"})
#for mobMan in soup.find("div", {"class": "tab-pane active"}).findAll("span")
labelData = soup.find("div", {"class": "tab-pane active"}).find_all("div", {"class": "item-content"})
labelPrice = soup.find("div", {"class": "tab-pane active"}).find_all("span", class_="item-price")
for label in labelData:
print(label.contents[1].find("div", {"class": "item-labels"}).getText())
for price in labelPrice:
print(price.getText())
input("\n\nPress the enter key to exit!") </code></pre>
</div>
</div>
</p>
| 0 | 2016-10-12T16:09:23Z | 40,004,347 | <p>You could try that:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup(source, "html.parser")
div1 = soup.find("div", { "class" : "item-labels" }).findAll('span', { "class" : "item-manufacturer" })
div2 = soup.find("div", { "class" : "item-labels" }).findAll('span', { "class" : "item-title" })
div3 = soup.find("div", { "class" : "item-secondary" }).findAll('span', { "class" : "item-price" })
for i,j,k in zip(div1,div2,div3):
print i.text
print j.text
print k.text.replace("currency!",'')
</code></pre>
<p>Note: as <code>source</code> in the above code I used the structure you provided in your post.</p>
<p>This will give the following output:</p>
<pre><code>Samsung
Galaxy S7 edge
94.000
</code></pre>
| 1 | 2016-10-12T17:02:21Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Matching multiple patterns in a string | 40,003,362 | <p>I have a string that looks like that:</p>
<pre><code>s = "[A] text [B] more text [C] something ... [A] hello"
</code></pre>
<p>basically it consists of <code>[X] chars</code> and I am trying to get the text "after" every <code>[X]</code>.</p>
<p>I would like to yield this dict (I don't care about order):</p>
<pre><code>mydict = {"A":"text, hello", "B":"more text", "C":"something"}
</code></pre>
<p>I was thinking about a regex but I was not sure if that is the right choice because in my case the order of [A], [B] and [C] can change, so this string is valid too:</p>
<pre><code>s = "[A] hello, [C] text [A] more text [B] something"
</code></pre>
<p>I don't know how to properly extract the string. Can anyone point me to the right direction? Thanks.</p>
| 1 | 2016-10-12T16:10:21Z | 40,003,541 | <blockquote>
<p>Expected output: <code>mydict = {"A":"text, hello", "B":"more text", "C":"something"}</code></p>
</blockquote>
<pre><code>import re
s = "[A] text [B] more text [C] something ... [A] hello"
pattern = r'\[([A-Z])\]([ a-z]+)'
items = re.findall(pattern, s)
output_dict = {}
for x in items:
if x[0] in output_dict:
output_dict[x[0]] = output_dict[x[0]] + ', ' + x[1].strip()
else:
output_dict[x[0]] = x[1].strip()
print(output_dict)
</code></pre>
<p><code>>>> {'A': 'text, hello', 'B': 'more text', 'C': 'something'}</code></p>
| 1 | 2016-10-12T16:18:41Z | [
"python",
"regex"
] |
Matching multiple patterns in a string | 40,003,362 | <p>I have a string that looks like that:</p>
<pre><code>s = "[A] text [B] more text [C] something ... [A] hello"
</code></pre>
<p>basically it consists of <code>[X] chars</code> and I am trying to get the text "after" every <code>[X]</code>.</p>
<p>I would like to yield this dict (I don't care about order):</p>
<pre><code>mydict = {"A":"text, hello", "B":"more text", "C":"something"}
</code></pre>
<p>I was thinking about a regex but I was not sure if that is the right choice because in my case the order of [A], [B] and [C] can change, so this string is valid too:</p>
<pre><code>s = "[A] hello, [C] text [A] more text [B] something"
</code></pre>
<p>I don't know how to properly extract the string. Can anyone point me to the right direction? Thanks.</p>
| 1 | 2016-10-12T16:10:21Z | 40,003,571 | <p>Not sure if this is quite what you're looking for but it fails with duplicates</p>
<pre><code>s = "[A] hello, [C] text [A] more text [B] something"
results = [text.strip() for text in re.split('\[.\]', s) if text]
letters = re.findall('\[(.)\]', s)
dict(zip(letters, results))
{'A': 'more text', 'B': 'something', 'C': 'text'}
</code></pre>
<p>Since the output looks like this:</p>
<pre><code>In [49]: results
Out[49]: ['hello,', 'text', 'more text', 'something']
In [50]: letters
Out[50]: ['A', 'C', 'A', 'B']
</code></pre>
<p>To solve for duplicate you could do something like....</p>
<pre><code>mappings = {}
for pos, letter in enumerate(letters):
try:
mappings[letter] += ' ' + results[pos]
except KeyError:
mappings[letter] = results[pos]
</code></pre>
<p>which gives: <code>{'A': 'hello, more text', 'B': 'something', 'C': 'text'}</code></p>
<p><strong>UPDATE</strong></p>
<p>Or even better you could look at using a default dict: as shown here: <a href="http://stackoverflow.com/questions/33091911/python-append-to-dictionary-from-a-zip">enter link description here</a></p>
| 3 | 2016-10-12T16:19:59Z | [
"python",
"regex"
] |
Matching multiple patterns in a string | 40,003,362 | <p>I have a string that looks like that:</p>
<pre><code>s = "[A] text [B] more text [C] something ... [A] hello"
</code></pre>
<p>basically it consists of <code>[X] chars</code> and I am trying to get the text "after" every <code>[X]</code>.</p>
<p>I would like to yield this dict (I don't care about order):</p>
<pre><code>mydict = {"A":"text, hello", "B":"more text", "C":"something"}
</code></pre>
<p>I was thinking about a regex but I was not sure if that is the right choice because in my case the order of [A], [B] and [C] can change, so this string is valid too:</p>
<pre><code>s = "[A] hello, [C] text [A] more text [B] something"
</code></pre>
<p>I don't know how to properly extract the string. Can anyone point me to the right direction? Thanks.</p>
| 1 | 2016-10-12T16:10:21Z | 40,003,902 | <p>Here's a simple solution:</p>
<pre class="lang-or-tag-here prettyprint-override"><code>#!/usr/bin/python
import re
s = "[A] text [B] more text [C] something ... [A] hello"
d = dict()
for x in re.findall(r"\[[^\]+]\][^\[]*",s):
m = re.match(r"\[([^\]*])\](.*)",x)
if not d.get(m.group(1),0):
#Key doesn't already exist
d[m.group(1)] = m.group(2)
else:
d[m.group(1)] = "%s, %s" % (d[m.group(1)], m.group(2))
print d
</code></pre>
<p>Prints:</p>
<pre><code>{'A': ' text , hello', 'C': ' something ... ', 'B': ' more text '}
</code></pre>
| 0 | 2016-10-12T16:38:54Z | [
"python",
"regex"
] |
PEP8 error in import line: E501 line too long | 40,003,378 | <p>I have a python import string. PEP8 linter show to me E501 error <code>line too long (82 > 79 characters)</code>:</p>
<pre><code>from tornado.options import define, options, parse_config_file, parse_command_line
</code></pre>
<p>Solution with two line seems weird to me:</p>
<pre><code>from tornado.options import define, options, parse_config_file
from tornado.options import parse_command_line
</code></pre>
<p>How I can fix it without disable E501 for this line? </p>
| 2 | 2016-10-12T16:11:13Z | 40,003,478 | <p>Put your imported names in parentheses, letting you span multiple lines:</p>
<pre><code>from tornado.options import (
define,
options,
parse_config_file,
parse_command_line,
)
</code></pre>
<p>Using one line per name has the added advantage that later edits to the list of names imported reduce line churn (you can see what was added and removed in your version control system as separate lines).</p>
| 5 | 2016-10-12T16:16:05Z | [
"python",
"coding-style",
"pep8"
] |
PEP8 error in import line: E501 line too long | 40,003,378 | <p>I have a python import string. PEP8 linter show to me E501 error <code>line too long (82 > 79 characters)</code>:</p>
<pre><code>from tornado.options import define, options, parse_config_file, parse_command_line
</code></pre>
<p>Solution with two line seems weird to me:</p>
<pre><code>from tornado.options import define, options, parse_config_file
from tornado.options import parse_command_line
</code></pre>
<p>How I can fix it without disable E501 for this line? </p>
| 2 | 2016-10-12T16:11:13Z | 40,003,519 | <p>See <a href="https://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328</a> for your options. Parentheses are probably the way to go.</p>
| 1 | 2016-10-12T16:17:44Z | [
"python",
"coding-style",
"pep8"
] |
PEP8 error in import line: E501 line too long | 40,003,378 | <p>I have a python import string. PEP8 linter show to me E501 error <code>line too long (82 > 79 characters)</code>:</p>
<pre><code>from tornado.options import define, options, parse_config_file, parse_command_line
</code></pre>
<p>Solution with two line seems weird to me:</p>
<pre><code>from tornado.options import define, options, parse_config_file
from tornado.options import parse_command_line
</code></pre>
<p>How I can fix it without disable E501 for this line? </p>
| 2 | 2016-10-12T16:11:13Z | 40,003,609 | <p>You should write it the way you think is more readable.. the 80 column limit was put in place for old style terminals that did not support re-sizing, which itself was for legacy support of terminal only computers where the monitor was only 80 chars wide. See: <a href="https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds" rel="nofollow">A Foolish Consistency is the Hobgoblin of Little Minds</a> #1 from pep8</p>
| 0 | 2016-10-12T16:22:24Z | [
"python",
"coding-style",
"pep8"
] |
How to capture the prints of a python script being executed from another python script? | 40,003,483 | <p>I have 2 scripts <code>script1.py</code> and <code>script2.py</code> in the same folder ,script1.py calls script2.py using Popen(See code below for details),issue is that the prints coming from script2.py is not being captured in script1.py,<code>print output</code> and <code>print error</code> doesn't print a thing in the code below? what am I missing here? how do I capture the prints from script2.py?</p>
<p>script1.py</p>
<pre><code>import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
cmd = "python script2.py"
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(output, error) = proc.communicate()
print output
print error
func1()
print "Done.."
</code></pre>
<p>script2.py</p>
<pre><code>import sys
print "ERROR:port not detected"
sys.exit(29)
</code></pre>
<p>OUTPUT:-</p>
<pre><code>C:\Dropbox>python script1.py
ERROR:port not detected
Done..
</code></pre>
| 1 | 2016-10-12T16:16:19Z | 40,004,066 | <p><strong>Edited answer based on comments</strong></p>
<p>Looks like after the edits you made to the original question, Your code is working correctly.
I just put <code>output=</code> in front of print statement to check that.</p>
<pre><code>import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
cmd = "python script2.py"
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(output, error) = proc.communicate()
print "output=",output
print error
func1()
print "Done.."
</code></pre>
<p>** OUTPUT: **</p>
<pre><code>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
output= ERROR:port not detected
Done..
>>>
</code></pre>
| 3 | 2016-10-12T16:47:43Z | [
"python",
"popen"
] |
How to capture the prints of a python script being executed from another python script? | 40,003,483 | <p>I have 2 scripts <code>script1.py</code> and <code>script2.py</code> in the same folder ,script1.py calls script2.py using Popen(See code below for details),issue is that the prints coming from script2.py is not being captured in script1.py,<code>print output</code> and <code>print error</code> doesn't print a thing in the code below? what am I missing here? how do I capture the prints from script2.py?</p>
<p>script1.py</p>
<pre><code>import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
cmd = "python script2.py"
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(output, error) = proc.communicate()
print output
print error
func1()
print "Done.."
</code></pre>
<p>script2.py</p>
<pre><code>import sys
print "ERROR:port not detected"
sys.exit(29)
</code></pre>
<p>OUTPUT:-</p>
<pre><code>C:\Dropbox>python script1.py
ERROR:port not detected
Done..
</code></pre>
| 1 | 2016-10-12T16:16:19Z | 40,004,373 | <p>your script is in fact working as intended. You likely are expecting a traceback to be printed to stderr of your subprocess, but that's not how <code>sys.exit()</code> works.</p>
<h3>script1.py</h3>
<pre class="lang-python prettyprint-override"><code>import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
cmd = "python script2.py"
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(output, error) = proc.communicate()
print output[::-1] #prints reversed message proving print is called from script1 not script2
print error #prints nothing because there is no error text (no error was raised only system exit)
print 'return status: '+str(proc.returncode) #this is what sys.exit() modifies
func1()
print "Done.. YAY" #done prints after call</code></pre>
<h3>script2.py</h3>
<pre class="lang-python prettyprint-override"><code>import sys
print "ERROR:port not detected"
sys.exit(29) #does not print traceback (or anything) only sets return code
print "Done.." #never prints because python interpreter is terminated</code></pre>
<p>when script1 calls script2 as a subprocess, script2 prints it's first statement to the stdout pipe, then exits with a return code of 29. A system exit with a return code of 0 is viewed as a successful return, so unless you specifically call something that raises an error, nothing will print to the stderr pipe. the return code can however be determined from the attribute <code>returncode</code> of your <code>proc</code>.</p>
<p>running <code>>python script1.py</code> yields:</p>
<pre>
detceted ton trop:RORRE
return status: 29
Done.. YAY</pre>
| 1 | 2016-10-12T17:03:41Z | [
"python",
"popen"
] |
Web in python that interacts with linux | 40,003,543 | <p>Is there a way to make web in python (mixed with <code>html/php</code>) that interacts with PC (<code>linux</code> OS) ?</p>
<p>As example: you click button in webpage and It sends command to PC (<code>linux</code>) that activates another <code>python</code> script, but not in web format (example: I push button 'RUN PYTHON.PY SCRIPT' and it sends command to PC to activate it)</p>
<p><code>web server</code> will be on the same computer, <code>localhost</code></p>
| -3 | 2016-10-12T16:18:45Z | 40,003,875 | <p>Yes, it is possible. Here is one way to do it.</p>
<pre><code>#!/usr/bin/env python
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def root():
return '''
<html><body><form action="/run" method="post">
<input type="submit" value="Run Python Script!"/>
</form></body></html>'''
@app.route('/run', methods=['POST'])
def run():
os.system("python /tmp/script.py > /tmp/out 2>&1")
return '''<html><body><p>The script has run.</p></body></html>'''
if __name__=='__main__':
app.run(debug=True)
</code></pre>
<p>Here is an example which passes information from the form to the python script:</p>
<pre><code>#!/usr/bin/env python
import os
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def root():
return '''
<html><body><form action="/run" method="post">
Arg1: <input name="Arg1"/><br/>
Arg2: <input name="Arg2"/><br/>
<input type="submit" value="Run Python Script!"/>
</form></body></html>'''
@app.route('/run', methods=['POST'])
def run():
# DANGER! DANGER! Example code only. Code injection bug in next line
cmd = "python /tmp/script.py {} {} > /tmp/out 2>&1".format(
request.form.get('Arg1'),
request.form.get('Arg2'),
)
os.system(cmd)
return '''<html><body><p>The script has run.</p></body></html>'''
if __name__=='__main__':
app.run(debug=True)
</code></pre>
<p>In each of these examples, you'll want to consider the security requirements of your own application. I have highlighted one security vulnerability in the second example; there may be others.</p>
| 3 | 2016-10-12T16:37:29Z | [
"php",
"python",
"linux"
] |
python pandas, trying to find unique combinations of two columns and merging while summing a third column | 40,003,559 | <p>Hi I will show what im trying to do through examples:
I start with a dataframe like this:</p>
<pre><code>> pd.DataFrame({'A':['a','a','a','c'],'B':[1,1,2,3], 'count':[5,6,1,7]})
A B count
0 a 1 5
1 a 1 6
2 a 2 1
3 c 3 7
</code></pre>
<p>I need to find a way to get all the unique combinations between column A and B, and merge them. The count column should be added together between the merged columns, the result should be like the following:</p>
<pre><code> A B count
0 a 1 11
1 a 2 1
2 c 3 7
</code></pre>
<p>Thans for any help.</p>
| 3 | 2016-10-12T16:19:14Z | 40,003,588 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with aggregating <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.sum.html" rel="nofollow"><code>sum</code></a>:</p>
<pre><code>print (df.groupby(['A','B'], as_index=False)['count'].sum())
A B count
0 a 1 11
1 a 2 1
2 c 3 7
print (df.groupby(['A','B'])['count'].sum().reset_index())
A B count
0 a 1 11
1 a 2 1
2 c 3 7
</code></pre>
| 4 | 2016-10-12T16:21:14Z | [
"python",
"pandas",
"group-by",
"sum",
"aggregate"
] |
Python telnet client | 40,003,572 | <p>Everyone, hello!</p>
<p>I'm currently trying to use Telnetlib (<a href="https://docs.python.org/2/library/telnetlib.html" rel="nofollow">https://docs.python.org/2/library/telnetlib.html</a>) for Python 2.7 to communicate with some external devices.</p>
<p>I have the basics set up:</p>
<pre><code>import sys
import telnetlib
tn_ip = xxxx
tn_port = xxxx
tn_username = xxxxx
tn_password = xxxx
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn, tn, 15)
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
tn.read_until(searchfor)
print "Found it!"
except:
print "Unable to connect to Telnet server: " + tn_ip
telnet()
</code></pre>
<p>And I'm trying to go through all of the data it's outputting (which is quite a lot) until I catch what I need. Although it is logging in quite fine, and even finds the data I'm looking for, and prints my found it message, I'm trying for a way to keep the connection with telnet open as there might be other data (or repeated data) i would be missing if I logged off and logged back in.</p>
<p>Does anyone know how to do this?</p>
| 2 | 2016-10-12T16:20:02Z | 40,054,951 | <p>Seems like you want to connect to external device once and print a message each time you see a specific string.</p>
<pre><code>import sys
import telnetlib
tn_ip = "0.0.0.0"
tn_port = "23"
tn_username = "xxxxx"
tn_password = "xxxx"
searchfor = "Specificdata"
def telnet():
try:
tn = telnetlib.Telnet(tn_ip, tn_port, 15)
except:
print "Unable to connect to Telnet server: " + tn_ip
return
tn.set_debuglevel(100)
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
while True:
tn.read_until(searchfor)
print "Found it"
telnet()
</code></pre>
| 0 | 2016-10-15T04:28:38Z | [
"python",
"telnet",
"telnetlib"
] |
Python3, PyQt5: QProgressBar updating makes actual task very slow | 40,003,598 | <p>I am using Python 3.5, PyQt5 on OSX and I was wondering if there was a possibility to update the QProgressBar without slowing down the whole computing work.
Here was my code and if I did just the task without the progressbar update it was soo much faster!! </p>
<pre><code>from PyQt5.QtWidgets import (QWidget, QProgressBar, QPushButton, QApplication)
from jellyfish import levenshtein_distance, jaro_winkler
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.pbar = QProgressBar(self)
self.pbar.setGeometry(30, 40, 200, 25)
self.btn = QPushButton('Start', self)
self.btn.move(40, 80)
self.btn.clicked.connect(self.doAction)
self.setGeometry(300, 300, 280, 170)
self.show()
def doAction(self):
#setup variables
step = 0
m = 1000
n = 500
step_val = 100 / (m * n)
#make task
for i in range(m):
for j in range(n):
jaro_winkler(str(i), str(j))
#show task
print(i,j)
#update progressbar
step += step_val
self.pbar.setValue(step)
QApplication.processEvents()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
</code></pre>
<p>Then with help from stackoverflow users I got the hint to make a separate working thread and connect the updating signal to the GUI. I did it and it looks now like the following code. It also works and is much faster, but I can't figure out how to connect the emited signal to the GUI. Can somebody please help me? Many thanks in advance!</p>
<pre><code>from jellyfish import jaro_winkler
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QProgressBar, QMainWindow
import time
import numpy as np
class Main_Window(QMainWindow):
def __init__(self):
super(Main_Window,self).__init__()
self.initUI()
def initUI(self):
self.pbar = QProgressBar(self)
self.pbar.setGeometry(30, 40, 200, 25)
self.btn = QPushButton('Start', self)
self.btn.move(40, 80)
self.btn.clicked.connect(MyThread.doAction)
self.setGeometry(300, 300, 280, 170)
self.show()
def updateProgressBar(self, val):
self.pbar.setValue.connect(val)
class MySignal(QWidget):
pbar_signal = QtCore.pyqtSignal(int)
class MyThread(QtCore.QThread):
def __init__(self):
super().__init__()
def doAction(self):
t = time.time() #for time measurement
#setup variables
step = 0
m = 1000
n = 500
pbar_val = 100 / m
signal_instance = MySignal()
#make task
for i in range(m):
for j in range(n):
jaro_winkler(str(i), str(j))
signal_instance.pbar_signal.emit(pbar_val)
#measuring task time
print(np.round_(time.time() - t, 3), 'sec elapsed')
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Main_Window()
sys.exit(app.exec_())
</code></pre>
| 1 | 2016-10-12T16:22:02Z | 40,005,253 | <p>There are three things slowing the code down:</p>
<ol>
<li>Printing to stdout is very expensive - especially when you do it 500,000 times! On my system, commenting out <code>print(i,j)</code> roughly halves the time <code>doAction</code> takes to run.</li>
<li>It's also quite expensive to call <code>processEvents</code> 500,000 times. Commenting out <code>QApplication.processEvents()</code> reduces the run time by another two-thirds.</li>
<li>Commenting out <code>self.pbar.setValue(step)</code> halves the time again.</li>
</ol>
<p>Hopefully it should be obvious by now that attempting to update the gui 500,000 times during a task that should take less than a second is massive overkill! Most user's reaction times are about 200ms at best, so you only need to update the gui about once every 100ms.</p>
<p>Given that, one simple fix is to move the updates into the outer loop:</p>
<pre><code> for i in range(m):
for j in range(n):
jaro_winkler(str(i), str(j))
# show task
# print(i,j)
step += step_val
# update progressbar
self.pbar.setValue(step)
QApplication.processEvents()
</code></pre>
<p>But an even better solution would be to move the calculations into a separate worker thread and have it periodically emit a custom signal to update the progress bar:</p>
<pre><code>class Main_Window(QMainWindow):
...
def initUI(self):
...
self.btn.clicked.connect(self.doAction)
self.thread = MyThread()
self.thread.pbar_signal.connect(self.pbar.setValue)
def doAction(self):
if not self.thread.isRunning():
self.thread.start()
class MyThread(QtCore.QThread):
pbar_signal = QtCore.pyqtSignal(int)
def run(self):
#for time measurement
t = time.time()
#setup variables
m = 1000
n = 500
progress = step = 100 / m
#make task
for i in range(m):
for j in range(n):
jaro_winkler(str(i), str(j))
progress += step
self.pbar_signal.emit(progress)
#measuring task time
print(np.round_(time.time() - t, 3), 'sec elapsed')
</code></pre>
| 0 | 2016-10-12T17:54:49Z | [
"python",
"python-3.x",
"signals",
"pyqt5",
"qprogressbar"
] |
subprocess permission denied | 40,003,813 | <p>I was looking into how python can start other programs on windows 10, I was on stack overflow and someone said that:</p>
<pre><code>import subprocess
subprocess.call(['C:\\Users\Edvin\Desktop', 'C:\\Example.txt'])
</code></pre>
<p>should do it, so I changed the locations so it is specific to me and there was an error which was <code>PermissionError: [WinError 5] Access is denied</code>.</p>
<p>Does anyone know how to grant permission for python to open the file?</p>
<p>I've tried:</p>
<pre><code>import subprocess
subprocess.call(['C:\\Users\\Edvin\\AppData\\Roaming\\Microsoft\\Windows'
'\\Start Menu\\Programs\\Accessories\\Notepad.exe'],
'C:\\Users\\Edvin\\Desktop\\Example.txt')
</code></pre>
<p>but this comes up with <code>TypeError: bufsize must be an integer</code> error.</p>
| 0 | 2016-10-12T16:33:49Z | 40,003,957 | <p>The thing is that you're trying to launch your desktop as a program. With a text file as an argument.</p>
<p>This is not allowed because you're not allowed to execute the desktop (because it can't be executed).</p>
<pre><code>subprocess.call(["command here", "arguments here"])
</code></pre>
<p>if it's an <code>exe</code> use</p>
<pre><code>subprocess.call(['C:\\...\\program.exe', 'argument'])
</code></pre>
<p>if it's a python script use</p>
<pre><code>execfile('file.py')
</code></pre>
| 2 | 2016-10-12T16:41:51Z | [
"python",
"windows",
"permissions",
"subprocess",
"python-3.5"
] |
How to compile python with PyInstaller in Linux | 40,003,821 | <p>I am using <code>Python 3.5.2</code> , <code>PyQt 5.7</code> , <code>PyInstaller 3.2</code> and I'm in Linux</p>
<p>I can compile file.py with : <code>pyinstaller file.py</code></p>
<p>but when I run the binary file in Build folder it returns:</p>
<p><code>Error loading Python lib '/home/arash/build/file/libpython3.5m.so.1.0': /home/arash/build/file/libpython3.5m.so.1.0: cannot open shared object file: No such file or directory</code></p>
<p>Where is the python library (.so file) to copy inside binary file or PyInstaller flag for copy library file?</p>
| 2 | 2016-10-12T16:34:24Z | 40,005,521 | <p>If this is just about the location of that .so; see here:</p>
<pre><code>/usr/lib/python3.5 $ find . -name "*.so" | grep libpython
./config-3.5m-x86_64-linux-gnu/libpython3.5.so
./config-3.5m-x86_64-linux-gnu/libpython3.5m.so
</code></pre>
<p>Another way to find it would be by running </p>
<pre><code>> locate libpython3.5m.so
/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/libpython3.5m.so
</code></pre>
<p>...</p>
<p>In other words: it should be part of the python3.5 installation of your system. Probably you can just copy it from there for further experiments.</p>
| 1 | 2016-10-12T18:09:24Z | [
"python",
"linux",
"python-3.x",
"pyqt",
"pyinstaller"
] |
How to compile python with PyInstaller in Linux | 40,003,821 | <p>I am using <code>Python 3.5.2</code> , <code>PyQt 5.7</code> , <code>PyInstaller 3.2</code> and I'm in Linux</p>
<p>I can compile file.py with : <code>pyinstaller file.py</code></p>
<p>but when I run the binary file in Build folder it returns:</p>
<p><code>Error loading Python lib '/home/arash/build/file/libpython3.5m.so.1.0': /home/arash/build/file/libpython3.5m.so.1.0: cannot open shared object file: No such file or directory</code></p>
<p>Where is the python library (.so file) to copy inside binary file or PyInstaller flag for copy library file?</p>
| 2 | 2016-10-12T16:34:24Z | 40,005,728 | <p>the binary file is in the <code>dist</code> folder not <code>build</code> folder</p>
| 0 | 2016-10-12T18:21:31Z | [
"python",
"linux",
"python-3.x",
"pyqt",
"pyinstaller"
] |
quicksort algorithm as WIKIPEDIA says in python | 40,003,839 | <p>In Wikipedia, there is a pseudo-code of quicksort algorithm:</p>
<p>So I tried to implement in python, but it does not sort anything.</p>
<pre><code>def partition(A,lo,hi):
pivot = A[hi]
i=lo
#Swap
for j in range(lo,len(A)-1):
if (A[j] <= pivot):
val=A[i]
A[i]=A[j]
A[j]=val
i=i+1
val=A[i]
A[i]=A[hi]
A[hi]=val
return(A,i)
def quicksort(A,lo,hi):
if (lo<hi):
[A,p]=partition(A,lo,hi)
quicksort(A,lo,p-1)
quicksort(A,p+1,hi)
A=[5,3,2,6,8,9,1]
A=quicksort(A, 0, len(A)-1)
print(A)
</code></pre>
<p>ORIGINAL: It does not throw an error so I do not no where I made a mistake.</p>
<p>UPDATE: It now goes into infinite recursion.</p>
| 0 | 2016-10-12T16:35:32Z | 40,003,950 | <p>It doesn't throw an error or print anything because there is no main program to run anything. You indented what should be the main program, so that is now part of the <strong>quicksort</strong> function.</p>
<p>Also, this code <em>does</em> throw an error, because you left a comment in what you posted. I'll clean up the code and edit your posting.</p>
<hr>
<p>I corrected several code errors:</p>
<ol>
<li>Removed "enter code here" text, which caused an obvious compilation error.</li>
<li>Corrected indentation, so that the last three lines are now your main program.</li>
<li>Corrected the main-program call: <strong>quicksort</strong> takes the bounds (subscripts) of the array, but you were passing in the array elements themselves.</li>
</ol>
<p>That fixes your given problem. You now have infinite recursion due to not handling the return values properly. Also, your main program destroys the sorted array, since <strong>quicksort</strong> doesn't return anything. The final print statement will give <strong>None</strong> as its result.</p>
<hr>
<p>You haven't quite implemented the given algorithm. The most important problem is the <strong>for</strong> loop's upper limit.</p>
<ul>
<li>Python loops do <em>not</em> include the end value. Your given loop will run <strong>j</strong> through the values <strong>lo</strong> through <strong>len(A)-2</strong>, so you'll never treat the last value of the list.</li>
<li>The upper limit given in Wikipedia is <strong>hi</strong>, not the list end.</li>
</ul>
<p>Fix those, and you'll be close to a solution.</p>
<p>Also, I strongly recommend that you stick in a couple of tracing <strong>print</strong> statements, so you can see follow how the program works. For instance, as the first statement of each function, print the function name and the input parameters.</p>
<p>Why do you return A from the function? The Wikipedia algorithm doesn't do that, and it's not necessary: you altered the list in place.</p>
<p>Since you already know about multiple assignment, note that there's an easier way to swap two values:</p>
<pre><code>a, b = b, a
</code></pre>
<p>Does this get you moving through the current problems, enough to get you back on the learning track you want?</p>
| 2 | 2016-10-12T16:41:35Z | [
"python",
"algorithm",
"quicksort",
"wikipedia"
] |
Find characters in a text | 40,003,849 | <p>I want to create a python script which finds an expression in a text.
If it succeeds, then print 'expression found'.</p>
<p>My text file is named "file_id_ascii"; it comes from a link named "clinical_file_link".</p>
<pre><code> import csv
import sys
import io
file_id_ascii =
io.open(clinical_file_link, 'r',
encoding='us-ascii', errors='ignore')
acc = 'http://tcga.nci/bcr/xml/clinical/acc/'
if acc in file_id_ascii:
print('expression found')
</code></pre>
<p>That code doesn't work...what's wrong?</p>
| 0 | 2016-10-12T16:35:53Z | 40,003,967 | <pre><code>if 'http://tcga.nci/bcr/xml/clinical/acc/' \
in open('clinical_file_link.txt').read():
print "true"
</code></pre>
<p>... works if your file has small content</p>
| 2 | 2016-10-12T16:42:19Z | [
"python",
"xml",
"csv",
"parsing"
] |
Find characters in a text | 40,003,849 | <p>I want to create a python script which finds an expression in a text.
If it succeeds, then print 'expression found'.</p>
<p>My text file is named "file_id_ascii"; it comes from a link named "clinical_file_link".</p>
<pre><code> import csv
import sys
import io
file_id_ascii =
io.open(clinical_file_link, 'r',
encoding='us-ascii', errors='ignore')
acc = 'http://tcga.nci/bcr/xml/clinical/acc/'
if acc in file_id_ascii:
print('expression found')
</code></pre>
<p>That code doesn't work...what's wrong?</p>
| 0 | 2016-10-12T16:35:53Z | 40,003,979 | <p>It doesn't work because you are not parsing the XML.
Check this <a href="http://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python">thread</a> for more info about parsing XML.</p>
<p>If it is indeed a text file you might edit it like this:</p>
<pre><code>if acc in open(clinical_file_link.txt).read():
print('expression FOUND')
</code></pre>
<p>EDIT: This solution wont work if files are big. Try this one:</p>
<pre><code>with open('clinical_file_link.txt') as f:
found = False
for line in f:
if acc in line:
print('found')
found = True
if not found:
print('The string cannot be found!')
</code></pre>
| 1 | 2016-10-12T16:43:16Z | [
"python",
"xml",
"csv",
"parsing"
] |
How to take set multiple variables using argparse, both required and optional variables? | 40,003,858 | <p>How do you deal with multiple inputs via <code>argparse</code>, especially when there are default inputs and optional inputs?</p>
<p>Within my script <code>file.py</code>, users must input two parameters, which I have in a list</p>
<pre><code>parameters_list = [parameter1, parameter2, parameter3]
parameter1 = "" # normally in the script, I would set these
parameter2 = ""
parameter3 = ""
</code></pre>
<p>The third parameter <code>parameter3</code> is a default parameter.</p>
<p>Now, to my mind, users could include the flags at run time <code>python file.py --parameters = 'parameter1', 'parameter2'</code></p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument('parameters', nargs = '*', help = 'input program parameters')
params = parser.parse_args()
</code></pre>
<p>However</p>
<ol>
<li><p>This doesn't parse how users have input the parameters, like:</p>
<p><code>--parameters = 'parameter1', 'parameter2'</code></p></li>
<li><p>How do you deal with the default parameter <code>parameter3</code>?</p>
<p>At the moment, this will throw at error, as the variable <code>parameter3</code> has been defined in the script, but isn't defined by <code>argparse</code>.</p></li>
</ol>
| 0 | 2016-10-12T16:36:52Z | 40,004,040 | <p>One method is to parse out the parameters as comma separated values.</p>
<pre><code>import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--parameters',nargs='*',help="input program parameters")
args,unknown = parser.parse_known_args()
if(unknown):
print("Do not use spaces!")
sys.exit()
parameters = args.parameters
parameters = parameters[0].split(',')
parameter1 = parameters[0]
parameter2 = parameters[1]
parameter3 = "your_value" if len(parameters) < 3 else params[2]
</code></pre>
<p>Of course the user would have to input the params as (no spaces):</p>
<pre><code>--parameters='parameter1','parameter2','parameter3'
</code></pre>
<p>Also note that to use <code>--parameters</code> the argument you add to the parser must match.</p>
| 1 | 2016-10-12T16:46:06Z | [
"python",
"argparse",
"optional"
] |
How to take set multiple variables using argparse, both required and optional variables? | 40,003,858 | <p>How do you deal with multiple inputs via <code>argparse</code>, especially when there are default inputs and optional inputs?</p>
<p>Within my script <code>file.py</code>, users must input two parameters, which I have in a list</p>
<pre><code>parameters_list = [parameter1, parameter2, parameter3]
parameter1 = "" # normally in the script, I would set these
parameter2 = ""
parameter3 = ""
</code></pre>
<p>The third parameter <code>parameter3</code> is a default parameter.</p>
<p>Now, to my mind, users could include the flags at run time <code>python file.py --parameters = 'parameter1', 'parameter2'</code></p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument('parameters', nargs = '*', help = 'input program parameters')
params = parser.parse_args()
</code></pre>
<p>However</p>
<ol>
<li><p>This doesn't parse how users have input the parameters, like:</p>
<p><code>--parameters = 'parameter1', 'parameter2'</code></p></li>
<li><p>How do you deal with the default parameter <code>parameter3</code>?</p>
<p>At the moment, this will throw at error, as the variable <code>parameter3</code> has been defined in the script, but isn't defined by <code>argparse</code>.</p></li>
</ol>
| 0 | 2016-10-12T16:36:52Z | 40,004,305 | <p>I would just define separate parameters for each:</p>
<pre><code>p = ArgumentParser()
p.add_argument("arg1")
p.add_argument("arg2")
p.add_argument("arg3", default=5, nargs='?')
</code></pre>
<p>and require calls like</p>
<pre><code>$ python file.py 3 2
$ python file.py 3 2 6
</code></pre>
| 2 | 2016-10-12T17:00:01Z | [
"python",
"argparse",
"optional"
] |
Can't extract individual fields from scapy packet | 40,003,923 | <p>I've been experimenting with scapy and Python 3 and I want to use the ARP protocol to find mac addresses of computers on the network. This is my code:</p>
<pre><code>>>> packet = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=IP_OF_HOST))
</code></pre>
<p>Then to extract the data from this packet I used the following line:</p>
<pre><code>>>> packet[0][Ether].src
</code></pre>
<p>However for some reason this produces the error:</p>
<pre class="lang-none prettyprint-override"><code>AttributeError: 'list' object has no attribute 'src'
</code></pre>
<p>Every tutorial I read used the method I used for extracting field data, why wouldn't it work for me?</p>
| 0 | 2016-10-12T16:39:55Z | 40,005,821 | <p>It has to do with the difference between the functions srp(), and srp1() (Those being for network layer 2, for layer 3 you would use sr() and sr1() respectively).</p>
<p>srp() sends the packet, and saves all packets, whether they are answered or not. To get say the source MAC address I'd do this:</p>
<pre><code>answered_packets, unanswered_packets = packet
for packet_i_sent, packet_i_received in answered_packets:
print(packet_i_received.src)
</code></pre>
<p>srp1() sends a packet, and waits for one answer, and saves only the reply packet. This means the format is different, since you don't have to deal with the unanswered packets, and my previous method would work:</p>
<pre><code>print(packet.src) #The [Ether] part doesn't matter,
#that's just for looking fancier when you print(packet)
</code></pre>
<p>So basically I used the command srp() and tried to decode the reply like I was using srp1()</p>
| 0 | 2016-10-12T18:26:37Z | [
"python",
"python-3.x",
"attributes",
"scapy",
"arp"
] |
Finding the difference image between multiple images | 40,003,929 | <p>I've taken multiple screenshots from a webcam on my campus and I have taken the average of the 300 screenshots and it gives me an image with many ghostly people. I am trying to figure out how to get the difference image between the images so that I can change the differences to red to show is more clearly. I just need some help getting an idea of where to start. I know I need to subtract the first image by the second, and then that image by the third, but I'm not sure of a way to do that in Python.</p>
<pre><code>import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np
files=os.listdir('./images')
print files
image=[]
for file in files:
img=Image.open('./images/'+file)
img=np.float32(img)
image.append(img)
avg_img=[]
for img in image:
try:
avg_img+=img
except:
avg_img=img
avg_img/=len(image)
avg_img=np.clip(avg_img, 0, 255)
avg_img=np.uint8(avg_img)
mplot.imshow(avg_img)
mplot.show()
</code></pre>
| 1 | 2016-10-12T16:40:06Z | 40,004,731 | <p>There are tons of ways to do this, but I will first keep closest to what you currently have. Then I will show a more compact way.</p>
<pre><code>import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np
files=os.listdir('./images')
print files
image=[]
for file in files:
img=Image.open('./images/'+file)
img=np.float32(img)
image.append(img)
avg_img=np.zeros_like(image[0])
for img in image:
avg_img += img
avg_img/=len(image)
avg_img=np.clip(avg_img, 0, 255)
avg_img=np.uint8(avg_img)
mplot.imshow(avg_img)
mplot.show()
# get series of differences
differences = []
for img0, img1 in zip(image[:-1], image[1:]):
differences.append(img1 - img0)
</code></pre>
<p>Here is an easier way using numpy.</p>
<pre><code>import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np
files = os.listdir('./images')
print files
img = Image.open(os.path.join('./images', files[0])
image_stack = np.ndarray((len(files), img.shape[0], img.shape[1], 3), dtype=np.float32)
for i, file in enumerate(files):
img = Image.open('./images/'+file)
img = np.float32(img)
image_stack[i] = img
avg_img = np.mean(image_stack, axis=0)
avg_img = np.clip(avg_img, 0, 255)
avg_img = avg_img.astype(np.uint8)
mplot.imshow(avg_img)
mplot.show()
difference_stack = image_stack[1:] - image_stack[:-1]
</code></pre>
<p>I doubt your webcam image stores floats, but maybe that is the case.</p>
| 1 | 2016-10-12T17:24:00Z | [
"python",
"image",
"numpy",
"difference"
] |
Wrong Behaviour doing tests on Django | 40,003,985 | <p>I'm having problems to do test on Django. I've been reading the documentation <a href="https://docs.djangoproject.com/en/1.10/topics/testing/tools/#testing-responses" rel="nofollow">of the responses</a> and I can't do the same as they explain on the documentation.</p>
<p>When I get the response, I only have access to <code>response.status_code</code> and can't access to <code>context</code> or <code>redirect_chain</code> when I write <code>response.(and now PyCharm shows all available options)</code>.</p>
<p>I've checked on <code>settings.py</code> and I've <code>'BACKEND': 'django.template.backends.django.DjangoTemplates'</code> to be sure that I'm using Django templates so I don't know why don't work the test. I need configure something?</p>
<p>The code of the test I'm trying to do it's:</p>
<pre><code>from django.test import TestCase
from django.test.client import Client
class Test(TestCase):
def testLogin(self):
client = Client()
headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'}
data = {}
response = self.client.post('/login/', headers=headers, data=data, secure=True, follow=True)
assert (response.status_code == 200)
# self.assertRedirects(response, '/menu/', status_code=301, target_status_code=200)
</code></pre>
<p>I'm not using Django authentication, the login form sends the data to an IDP and if the IDP sends with a correct answer, the "login" it's successful:</p>
<pre><code>def login(request):
logout(request)
message = None
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
headers = {'X-OpenAM-Username': username, 'X-OpenAM-Password': password, 'Content-Type': 'application/json'}
data = {}
req = requests.post('http://openam.idp.com:8090/openamIDP/json/authenticate', headers=headers, params=data)
if req.status_code == 200:
respJson = json.loads(req.content)
tokenIdJson = respJson['tokenId']
request.session['tokenId'] = tokenIdJson
return render_to_response('menu/menu.html', request)
elif req.status_code == 401:
message = "Invalid username and/or password. Please, try again"
else:
form = LoginForm()
return render_to_response('registration/login.html', {'message': message, 'form': form},
context_instance=RequestContext(request))
</code></pre>
<p>The redirect assert it's commented because now it fails, when I do the debug I see an empty <code>redirect_chain</code>. I don't understand why happens this because running the web everything works, all views redirect as expected.</p>
<p>Why I only can check <code>status_code</code>? I'm doing something wrong when I redirect after a successful login that on a normal use it works but on the test not?</p>
<p>Thanks.</p>
| 0 | 2016-10-12T16:43:36Z | 40,004,116 | <p>The remote authentication url expects the credentials as headers, but your local login view expects them as <code>POST</code> data. Your test passes the credentials as headers to your local view.</p>
<p>As a result, the form is passed an empty dictionary (<code>request.POST</code> contains no actual data), and the form is invalid. You get an empty form as a response, without any redirects. </p>
<p>You have to simply pass the credentials as post data to your local view:</p>
<pre><code>def testLogin(self):
client = Client()
data = {'username': 'user', 'password': 'password'}
response = self.client.post('/login/', data=data, secure=True, follow=True)
assert (response.status_code == 200)
self.assertRedirects(response, '/menu/', status_code=301, target_status_code=200)
</code></pre>
| 1 | 2016-10-12T16:50:04Z | [
"python",
"django",
"django-testing"
] |
pyad: Installs fine, but says it can't find adbase | 40,004,147 | <p>This has me pretty confused. I've installed pyad using pip and everything seems fine:</p>
<pre><code>C:\WINDOWS\system32>pip install pyad
Collecting pyad
Using cached pyad-0.5.16.tar.gz
Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\python35\lib\site-packages (from pyad)
Requirement already satisfied (use --upgrade to upgrade): pywin32 in c:\python35\lib\site-packages (from pyad)
Installing collected packages: pyad
Running setup.py install for pyad ... done
Successfully installed pyad-0.5.16
</code></pre>
<p>But when I try to use it, I get an error that complains about not finding adbase:</p>
<pre><code>C:\WINDOWS\system32>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyad import aduser
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\site-packages\pyad\__init__.py", line 1, in <module>
from adbase import set_defaults as pyad_setdefaults
ImportError: No module named 'adbase'
>>> import pyad
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\site-packages\pyad\__init__.py", line 1, in <module>
from adbase import set_defaults as pyad_setdefaults
ImportError: No module named 'adbase'
</code></pre>
<p>This is odd, because if I try to uninstall pyad or if I check the site-packages directory, adbase is definitely there:</p>
<pre><code>C:\WINDOWS\system32>pip uninstall pyad
Uninstalling pyad-0.5.16:
c:\python35\lib\site-packages\pyad-0.5.16-py3.5.egg-info
c:\python35\lib\site-packages\pyad\__init__.py
c:\python35\lib\site-packages\pyad\__pycache__\__init__.cpython-35.pyc
c:\python35\lib\site-packages\pyad\__pycache__\adcomputer.cpython-35.pyc
c:\python35\lib\site-packages\pyad\__pycache__\addomain.cpython-35.pyc
c:\python35\lib\site-packages\pyad\__pycache__\adgroup.cpython-35.pyc
c:\python35\lib\site-packages\pyad\__pycache__\adquery.cpython-35.pyc
c:\python35\lib\site-packages\pyad\__pycache__\adsearch.cpython-35.pyc
c:\python35\lib\site-packages\pyad\__pycache__\pyad.cpython-35.pyc
c:\python35\lib\site-packages\pyad\adbase.py
c:\python35\lib\site-packages\pyad\adcomputer.py
c:\python35\lib\site-packages\pyad\adcontainer.py
c:\python35\lib\site-packages\pyad\addomain.py
c:\python35\lib\site-packages\pyad\adgroup.py
c:\python35\lib\site-packages\pyad\adobject.py
c:\python35\lib\site-packages\pyad\adquery.py
c:\python35\lib\site-packages\pyad\adsearch.py
c:\python35\lib\site-packages\pyad\aduser.py
c:\python35\lib\site-packages\pyad\pyad.py
c:\python35\lib\site-packages\pyad\pyadconstants.py
c:\python35\lib\site-packages\pyad\pyadexceptions.py
c:\python35\lib\site-packages\pyad\pyadutils.py
Proceed (y/n)?
</code></pre>
<p><a href="https://i.stack.imgur.com/y7Yg2.png" rel="nofollow">pyad directory contents</a></p>
<p>I'm really not sure what else to try. I've run everything under an elevated command prompt, so it's not a permissions issue. I even tried downloading pyad and installing it using setup.py, but I had the same problem with that. adbase is <em>definitely</em> there, and I can't figure out why Python isn't finding it.</p>
| 0 | 2016-10-12T16:51:51Z | 40,004,427 | <p>That's a bug on pyad part. They're importing adbase as if it were a standalone module or package, and that's why it does not work. The proper way to fix this would be to change the import to an absolute import <code>from pyad.adbase import ...</code> or relative <code>from .adbase import ...</code>.</p>
<p>However, if you check the <a href="https://github.com/zakird/pyad/blob/master/pyad/__init__.py" rel="nofollow"><code>master</code></a> branch on Github, you will see that they have actually fixed it. But that's not all, if you check their <a href="https://github.com/zakird/pyad/blob/master/setup.py#L13" rel="nofollow"><code>setup.py</code></a> you'll see that the version on Github is <code>0.5.15</code>, while the last version on PyPI, which is the one you have installed, is <code>0.5.16</code>. Weird.</p>
<p>I suggest you to install the package directly from Github, and that should take care of the problem. To do that, first uninstall <code>pyad</code> and then run</p>
<pre><code>pip install https://github.com/zakird/pyad/archive/master.zip
</code></pre>
| 0 | 2016-10-12T17:06:30Z | [
"python",
"pip"
] |
Getting started with Regular Expressions | 40,004,211 | <p>I'm trying to simply play with regular expressions in the console, but I can't.</p>
<p>What am I doing wrong? I'm on python 3.5 I think.</p>
<p>First I tried to use <code>.replace</code> on a string object. </p>
<p>then I imported the <code>re</code> module, but even that didn't work with <code>re.sub</code></p>
<p>I'm basically at a loss. I just want to experiment with regex so I can learn how to use them. </p>
<p>Can you help me get started?</p>
<p>The code that hasn't worked for me is this:</p>
<pre><code>m = "555.555.5555"
mm = m.str.replace(r"'.'","helloworld")
mm
>> 555.555.5555
import re
mm = re.sub(r"'.'","helloworld",m)
mm
>> 555.555.5555
</code></pre>
<p>p.s. </p>
<p>I have some code here that I was trying to emulate</p>
<pre><code>df.CODE.str.replace(r"\A'(E?[V\d]\d\d)(\d*).*", r'\1.\2')
</code></pre>
<p>so that actually works, but I don't understand why. everything I read about says replace doesn't use regex, that you're supposed to use the <code>re</code> module but anyway. I don't understand why it works.</p>
| -1 | 2016-10-12T16:54:54Z | 40,004,444 | <p>The problem is that you are trying to use regular expressions in string replaces - string replace does <strong>not</strong> support regular expressions for that you need to import and use the re or regex library.</p>
<pre><code>>>> import re
>>> m = "555.555.5555"
>>> >>> mm = re.sub(r"(\d\d)\.(\d)?", m, "helloworld")
>>> mm
'helloworld'
</code></pre>
| 2 | 2016-10-12T17:07:30Z | [
"python",
"regex",
"python-3.x",
"console"
] |
Is there python for 64bit instead of 32bit? | 40,004,277 | <p>Is there python for 64bit instead of 32bit?</p>
<p>Can't find it on downloads page on python.org</p>
<p>Thankyou</p>
| -6 | 2016-10-12T16:58:39Z | 40,004,338 | <p>Take a few steps further back, it's right in front of your nose so that's why you can't see it.</p>
<p><a href="https://www.python.org/downloads/release/python-352/" rel="nofollow">https://www.python.org/downloads/release/python-352/</a></p>
| 0 | 2016-10-12T17:01:50Z | [
"python"
] |
Is there python for 64bit instead of 32bit? | 40,004,277 | <p>Is there python for 64bit instead of 32bit?</p>
<p>Can't find it on downloads page on python.org</p>
<p>Thankyou</p>
| -6 | 2016-10-12T16:58:39Z | 40,004,383 | <p>Check <a href="https://www.python.org/downloads/release/python-352/" rel="nofollow">THIS</a> page. Depends on the OS as @birryree mentioned. There ARE 64bit editions</p>
| 1 | 2016-10-12T17:04:23Z | [
"python"
] |
Is there python for 64bit instead of 32bit? | 40,004,277 | <p>Is there python for 64bit instead of 32bit?</p>
<p>Can't find it on downloads page on python.org</p>
<p>Thankyou</p>
| -6 | 2016-10-12T16:58:39Z | 40,004,398 | <p>Check out the <a href="https://www.python.org/downloads/windows/" rel="nofollow">python downloads webpage for Windows</a>. It has the latest versions of Python as x86 and x86-64, which is the 64-bit version. </p>
<p>If you're looking for the Mac version, just look <a href="https://www.python.org/downloads/mac-osx/" rel="nofollow">for mentions of a 64-bit/32-bit installer</a>.</p>
| 0 | 2016-10-12T17:05:06Z | [
"python"
] |
Is there python for 64bit instead of 32bit? | 40,004,277 | <p>Is there python for 64bit instead of 32bit?</p>
<p>Can't find it on downloads page on python.org</p>
<p>Thankyou</p>
| -6 | 2016-10-12T16:58:39Z | 40,004,433 | <p>If you are on windows, choose the x86-<strong>64</strong> option for your desired release on this page.</p>
<p><a href="https://www.python.org/downloads/windows/" rel="nofollow">https://www.python.org/downloads/windows/</a> </p>
| 1 | 2016-10-12T17:06:59Z | [
"python"
] |
Is there any way to cancel UrlRequest in Kivy? | 40,004,431 | <p>Is there any way to cancel UrlRequest in Kivy?</p>
<pre><code>def got_url(req, result):
print(result)
req = UrlRequest('http://httpbin.org/delay/2', got_url) # Request lasts 2 seconds
def my_callback(dt):
print('Request cancelled.')
# sort of req.cancel()
Clock.schedule_once(my_callback, 1) # But some event happens after 1 sec. and I want to cancel request
</code></pre>
<p>This is just example: I know about timeout, I want to cancel request on some arbitrary event. </p>
| 2 | 2016-10-12T17:06:53Z | 40,030,697 | <p>Afaik there's no other way except <code>UrlRequest.timeout</code>, which could translate to politely wait and close any harmful stuff safely. It uses <code>Thread</code> which may and may not be dangerous. Even more if e.g. packaged into exe or other form of binary where it could create a lock because something broke. I think the way you would like it to use would only trigger problems.</p>
<p>There's another way using <code>on_*</code> events and as small as possible <code>timeout</code>, which can trigger your function.</p>
<p>Example: set timeout for 1s if you want to cancel it after that amount of time and let the UrlRequest ping you when it does so, which is</p>
<ol>
<li>safer to use than stopping it at random place</li>
<li>less amount of lines for reinventing the wheel</li>
</ol>
| 1 | 2016-10-13T20:48:33Z | [
"python",
"kivy"
] |
is it possible to list all blocked tornado coroutines | 40,004,443 | <p>I have a "gateway" app written in <code>tornado</code> using <code>@tornado.gen.coroutine</code> to transfer information from one handler to another. I'm trying to do some debugging/status testing. What I'd like to be able to do is enumerate all of the currently blocked/waiting coroutines that are live at a given moment. Is this information accessible somewhere in tornado?</p>
| 2 | 2016-10-12T17:07:29Z | 40,005,951 | <p>You talk about ioloop <code>_handlers</code> dict maybe. Try to add this in periodic callback:</p>
<pre><code>def print_current_handlers():
io_loop = ioloop.IOLoop.current()
print io_loop._handlers
</code></pre>
<p><strong>update</strong>: I've checked source code and now think that there is no simple way to trace current running gen.corouitines, A. Jesse Jiryu Davis is right!</p>
<p>But you can trace all "async" calls (yields) from coroutines - each yield from generator go into <code>IOLoop.add_callback</code> (<a href="http://www.tornadoweb.org/en/stable/ioloop.html#callbacks-and-timeouts" rel="nofollow">http://www.tornadoweb.org/en/stable/ioloop.html#callbacks-and-timeouts</a>)</p>
<p>So, by examining <code>io_loop._callbacks</code> you can see what yields are in ioloop right now.</p>
<p>Many interesting stuff is here :) <a href="https://github.com/tornadoweb/tornado/blob/master/tornado/gen.py" rel="nofollow">https://github.com/tornadoweb/tornado/blob/master/tornado/gen.py</a></p>
| 2 | 2016-10-12T18:34:44Z | [
"python",
"tornado"
] |
is it possible to list all blocked tornado coroutines | 40,004,443 | <p>I have a "gateway" app written in <code>tornado</code> using <code>@tornado.gen.coroutine</code> to transfer information from one handler to another. I'm trying to do some debugging/status testing. What I'd like to be able to do is enumerate all of the currently blocked/waiting coroutines that are live at a given moment. Is this information accessible somewhere in tornado?</p>
| 2 | 2016-10-12T17:07:29Z | 40,006,626 | <p>No there isn't, but you could perhaps create your own decorator that wraps gen.coroutine, then updates a data structure when the coroutine begins.</p>
<pre><code>import weakref
import functools
from tornado import gen
from tornado.ioloop import IOLoop
all_coroutines = weakref.WeakKeyDictionary()
def tracked_coroutine(fn):
coro = gen.coroutine(fn)
@functools.wraps(coro)
def start(*args, **kwargs):
future = coro(*args, **kwargs)
all_coroutines[future] = str(fn)
return future
return start
@tracked_coroutine
def five_second_coroutine():
yield gen.sleep(5)
@tracked_coroutine
def ten_second_coroutine():
yield gen.sleep(10)
@gen.coroutine
def tracker():
while True:
running = list(all_coroutines.values())
print(running)
yield gen.sleep(1)
loop = IOLoop.current()
loop.spawn_callback(tracker)
loop.spawn_callback(five_second_coroutine)
loop.spawn_callback(ten_second_coroutine)
loop.start()
</code></pre>
<p>If you run this script for a few seconds you'll see two active coroutines, then one, then none.</p>
<p>Note the <a href="https://docs.python.org/2.7/library/weakref.html#weakref.WeakKeyDictionary" rel="nofollow">warning in the docs about the dictionary changing size</a>, you should catch "RuntimeError" in "tracker" to deal with that problem.</p>
<p>This is a bit complex, you might get all you need much more simply by turning on Tornado's logging and using <a href="http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.set_blocking_log_threshold" rel="nofollow">set_blocking_log_threshold</a>.</p>
| 1 | 2016-10-12T19:14:40Z | [
"python",
"tornado"
] |
python changefig() takes exactly 2 arguments (1 given) | 40,004,506 | <p>I am writing a program which is supposed to give me data of a chart when i click certain buttons.
So this is the program as far as I am right now, I still have to connect the last 4 buttons but the first one works, but now there is another problem: I used to have a chart displayed as i clicked on "One Plot" but since I activated "First Button", the chart does not appear anymore due to the in the title mentioned problem. This is the script:</p>
<pre><code>class Main(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setupUi(self)
self.fig_dict = {}
self.mplfigs.itemClicked.connect(self.changefig)
self.button1.setText("First Point")
self.button1.clicked.connect(self.onClickButton1)
self.dialogbutton1 = PopUp(self)
fig = Figure()
self.addmpl(fig)
@QtCore.pyqtSlot()
def changefig(self, item):
text = item.text()
self.rmmpl()
self.addmpl(self.fig_dict[str(text)])
def addfig(self, name, fig):
self.fig_dict[name] = fig
self.mplfigs.addItem(name)
def addmpl(self, fig):
self.canvas = FigureCanvas(fig)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,
self.mplwindow, coordinates=True)
self.mplvl.addWidget(self.toolbar)
def onClickButton1(self):
""" When button 1 is clicked I do the following """
print "does nothing now."
self.dialogbutton1.exec_()
def rmmpl(self,):
self.mplvl.removeWidget(self.canvas)
self.canvas.close()
self.mplvl.removeWidget(self.toolbar)
self.toolbar.close()
</code></pre>
<p>class PopUp(QtGui.QDialog):
def <strong>init</strong>(self, parent=None):
super(PopUp, self).<strong>init</strong>(parent)</p>
<pre><code> self.buttonBox = QtGui.QDialogButtonBox(self)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.textBrowser = QtGui.QTextBrowser(self)
self.textBrowser.append("x - Coordinate = 0 y - Coordinate = 0.031451")
self.verticalLayout = QtGui.QVBoxLayout(self)
self.verticalLayout.addWidget(self.textBrowser)
self.verticalLayout.addWidget(self.buttonBox)
</code></pre>
<p>if <strong>name</strong> == '<strong>main</strong>':
import sys
from PyQt4 import QtGui
import numpy as np</p>
<pre><code>fig1 = Figure()
ax1f1 = fig1.add_subplot(111)
ax1f1.plot(np.random.rand(5))
app = QtGui.QApplication(sys.argv)
main = Main()
main.addfig('One plot', fig1)
print main.fig_dict
main.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-10-12T17:11:03Z | 40,005,010 | <p>In <code>class Main</code>, you are calling <code>changefig</code> function as <code>self.mplfigs.itemClicked.connect(self.changefig)</code>.</p>
<p>But function definition of <code>changefig</code> is <code>def changefig(self, item):</code> which expects two arguments - <code>self</code> and <code>item</code>.</p>
<p>When you called changefig - <code>self.mplfigs.itemClicked.connect(self.changefig)</code>, only self is passed. But item is not passed. </p>
<p>That's why you are getting that error.</p>
<p>It should be <code>self.mplfigs.itemClicked.connect(self.changefig(item))</code></p>
| 0 | 2016-10-12T17:40:42Z | [
"python",
"arguments"
] |
Why does bytearray_obj.extend(bytes) differ from bytearray_obj += bytes? | 40,004,517 | <p>Just saw (and enjoyed) the video of Brandon Rhodes talking on PyCon 2015 about bytearrays.</p>
<p>He said that <code>.extend</code> method is slow, but <code>+=</code> operation is implemented differently and is much more efficient. Yes, indeed:</p>
<pre><code>>>> timeit.timeit(setup='ba=bytearray()', stmt='ba.extend(b"xyz123")', number=1000000)
0.19515220914036036
>>> timeit.timeit(setup='ba=bytearray()', stmt='ba += b"xyz123"', number=1000000)
0.09053478296846151
</code></pre>
<p>What is the reason of having two ways of extending a bytearray? Are they performing exactly the same task? If not, what is the difference? Which one should be used when?</p>
| 3 | 2016-10-12T17:11:48Z | 40,005,377 | <blockquote>
<p>What is the reason of having two ways of extending a bytearray?</p>
</blockquote>
<ul>
<li>An operator is not chainable like function calls, whereas a method is.</li>
<li>The <code>+=</code> operator cannot be used with nonlocal variables.</li>
<li>The <code>+=</code> is slightly faster</li>
<li><code>.extend()</code> may/might/could sometimes possibly be more readable</li>
</ul>
<blockquote>
<p>Are they performing exactly the same task?</p>
</blockquote>
<p>Depends on how you look at it. The implementation is not the same, but the result usually is. For a bunch of examples and explanations, maybe try the SO search, and for example this question: <a href="http://stackoverflow.com/questions/3653298/concatenating-two-lists-difference-between-and-extend">Concatenating two lists - difference between '+=' and extend()</a></p>
<blockquote>
<p>Which one should be used when?</p>
</blockquote>
<p>If you care about the small performance difference, use the operator when you can. Other than that, just use whichever you like to look at, of course given the restrictions I mentioned above.</p>
<blockquote>
<p>But the main question is why += and .extend do not share the same internal function to do the actual work of extending a bytearray.</p>
</blockquote>
<p>Because one is faster but has limitations, so we need the other for the cases where we do have the limitations.</p>
<p><br>
<strong>Bonus</strong>:</p>
<p>The increment operator might cause some funny business with tuples:</p>
<blockquote>
<p>if you put a list in a tuple and use the += operator to extend the list, the increment succeeds and you get a TypeError</p>
</blockquote>
<p>Source: <a href="https://emptysqua.re/blog/python-increment-is-weird-part-ii/" rel="nofollow">https://emptysqua.re/blog/python-increment-is-weird-part-ii/</a></p>
| 0 | 2016-10-12T18:01:14Z | [
"python"
] |
Python Pandas: Group by and count distinct value over all columns? | 40,004,595 | <p>I have df</p>
<pre><code> column1 column2 column3 column4
0 name True True NaN
1 name NaN True NaN
2 name1 NaN True True
3 name1 True True True
</code></pre>
<p>and I would like to Group by and count distinct value over all columnsI am trying :</p>
<pre><code>df.groupby('column1').nunique()
</code></pre>
<p>but I am receiving this error. </p>
<blockquote>
<p>AttributeError: 'DataFrameGroupBy' object has no attribute 'nunique'</p>
</blockquote>
<p>Anybody have a suggestion?</p>
| 0 | 2016-10-12T17:16:12Z | 40,004,637 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for <code>Series</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>Series.groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>SeriesGroupBy.nunique</code></a>:</p>
<pre><code>df1 = df.set_index('column1').stack()
print (df1.groupby(level=[0,1]).nunique(dropna=False).unstack())
</code></pre>
<p>Sample:</p>
<pre><code>print (df)
column1 column2 column3 column4
0 name True True NaN
1 name NaN True NaN
2 name1 NaN True True
3 name1 True True True
df1 = df.set_index('column1').stack(dropna=False)
print (df1)
column1
name column2 True
column3 True
column4 NaN
column2 NaN
column3 True
column4 NaN
name1 column2 NaN
column3 True
column4 True
column2 True
column3 True
column4 True
dtype: object
print (df1.groupby(level=[0,1]).nunique(dropna=False).unstack(fill_value=0))
column2 column3 column4
column1
name 2 1 1
name1 2 1 1
print (df1.groupby(level=[0,1]).nunique().unstack(fill_value=0))
column2 column3 column4
column1
name 1 1 0
name1 1 1 1
</code></pre>
<hr>
<p>Another solution with double <code>apply</code>:</p>
<pre><code>print (df.groupby('column1')
.apply(lambda x: x.iloc[:,1:].apply(lambda y: y.nunique(dropna=False))))
column2 column3 column4
column1
name 2 1 1
name1 2 1 1
print (df.groupby('column1').apply(lambda x: x.iloc[:,1:].apply(lambda y: y.nunique())))
column2 column3 column4
column1
name 1 1 0
name1 1 1 1
</code></pre>
| 2 | 2016-10-12T17:19:20Z | [
"python",
"pandas",
"count",
"unique",
"distinct"
] |
yes or no loop (TypeError: 'NoneType' object is not iterable) error | 40,004,620 | <p>I'm trying to implement a yes / no / retry, but I am getting this error: 'NoneType' object is not iterable. I assume the issue is the function (def izberiEkipo() is not returning what it's suppose to.</p>
<pre><code>def izberiEkipo():
m = set(['m'])
p = set(['p'])
while False:
if reply in m:
with open('vprasanja2.txt') as f:
vsaVprasanja = [line.strip() for line in f]
max_line = len(vsaVprasanja)
True
elif reply in p:
with open('vprasanja.txt') as f:
vsaVprasanja = [line.strip() for line in f]
max_line = len(vsaVprasanja)
True
else:
sys.stdout.write("Answer with 'm' ord 'p'")
return (max_line, vsaVprasanja)
def genVprasanja ():
obsVred = set()
maxL, vsaQ = izberiEkipo()
tocke = 5
total = 0
.
.
[...]
</code></pre>
| -1 | 2016-10-12T17:18:01Z | 40,004,724 | <p>Your assumption is correct: as given, your upper function returns nothing. You've disabled the loop with a <strong>False</strong> entry condition: it won't run at all. The only <strong>return</strong> in the function is inside that loop.</p>
<p>Thus, all that routine does is to create two sets of a single character each, and then return <strong>None</strong> to the main program. Since you haven't included code to reproduce the problem -- in fact, the line that throws the error isn't in your example -- and no trace-back, we can't help much farther than this.</p>
| 0 | 2016-10-12T17:23:53Z | [
"python"
] |
Moviepy OSError Exec format error - Missing Shebang? | 40,004,639 | <p>I am attempting to use MoviePy with Python 3.2.3 on Raspian.
I have installed it (for Python 2.7, 3.2 and 3.5... long story) and the line</p>
<pre><code>from moviepy.editor import *
</code></pre>
<p>works fine.
When I try</p>
<pre><code>clip = VideoFileClip("vid.mov")
</code></pre>
<p>which is the most basic command, it gives the error</p>
<pre><code>Traceback (most recent call last):
File "/home/pi/QuickFlicsPics/moviepytest.py", line 8, in <module>
clip = VideoFileClip("vid.mov")
File "/usr/local/lib/python3.2/distpackages/moviepy/video/io/VideoFileClip.py", line 55, in __init__
reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
File "/usr/local/lib/python3.2/dist-packages/moviepy/video/io/ffmpeg_reader.py", line 32, in __init__
infos = ffmpeg_parse_infos(filename, print_infos, check_duration)
File "/usr/local/lib/python3.2/dist-packages/moviepy/video/io/ffmpeg_reader.py", line 237, in ffmpeg_parse_infos
proc = sp.Popen(cmd, **popen_params)
File "/usr/lib/python3.2/subprocess.py", line 745, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.2/subprocess.py", line 1371, in _execute_child
raise child_exception_type(errno_num, err_msg)
OSError: [Errno 8] Exec format error
</code></pre>
<p>I have researched this error, and it appears to be something to do with a shebang line missing somewhere. Is this correct, if so, how do I go about finding where it is missing, and what do I add?
Thanks</p>
<p>Edit:
As per cxw's comment, I installed moviepy using the command</p>
<pre><code>pip-3.2 install moviepy
</code></pre>
<p>(I may have used 'sudo' as well)</p>
<p>FFMPEG was supposed to download automatically when I first used moviepy:</p>
<blockquote>
<p>MoviePy depends on the software FFMPEG for video reading and writing. > You donât need to worry about that, as FFMPEG should be automatically > downloaded/installed by ImageIO during your first use of MoviePy (it takes a few seconds). If you want to use a specific version of FFMPEG, follow the instructions in file config_defaults.py.</p>
</blockquote>
<p>[Quote from installation guide <a href="https://zulko.github.io/moviepy/install.html" rel="nofollow">here</a>]</p>
| 1 | 2016-10-12T17:19:27Z | 40,005,275 | <p>Manually download ffmpeg, then before running your Python code, do</p>
<pre><code>export FFMPEG_BINARY=path/to/ffmpeg
</code></pre>
<p>at the shell/terminal prompt.</p>
<p>As far as I can tell from <a href="https://github.com/imageio/imageio/blob/master/imageio/plugins/ffmpeg.py#L48" rel="nofollow">the source</a>, the automatic download of ffmpeg does not know about Raspberry Pis. The <a href="https://github.com/imageio/imageio/blob/master/imageio/core/fetching.py#L29" rel="nofollow">auto-download code</a> pulls from <a href="https://github.com/imageio/imageio-binaries/tree/master/ffmpeg" rel="nofollow">the imageio github repo</a>, which only knows "linux32" vs. "linux64". It doesn't look like it has an ARM-linux option. When the ARM kernel sees a non-ARM image, it throws the error you see.</p>
<p>Rather than using the environment variable, you can edit your moviepy <a href="https://github.com/Zulko/moviepy/blob/master/moviepy/config_defaults.py" rel="nofollow"><code>config-defaults.py</code></a> file to specify <code>FFMPEG_BINARY = r"/path/to/ffmpeg"</code>.</p>
<p><strong>Edit</strong> to find the <code>path/to/ffmpeg</code> after installing it with <code>apt-get</code>, do</p>
<pre><code>dpkg -L ffmpeg | grep bin
</code></pre>
<p>at the shell/terminal prompt. It will probably be in <code>/bin</code> or <code>/usr/bin</code>, and will probably be called <code>ffmpeg</code> or <code>ffmpeg-x.xx</code> (with some version number).<br>
<sub>Thanks to <a href="http://askubuntu.com/a/129024">this answer</a> for <code>dpkg</code></sub></p>
| 2 | 2016-10-12T17:56:04Z | [
"python",
"linux",
"python-3.x",
"raspberry-pi",
"moviepy"
] |
how to go the start of file in python? | 40,004,672 | <p>I am new to python and I am learning some basic file reading stuff. I am trying to read a file and count the number of new lines and also print lines that start with 'From: ' .</p>
<p>This is the code I have for that:</p>
<pre><code>fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count + 1
print count
for line in fhand:
if line.startswith('From: '):
print line
</code></pre>
<p>I know that I can do this in one loop but I am trying to learn something here. As soon as the first loop is executed, 'line' is at the end of the file. So when it runs the second loop, it does not print anything. I tried putting in line = 0, it doesnt work. How to I got back to start of file?</p>
<p>Thank you for your help. </p>
| 0 | 2016-10-12T17:21:06Z | 40,004,712 | <pre><code>file.seek(0)
</code></pre>
<p><a href="https://docs.python.org/3.5/tutorial/inputoutput.html" rel="nofollow">Seek()</a> takes an argument that goes back to that "byte" so 0 byte will go back to the start of the file. </p>
| 1 | 2016-10-12T17:23:15Z | [
"python"
] |
how to go the start of file in python? | 40,004,672 | <p>I am new to python and I am learning some basic file reading stuff. I am trying to read a file and count the number of new lines and also print lines that start with 'From: ' .</p>
<p>This is the code I have for that:</p>
<pre><code>fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count + 1
print count
for line in fhand:
if line.startswith('From: '):
print line
</code></pre>
<p>I know that I can do this in one loop but I am trying to learn something here. As soon as the first loop is executed, 'line' is at the end of the file. So when it runs the second loop, it does not print anything. I tried putting in line = 0, it doesnt work. How to I got back to start of file?</p>
<p>Thank you for your help. </p>
| 0 | 2016-10-12T17:21:06Z | 40,004,713 | <p>Try this out :</p>
<pre><code>with open('mbox.txt') as f:
count = 0
for l in f.readlines():
count += 1
if l.startswith('From: '):
print l
</code></pre>
<p>To get back to start of file use <code>seek(0)</code></p>
| 0 | 2016-10-12T17:23:22Z | [
"python"
] |
Using R or Python plot worldmap with countries from simple list colored | 40,004,689 | <p>I have the list of countries :</p>
<pre><code>("Albania", "Algeria", "Anguilla", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belgium", "Belize", "Benin", "Bermuda", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Cambodia", "Cameroon", "Canada", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Congo", "Congo (DRC)", "Costa Rica", "Croatia", "Curacao", "Cyprus", "Czech Republic", "Denmark", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Faroe Islands", "Fiji Islands", "Finland", "France", "French Guiana", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong SAR", "Hungary", "Iceland", "India", "Indonesia", "Ireland", "Isle of Man", "Israel", "Italy", "Ivory Coast / Côte d'Ivoire", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kuwait", "Latvia", "Lebanon", "Lesotho", "Lithuania", "Luxembourg", "Macao SAR", "Macedonia, Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Mali", "Malta", "Martinique", "Mauritania", "Mauritius", "Mexico", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Namibia", "Netherlands", "Netherlands Antilles", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Pakistan", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Puerto Rico", "Qatar", "Romania", "Russia", "Rwanda", "Réunion", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadine", "Samoa", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Singapore", "Slovakia", "Slovenia", "South Africa", "South Korea", "Spain", "Sri Lanka", "St. Maarten", "Suriname", "Swaziland", "Sweden", "Switzerland", "Taiwan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turks and Caicos Islands", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands, British", "Virgin Islands, U.S.", "Zambia"))
</code></pre>
<p>And when I try to plot it by R:</p>
<pre><code>map('worldHires',
c("Albania", "Algeria", "Anguilla", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belgium", "Belize", "Benin", "Bermuda", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Cambodia", "Cameroon", "Canada", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Congo", "Congo (DRC)", "Costa Rica", "Croatia", "Curacao", "Cyprus", "Czech Republic", "Denmark", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Faroe Islands", "Fiji Islands", "Finland", "France", "French Guiana", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong SAR", "Hungary", "Iceland", "India", "Indonesia", "Ireland", "Isle of Man", "Israel", "Italy", "Ivory Coast / Côte d'Ivoire", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kuwait", "Latvia", "Lebanon", "Lesotho", "Lithuania", "Luxembourg", "Macao SAR", "Macedonia, Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Mali", "Malta", "Martinique", "Mauritania", "Mauritius", "Mexico", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Namibia", "Netherlands", "Netherlands Antilles", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Pakistan", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Puerto Rico", "Qatar", "Romania", "Russia", "Rwanda", "Réunion", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadine", "Samoa", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Singapore", "Slovakia", "Slovenia", "South Africa", "South Korea", "Spain", "Sri Lanka", "St. Maarten", "Suriname", "Swaziland", "Sweden", "Switzerland", "Taiwan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turks and Caicos Islands", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands, British", "Virgin Islands, U.S.", "Zambia"))
</code></pre>
<p>I get:
<a href="https://i.stack.imgur.com/dbsSC.png" rel="nofollow"><img src="https://i.stack.imgur.com/dbsSC.png" alt="Incorrect world map"></a>
What I am doing wrong or maybe there is much easier way to plot worldmap?
And how to plot all other uncolored or colored in another color?</p>
| 1 | 2016-10-12T17:21:53Z | 40,004,867 | <p>This line might work:</p>
<pre><code>map("world", fill=TRUE, col="white", bg="lightblue", ylim=c(-60, 90), mar=c(0,0,0,0))
</code></pre>
<p>Also this is a good website to look at: <a href="https://www.r-bloggers.com/r-beginners-plotting-locations-on-to-a-world-map/" rel="nofollow">https://www.r-bloggers.com/r-beginners-plotting-locations-on-to-a-world-map/</a></p>
| 2 | 2016-10-12T17:32:35Z | [
"python",
"plot",
"rworldmap"
] |
What optimisations are done that this code completes quickly? | 40,004,692 | <p>I was solving a problem I came across, what is the sum of powers of 3 from 0 to 2009 mod 8.</p>
<p>I got an answer using pen and paper, and tried to verify it with some simple python</p>
<pre><code>print(sum(3**k for k in range(2010)) % 8)
</code></pre>
<p>I was surprised by how quickly it returned an answer. My question is what optimisations or tricks are used by the interpreter to get the answer so quickly?</p>
| -1 | 2016-10-12T17:22:01Z | 40,004,744 | <p>No fancy optimizations are responsible for the fast response you observed. Computers are just a lot faster in absolute terms than you expected.</p>
| 1 | 2016-10-12T17:24:32Z | [
"python",
"python-3.x",
"optimization"
] |
What optimisations are done that this code completes quickly? | 40,004,692 | <p>I was solving a problem I came across, what is the sum of powers of 3 from 0 to 2009 mod 8.</p>
<p>I got an answer using pen and paper, and tried to verify it with some simple python</p>
<pre><code>print(sum(3**k for k in range(2010)) % 8)
</code></pre>
<p>I was surprised by how quickly it returned an answer. My question is what optimisations or tricks are used by the interpreter to get the answer so quickly?</p>
| -1 | 2016-10-12T17:22:01Z | 40,004,749 | <p>None, it's just not a lot of computation for a computer to do. </p>
<p>Your code is equivalent to:</p>
<pre><code>>>> a = sum(3**k for k in range(2010))
>>> a % 8
4
</code></pre>
<p><code>a</code> is a 959-digit number - it's just not a large task to ask of a computer.</p>
<p>Try sticking two zeros on the end of the <code>2010</code> and you will see it taking an appreciable amount of time.</p>
| 3 | 2016-10-12T17:24:45Z | [
"python",
"python-3.x",
"optimization"
] |
What optimisations are done that this code completes quickly? | 40,004,692 | <p>I was solving a problem I came across, what is the sum of powers of 3 from 0 to 2009 mod 8.</p>
<p>I got an answer using pen and paper, and tried to verify it with some simple python</p>
<pre><code>print(sum(3**k for k in range(2010)) % 8)
</code></pre>
<p>I was surprised by how quickly it returned an answer. My question is what optimisations or tricks are used by the interpreter to get the answer so quickly?</p>
| -1 | 2016-10-12T17:22:01Z | 40,004,855 | <p>The only optimization at work is that each instance of <code>3**k</code> is evaluated using a number of multiplications proportional to the number of bits in <code>k</code> (it does <em>not</em> multiply 3 by itself <code>k-1</code> times).</p>
<p>As already noted, if you boost 2010 to 20100 or 201000 or ..., it will take much longer, because <code>3**k</code> becomes very large. However, in those cases you can speed it enormously again by rewriting it as, e.g.,</p>
<pre><code>print(sum(pow(3, k, 8) for k in range(201000)) % 8)
</code></pre>
<p>Internally, <code>pow(3, k, 8)</code> still does a number of multiplications proportional to the number of bits in <code>k</code>, but doesn't need to retain any integers internally larger than about 8**2 (the square of the modulus).</p>
| 2 | 2016-10-12T17:31:51Z | [
"python",
"python-3.x",
"optimization"
] |
Is it possible using Tensorflow to create a neural network for input/output mapping? | 40,004,703 | <p>I am currently using tensorflow to create a neural network, that replicates the function of creating a certain output given an input. </p>
<p>The input in this case is a sampled audio, and the audio is generating MFCC features. Know for each file what the corresponding MFCC feature, is, but aren't sure how i should setup the neural network. </p>
<p>I am following this guide/tutorial <a href="http://www.kdnuggets.com/2016/09/urban-sound-classification-neural-networks-tensorflow.html/2" rel="nofollow">http://www.kdnuggets.com/2016/09/urban-sound-classification-neural-networks-tensorflow.html/2</a></p>
<p>It which it says that the neural network is setup as such</p>
<pre><code>training_epochs = 5000
n_dim = tr_features.shape[1]
n_classes = 10
n_hidden_units_one = 280
n_hidden_units_two = 300
sd = 1 / np.sqrt(n_dim)
learning_rate = 0.01
</code></pre>
<p>My question here is how i define the number of classes? I mean, the real values I've computed aren't divided into classes, but is a decimal number, so should I just create multiple networks with different number of classes, and choose the one which has the smallest error compared to the original value, or is there a tensorflow command that can do that, as I am doing supervised learning..</p>
| 0 | 2016-10-12T17:22:43Z | 40,016,293 | <p>Neural networks could be use for classification tasks or regression tasks. In <a href="http://www.kdnuggets.com/2016/09/urban-sound-classification-neural-networks-tensorflow.html/2" rel="nofollow">tutorial</a>, the author wants to classify sounds into 10 different categories. So the neural networks have 10 output neurons (<code>n_classes</code>) and each of their activation value give the probability of membership to a class for an input sound.</p>
<p>In our case, you want to map a given sound with a decimal number (that's right ?), so it's a regression task : the neural network have to learn an unknown function. The number of output neurons has to be equal to the output dimension of our unknown function (1 if it's just a decimal number).</p>
<p>So if you want to keep the same architecture to our regression task, just set <code>n_classes = 1</code> and modify <code>y_</code> to </p>
<pre><code>y_ = tf.matmul(h_2,W) + b
</code></pre>
<p>because <code>tf.nn.softmax</code> convert the final score to probability (it's good for classification but not for regression)</p>
| 0 | 2016-10-13T08:47:12Z | [
"python",
"tensorflow",
"supervised-learning"
] |
Keras Custom Scaling Layer | 40,004,706 | <p>For my work, I need to make a layer, that has only single weight, that will multiply the data in the current layer by some trained value. Is there a way to do this?</p>
<p>Or change the merge layer, which will be able to make a weighted average of input layers.
Thanks</p>
| 0 | 2016-10-12T17:22:46Z | 40,008,115 | <p>Try Lambda layer</p>
<pre><code>model.add(Lambda(lambda x: x *MyValue))
</code></pre>
<p><a href="https://keras.io/layers/core/#lambda" rel="nofollow">https://keras.io/layers/core/#lambda</a></p>
| 0 | 2016-10-12T20:50:00Z | [
"python",
"machine-learning",
"keras"
] |
In python how can I call a function using an imported module | 40,004,738 | <p>I have this module that calls main() function:</p>
<pre><code>## This is mymodules ##
def restart():
r = input('Do you want to build another configuration file?\n1. Yes\n2. No\n')
if r == '1':
main()
elif r == '2':
os.system('pause')
</code></pre>
<p>The main() is in another script that loads this module. However when it calls it says main() is not defined. essentially this is what I have in my test:</p>
<pre><code>import mymodules as my
def main():
print('good')
my.restart()
</code></pre>
<p>When this runs I want the my.restart() to be able to call the main() defined.</p>
| 0 | 2016-10-12T17:24:09Z | 40,004,984 | <p>For a code as simple as this one you could simply pass the <code>main</code> function as an argument to the restart function.</p>
<p>E.g.</p>
<pre><code>def restart(function):
r = input('Do you want to build another configuration file?\n1. Yes\n2. No\n')
if r == '1':
function()
elif r == '2':
os.system('pause')
</code></pre>
<p>And:</p>
<pre><code>import mymodules as my
def main():
print('good')
my.restart(main)
</code></pre>
<p>This is a popular design pattern known as a <a href="http://stackoverflow.com/a/4690014/3424550">callback</a></p>
<p>However, this only works in simple examples like this. If you are writing something more complex you probably want to use objects and pass the objects instead. That way you will be able to call all multiple methods/functions from a single object.</p>
| 2 | 2016-10-12T17:39:05Z | [
"python",
"function",
"import",
"module"
] |
How to fix "bad handshake" SSLErrors when utilizing python requests | 40,004,748 | <p>I'm trying to get access to the BambooHR API (<a href="https://www.bamboohr.com/api/documentation/login.php" rel="nofollow">documentation here</a>), but I receive the following error</p>
<pre><code> params = {
'user': username,
'password': password,
'api_token': api_key}
url = 'https://api.bamboohr.com/api/gateway.php/company/v1/login'
r = requests.get(url, params=params)
</code></pre>
<p>Error: </p>
<pre><code>Traceback (most recent call last):
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1580, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 964, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/chriscruz/Dropbox/PycharmProjects/082716_r2/Shippy/API/bamboo_api2.py", line 31, in <module>
BambooFunctions().login()
File "/Users/chriscruz/Dropbox/PycharmProjects/082716_r2/Shippy/API/bamboo_api2.py", line 26, in login
r = requests.get(url, params=params, auth=HTTPBasicAuth(api_key, 'api_token'))
File "/Library/Python/2.7/site-packages/requests/api.py", line 70, in get
return request('get', url, params=params, **kwargs)
File "/Library/Python/2.7/site-packages/requests/api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Python/2.7/site-packages/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "/Library/Python/2.7/site-packages/requests/sessions.py", line 596, in send
r = adapter.send(request, **kwargs)
File "/Library/Python/2.7/site-packages/requests/adapters.py", line 497, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'unknown protocol')],)",)
</code></pre>
<p>I'm unsure what this is caused by as I've re-installed OpenSSL, Requests, and not sure how to fix this issue.</p>
| 0 | 2016-10-12T17:24:43Z | 40,004,934 | <p>You try by setting verify=False, use this option if you are using self-signed certificates.</p>
<p><code>r = requests.get(url, params=params, verify=False)</code></p>
<p>More info <a href="http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification" rel="nofollow">http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification</a></p>
| 0 | 2016-10-12T17:36:11Z | [
"python",
"api",
"openssl",
"python-requests"
] |
Encrypt in python and decrypt in Java with AES-CFB | 40,004,858 | <p>I am aware of a question very similar to this (<a href="http://stackoverflow.com/questions/10440777/how-do-i-encrypt-in-python-and-decrypt-in-java">How do I encrypt in Python and decrypt in Java?</a>) but I have a different problem.</p>
<p>My problem is, I am not able to decrypt in Java correctly. Despite using the correct key and IV, I still get garbage characters after decryption. I don't have any compile/run-time errors or exceptions in Java so I believe I am using the right parameters for decryption.</p>
<p>Python Encryption Code - </p>
<pre><code>from Crypto.Cipher import AES
import base64
key = '0123456789012345'
iv = 'RandomInitVector'
raw = 'samplePlainText'
cipher = AES.new(key,AES.MODE_CFB,iv)
encrypted = base64.b64encode(cipher.encrypt(raw))
</code></pre>
<p>Java Decryption Code - </p>
<pre><code>private static String KEY = "0123456789012345";
public static String decrypt(String encrypted_encoded_string) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
String plain_text = "";
try{
byte[] encrypted_decoded_bytes = Base64.getDecoder().decode(encrypted_encoded_string);
String encrypted_decoded_string = new String(encrypted_decoded_bytes);
String iv_string = encrypted_decoded_string.substring(0,16); //IV is retrieved correctly.
IvParameterSpec iv = new IvParameterSpec(iv_string.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
plain_text = new String(cipher.doFinal(encrypted_decoded_bytes));//Returns garbage characters
return plain_text;
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
}
return plain_text;
}
</code></pre>
<p>Is there anything obvious that I am missing?</p>
| 1 | 2016-10-12T17:32:01Z | 40,006,920 | <p>The <a href="https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Feedback_.28CFB.29" rel="nofollow">Cipher Feedback (CFB) mode of operation</a> is a family of modes. It is parametrized by the segment size (or register size). PyCrypto has a default <a href="https://github.com/dlitz/pycrypto/blob/v2.6.1/src/block_template.c#L182" rel="nofollow">segment size of 8 bit</a> and Java (actually OpenJDK) has a default segment size the <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/crypto/provider/CipherCore.java#228" rel="nofollow">same as the block size</a> (128 bit for AES).</p>
<p>If you want CFB-128 in pycrypto, you can use <code>AES.new(key, AES.MODE_CFB, iv, segment_size=128)</code>. If you want CFB-8 in Java, you can use <code>Cipher.getInstance("AES/CFB8/NoPadding");</code>.</p>
<hr>
<p>Now that we have that out the way, you have other problems:</p>
<ul>
<li><p>Always specify the character set you're using, because it can change between different JVMs: <code>new String(someBytes, "UTF-8")</code> and <code>someString.getBytes("UTF-8")</code>. When you do, be consistent.</p></li>
<li><p>Never use a String to store binary data (<code>new String(encrypted_decoded_bytes);</code>). You can copy the bytes directly: <code>IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(encrypted_decoded_bytes, 16));</code> and <code>cipher.doFinal(Arrays.copyOfRange(encrypted_decoded_bytes, 16, encrypted_decoded_bytes.length))</code>.</p></li>
<li><p>In Java, you're assuming that the IV is written in front of the ciphertext and then encoded together, but in Python, you're never doing anything with the IV. I guess you posted incomplete code.</p></li>
<li><p>It is crucial for CFB mode to use a <strong>different</strong> IV every time if the key stays the same. If you don't change the IV for every encryption, you will create a multi-time pad which enables an attacker to deduce the plaintext even without knowing the key.</p></li>
</ul>
| 0 | 2016-10-12T19:34:40Z | [
"java",
"python",
"encryption",
"pycrypto",
"cfb-mode"
] |
pandas: get the value of the index for a row? | 40,004,871 | <p>I have a dataframe:</p>
<pre><code> cost month para
prod_code
040201060AAAIAI 43 2016-01-01 0402
040201060AAAIAJ 45 2016-02-01 0402
040201060AAAIAI 46 2016-03-01 0402
040201060AAAIAI 41 2016-01-01 0402
040201060AAAIAI 48 2016-02-01 0402
</code></pre>
<p>How can I iterate over the rows, and get the value of the index for each one?</p>
<pre><code>d = { 'prod_code': ['040201060AAAIAI', '040201060AAAIAJ', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040301060AAAKAG', '040301060AAAKAK', '040301060AAAKAK', '040301060AAAKAX', '040301060AAAKAK', '040301060AAAKAK'], 'month': ['2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01'], 'cost': [43, 45, 46, 41, 48, 59, 8, 9, 10, 12, 15, 13] }
df = pd.DataFrame.from_dict(d)
df.set_index('prod_code', inplace=True)
</code></pre>
<p>This is what I'm trying:</p>
<pre><code>for i, row in df.iterrows():
print row.index, row['cost']
</code></pre>
<p>But I get this:</p>
<pre><code>Index([u'items', u'cost'], dtype='object') 3.34461552621
</code></pre>
<p>UPDATE: This is the same as asking how to get the name of the index for a series, but phrased differently. Also though the <em>answer</em> is the same as another question, the <em>question</em> is not the same! Specifically, this question will be found when people Google for "pandas index of row" rather than "pandas name of series". </p>
| 3 | 2016-10-12T17:33:00Z | 40,004,924 | <p>use this to iterate over any value <code>df.ix[row_value,col_value]</code> for finding the column index use this function</p>
<pre><code>def find_column_number(column_name):
x=list(df1.columns.values)
print column_name
col_lenth= len(x)
counter=0
count=[]
while counter<col_lenth:
if x[counter]==column_name:
count=counter
counter+=1
return count
</code></pre>
| 1 | 2016-10-12T17:35:44Z | [
"python",
"pandas"
] |
pandas: get the value of the index for a row? | 40,004,871 | <p>I have a dataframe:</p>
<pre><code> cost month para
prod_code
040201060AAAIAI 43 2016-01-01 0402
040201060AAAIAJ 45 2016-02-01 0402
040201060AAAIAI 46 2016-03-01 0402
040201060AAAIAI 41 2016-01-01 0402
040201060AAAIAI 48 2016-02-01 0402
</code></pre>
<p>How can I iterate over the rows, and get the value of the index for each one?</p>
<pre><code>d = { 'prod_code': ['040201060AAAIAI', '040201060AAAIAJ', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040301060AAAKAG', '040301060AAAKAK', '040301060AAAKAK', '040301060AAAKAX', '040301060AAAKAK', '040301060AAAKAK'], 'month': ['2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01'], 'cost': [43, 45, 46, 41, 48, 59, 8, 9, 10, 12, 15, 13] }
df = pd.DataFrame.from_dict(d)
df.set_index('prod_code', inplace=True)
</code></pre>
<p>This is what I'm trying:</p>
<pre><code>for i, row in df.iterrows():
print row.index, row['cost']
</code></pre>
<p>But I get this:</p>
<pre><code>Index([u'items', u'cost'], dtype='object') 3.34461552621
</code></pre>
<p>UPDATE: This is the same as asking how to get the name of the index for a series, but phrased differently. Also though the <em>answer</em> is the same as another question, the <em>question</em> is not the same! Specifically, this question will be found when people Google for "pandas index of row" rather than "pandas name of series". </p>
| 3 | 2016-10-12T17:33:00Z | 40,004,947 | <pre><code>for i, row in df.iterrows():
</code></pre>
<p>returns a <code>Series</code> for each row where the <code>Series</code> name is the <code>index</code> of the row you are iterating through. you could simply do</p>
<pre><code>d = { 'prod_code': ['040201060AAAIAI', '040201060AAAIAJ', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040201060AAAIAI', '040301060AAAKAG', '040301060AAAKAK', '040301060AAAKAK', '040301060AAAKAX', '040301060AAAKAK', '040301060AAAKAK'], 'month': ['2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-01-01', '2016-02-01', '2016-03-01'], 'cost': [43, 45, 46, 41, 48, 59, 8, 9, 10, 12, 15, 13] }
df = pd.DataFrame.from_dict(d)
df.set_index('prod_code', inplace=True)
for i, row in df.iterrows():
print row.name, row['cost']
040201060AAAIAI 43
040201060AAAIAJ 45
040201060AAAIAI 46
040201060AAAIAI 41
040201060AAAIAI 48
040201060AAAIAI 59
040301060AAAKAG 8
040301060AAAKAK 9
040301060AAAKAK 10
040301060AAAKAX 12
040301060AAAKAK 15
040301060AAAKAK 13
</code></pre>
<p>you can learn more about it <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html#pandas-dataframe-iterrows" rel="nofollow">here</a></p>
| 2 | 2016-10-12T17:36:55Z | [
"python",
"pandas"
] |
Hashlib MemoryError in Python 3.5 but not in 2.7 | 40,004,963 | <p>I've been porting a set of Python 2.7 scripts to Python 3.5 so that I can use some libraries that aren't available in 2.7, but I'm getting MemoryError from this code that worked previously:</p>
<pre><code>import hashlib, functools
sha2h = hashlib.sha256()
with open('/path/to/any/file', 'rb') as f:
[sha2h.update(chunk) for chunk in iter(functools.partial(f.read, 256), '')]
</code></pre>
<p>As far as I can tell, this is the proper way to get a SHA256 hash of a file. I can't seem to find anything about this issue. If it helps, here's the traceback when the above code is run from the shell:</p>
<pre><code>File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in <listcomp>
</code></pre>
<p>Also tried replacing</p>
<pre><code>sha2h = hashlib.sha256()
</code></pre>
<p>with</p>
<pre><code>sha2h = hashlib.new('sha256')
</code></pre>
<p>to match the documentation for hashlib, but this yielded no change in outcome.</p>
<p>Any help or insight would be greatly appreciated!</p>
| 0 | 2016-10-12T17:37:44Z | 40,005,048 | <p>On Python 3, you need to set <code>b''</code> instead of <code>''</code> as the sentinel value for the <code>iter</code> call:</p>
<pre><code>iter(functools.partial(f.read, 256), b'')
</code></pre>
<p>You also really shouldn't be using a list comprehension for side effects like this, but if you're porting existing code that does that, it's probably best to just leave that for now.</p>
| 0 | 2016-10-12T17:43:04Z | [
"python",
"python-3.x",
"hashlib",
"functools"
] |
MongoDB collection chain | 40,004,988 | <p>I have a problem that I need to solve. Currently my code works with one collection where I create a cursor for one collection of builds. It looks like this:</p>
<pre><code>from pymongo import MongoClient
from itertools import chain
db = MongoClient('10.39.165.193', 27017)['mean-dev']
cursor = db.collection1.find().limit(10).sort('number', -1)
</code></pre>
<p>The definition I use returns this value so that I can use it access information.
I want to be able to add another collection to this and treat both collections almost as if they were the same. </p>
<pre><code>cursor2 = db.collection1.find().limit(10).sort('number', -1)
joinCursors = ... # Somehow join cursors
</code></pre>
<p>What I tried was this (but it did'nt work):</p>
<pre><code>joinCursor = [x for x in chain(cursor1, cursor2)]
</code></pre>
<p>When I simply print joinCursor. I get the last thing in my DB which is not what I want. What I want is the same thing as when I'm only returning cursor1 which is: . So that I can use for things like counting, example:</p>
<pre><code>counter = joinedCursor.count(True)
</code></pre>
| 0 | 2016-10-12T17:39:12Z | 40,015,554 | <p>One way to solve this is to write your own <code>JoinedCursor</code> class such as this:</p>
<pre><code>class JoinedCursor:
def __init__(self, db, collection1, collection2, limit=None, sort_on=None, order=1):
self.limit = limit
self.sort_on = sort_on
self.order = order
self.cursor1 = db[collection1].find()
self.cursor2 = db[collection2].find()
def __iter__(self):
for doc in self.cursor1.limit(self.limit).sort(self.sort_on, self.order):
yield doc
for doc in self.cursor2.limit(self.limit).sort(self.sort_on, self.order):
yield doc
def count(self):
return self.cursor1.count() + self.cursor2.count()
</code></pre>
<p>This then allows you to create a joined cursor on two collections like so:</p>
<pre><code>db = pymongo.MongoClient()["test-join"]
joined_cursor = JoinedCursor(db, "collection1", "collection2", limit=10, sort_on="num", order=-1)
</code></pre>
<p>You can iterate over both in sequence with a for loop and call the <code>count</code> method:</p>
<pre><code>for doc in joined_cursor:
print(doc)
print(joined_cursor.count())
</code></pre>
<p>This could of course be more generalised to take two or more collections and apply queries etc. </p>
| 0 | 2016-10-13T08:08:34Z | [
"python",
"mongodb",
"pymongo"
] |
character detection and crop from an image using opencv python | 40,005,055 | <p>I have a project in which I have to detect Bengali numbers from image. I decided to do an experiment like numbers with spaces and without spaces. My python program can detect all number from with spaces image.</p>
<p>The problem occurred when I gave image without spaces. It couldn't cut number smoothly like the previous one. </p>
<p>here is my code</p>
<pre class="lang-python prettyprint-override"><code>import cv2
image = cv2.imread("number.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,70,255,cv2.THRESH_BINARY_INV)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 0)
_,contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
i=5
for contour in contours:
[x,y,w,h] = cv2.boundingRect(contour)
cv2.imwrite(str(i)+".jpg",image[y:y+h,x:x+h])
i=i+1</code></pre>
<p>At first I used dilated in for finding contours but it didn't work for number without space image. Then I use directly thresh output and after that I got most of the numbers but I couldn't cut them perfectly because contour area detect number with some portion of other number. Though it didn't have space in 2nd image but still 2 numbers didn't touch them each other. So why the output like this?</p>
<h2>With Space:</h2>
<p><img src="https://i.stack.imgur.com/lpQYZ.png" alt="with space"></p>
<h2>Without Space:</h2>
<p><img src="https://i.stack.imgur.com/PEW7H.png" alt="without space"> </p>
| 0 | 2016-10-12T17:43:13Z | 40,034,372 | <p>Unfortunately I didn't notice that when I cut rectangle portion I added x:x+h instead of x:x+w. That's the main problem. After modifying that the program worked fine. sorry.</p>
| 0 | 2016-10-14T03:15:49Z | [
"python",
"opencv",
"ocr",
"opencv-contour"
] |
AttributeError: module âxgboostâ has no attribute âXGBRegressorâ | 40,005,093 | <p>I am trying to run xgboost using spyder python but keep getting this error
<strong>AttributeError: module âxgboostâ has no attribute âXGBRegressorâ</strong></p>
<p>Here is the code</p>
<pre><code>import xgboost as xgb
xgb.XGBRegressor(max_depth=3, learning_rate=0.1, n_estimators=100, silent=True,
objective='reg:linear', gamma=0, min_child_weight=1,
max_delta_step=0, subsample=1, colsample_bytree=1,
seed=0, missing=None)
</code></pre>
<p><strong>Error is</strong></p>
<pre><code>Traceback (most recent call last):
File "<ipython-input-33-d257a9a2a5d8>", line 1, in <module>
xgb.XGBRegressor(max_depth=3, learning_rate=0.1, n_estimators=100, silent=True,
AttributeError: module 'xgboost' has no attribute 'XGBRegressor'
</code></pre>
<p>I have
Python 3.5.2 :: Anaconda 4.2.0 (x86_64)</p>
<p>Please help</p>
| 0 | 2016-10-12T17:45:13Z | 40,025,007 | <p>Since your <code>dir</code> call is missing basically everything, my suspicion is that wherever you're starting your script from has an <code>xgboost</code> subfolder with an empty <code>__init__.py</code> in it that is being found first by your <code>import</code>.</p>
| 0 | 2016-10-13T15:21:15Z | [
"python",
"machine-learning",
"regression",
"xgboost"
] |
Make an array class using dictionaries only | 40,005,203 | <p>I am a student who is new to python. I am trying to define an array class below which uses a dictionary as its only member variable. I am assuming that Python implements dictionaries as the only structured type (i.e., there is no array, list, tuple, etc.).</p>
<p>I am facing difficulty in coding such a program.</p>
<p>This is my code:</p>
<pre><code>class array(object):
def __init__(self):
self.dic={}
def __init__(self,diction):
self.dic = {}
for x in diction:
self.dic.append(x)
def __setitem__(self,key,value):
self.dic[key]=value
def __getitem__(self,key):
if key not in self.dic.keys():
raise KeyError
return self.dic[key]
</code></pre>
<p>I want the program to work this way:</p>
<pre><code>a = array('a','b','c') #------output------
print(a) # ['a', 'b', 'c']
print(a[1]) # b
a[1] = 'bee'
print(a) # ['a', 'bee', 'c']
a[3] = 'day'
print(a) # ['a', 'bee', 'c', 'day']
print(a[6]) # IndexError exception
</code></pre>
<p>Any suggestions, advice. :)</p>
| 0 | 2016-10-12T17:51:55Z | 40,005,466 | <p>There are quite a few issues with your class definition:</p>
<ul>
<li><code>array</code> is already a data structure: better to rename using the proper Python class-naming conventions (<code>MyClass</code>).</li>
<li>You cannot overload function definitions: better to use an unpacking operator (<code>*</code>) to extract all (if any) arguments.</li>
<li>You cannot append to a dictionary: you need to assign to a key.</li>
<li>Your call to <code>print</code> will display a generic class name, since you don't specify a <code>__str__</code> magic method. Since a <code>dict</code> is unordered, I did some funny business here to make it display as sorted, though I'm sure there's a better way.</li>
<li>No need to raise a <code>KeyError</code> in <code>__getitem__</code>, since this will be raised anyway.</li>
<li>Finally, I corrected your spacing.</li>
</ul>
<p>Note that I've only implemented the methods necessary to make your test cases work. </p>
<pre><code>class MyArray(object):
def __init__(self, *diction):
self.dic = {}
for i, x in enumerate(diction):
self.dic[i] = x
def __setitem__(self, key, value):
self.dic[key] = value
def __getitem__(self, key):
return self.dic[key]
def __str__(self):
return str([self.dic[i] for i in sorted(self.dic.keys())])
</code></pre>
| 1 | 2016-10-12T18:06:39Z | [
"python",
"dictionary"
] |
Weird UTF-8 one-liner interpreter bug | 40,005,226 | <p>So, I have this unholy abomination of a program:</p>
<pre><code>print((lambda raw, name_file: ((lambda start_time, total, lines, names: ((lambda parsed: ('\n'.join(str(10*(parsed[0][name]+parsed[1][name]/2)/total).ljust(6) + name for name in names)))(list(map(lambda x: __import__("collections").Counter(x), map(lambda x: list(map(lambda x: x[1], x)), [list(group[1]) for group in __import__("itertools").groupby(sorted([list(group[1])[0] for group in __import__("itertools").groupby(sorted(list(map(lambda x: [x[3], ' '.join([x[4], x[5], x[6]]), __import__("datetime").datetime.strptime(x[0] + ' ' + x[1], '%Y.%m.%d %H:%M:%S')], map(str.split, filter(lambda x: (any(name.strip() in x for name in names) and "OK ( 0 )" in x), lines))))), lambda x: (x[0], x[1]))], key = lambda x: (x[2], x[1], x[0])), lambda x: ((x[2] < start_time+__import__("datetime").timedelta(days=7)) + (x[2] < start_time+__import__("datetime").timedelta(days=14))))]))))))(__import__("datetime").datetime.strptime(raw.readline().strip(), '%d.%m.%Y %H:%M'), int(raw.readline()), map(lambda x: x.replace("ÐинÑен", ""), raw.readlines()), list(map(str.strip, name_file.readlines())))))(raw = open("test.txt", "r"), name_file = open("names.txt", "r")))
</code></pre>
<p>(probably better on <a href="http://pastebin.com/XFTK63EN" rel="nofollow">pastebin</a>)</p>
<p>It <em>almost</em> works, but the way it does <em>not</em> work is very weird and looks like an interpreter bug to me.</p>
<p>Now, the only non-ASCII characters in the code are in the string "ÐинÑен" in the end, and even then they are perfectly UTF-8-compatible, which is supposed to be the default encoding. Now, the problem is, Python throws this error:</p>
<pre><code>Non-UTF-8 code starting with '\xd1' in file lulz.py on line 1, but no encoding declared;
</code></pre>
<p>And it's not just some weird encoding problem! If I remove the last "н" in the string, the program runs just fine; the moment I add <strong>any</strong> russian letter in it's place, the interpreter crashes. Even if I only add one linebreak before this place, anywhere, just so that this string is on the second line of the source code, the interpreter does not crash.</p>
<p>Of course, I can't provide a <em>Minimal</em> example, given how finicky and unstable this is, but I'm pretty sure this is not the expected behaviour. Is this a bug in the interpreter or am I doing something wrong?</p>
<p>BTW, it may require "names.txt" and "test.txt" to be present; if you want to test, you can create two empty files with these names.</p>
<p><strong>UPD</strong> Even adding a space <em>after any single <code>(</code></em> makes everything work! Something is definitely wrong here.</p>
<p><strong>UPD2</strong> I am using Python 3.5.1</p>
<p><code>>>> python3 --version
Python 3.5.1</code></p>
<p><strong>UPD3</strong> here is my <a href="http://dropmefiles.com/zhkT9" rel="nofollow">file.</a></p>
<p><strong>UPD4</strong> and here is a hexdump: <a href="http://pastebin.com/5R1rbtc3" rel="nofollow">http://pastebin.com/5R1rbtc3</a></p>
<p><strong>UPD5</strong> apparently, this problem can only be reproduced on a Mac. I feel like different behaviour on different platforms is not intended.</p>
| 1 | 2016-10-12T17:53:07Z | 40,005,542 | <p>The bug is in your expectation of what the default source file encoding is.
It is only UTF-8 when you're using Python 3.x (I checked, 3.5 parses the abomination without problems)</p>
<p>Python 2.x defaults to ASCII so add an encoding comment as first line in this abomination and you're good to go</p>
<pre><code># -*- coding: utf8 -*-
</code></pre>
| 1 | 2016-10-12T18:11:27Z | [
"python",
"python-3.x",
"utf-8",
"character-encoding"
] |
Weird UTF-8 one-liner interpreter bug | 40,005,226 | <p>So, I have this unholy abomination of a program:</p>
<pre><code>print((lambda raw, name_file: ((lambda start_time, total, lines, names: ((lambda parsed: ('\n'.join(str(10*(parsed[0][name]+parsed[1][name]/2)/total).ljust(6) + name for name in names)))(list(map(lambda x: __import__("collections").Counter(x), map(lambda x: list(map(lambda x: x[1], x)), [list(group[1]) for group in __import__("itertools").groupby(sorted([list(group[1])[0] for group in __import__("itertools").groupby(sorted(list(map(lambda x: [x[3], ' '.join([x[4], x[5], x[6]]), __import__("datetime").datetime.strptime(x[0] + ' ' + x[1], '%Y.%m.%d %H:%M:%S')], map(str.split, filter(lambda x: (any(name.strip() in x for name in names) and "OK ( 0 )" in x), lines))))), lambda x: (x[0], x[1]))], key = lambda x: (x[2], x[1], x[0])), lambda x: ((x[2] < start_time+__import__("datetime").timedelta(days=7)) + (x[2] < start_time+__import__("datetime").timedelta(days=14))))]))))))(__import__("datetime").datetime.strptime(raw.readline().strip(), '%d.%m.%Y %H:%M'), int(raw.readline()), map(lambda x: x.replace("ÐинÑен", ""), raw.readlines()), list(map(str.strip, name_file.readlines())))))(raw = open("test.txt", "r"), name_file = open("names.txt", "r")))
</code></pre>
<p>(probably better on <a href="http://pastebin.com/XFTK63EN" rel="nofollow">pastebin</a>)</p>
<p>It <em>almost</em> works, but the way it does <em>not</em> work is very weird and looks like an interpreter bug to me.</p>
<p>Now, the only non-ASCII characters in the code are in the string "ÐинÑен" in the end, and even then they are perfectly UTF-8-compatible, which is supposed to be the default encoding. Now, the problem is, Python throws this error:</p>
<pre><code>Non-UTF-8 code starting with '\xd1' in file lulz.py on line 1, but no encoding declared;
</code></pre>
<p>And it's not just some weird encoding problem! If I remove the last "н" in the string, the program runs just fine; the moment I add <strong>any</strong> russian letter in it's place, the interpreter crashes. Even if I only add one linebreak before this place, anywhere, just so that this string is on the second line of the source code, the interpreter does not crash.</p>
<p>Of course, I can't provide a <em>Minimal</em> example, given how finicky and unstable this is, but I'm pretty sure this is not the expected behaviour. Is this a bug in the interpreter or am I doing something wrong?</p>
<p>BTW, it may require "names.txt" and "test.txt" to be present; if you want to test, you can create two empty files with these names.</p>
<p><strong>UPD</strong> Even adding a space <em>after any single <code>(</code></em> makes everything work! Something is definitely wrong here.</p>
<p><strong>UPD2</strong> I am using Python 3.5.1</p>
<p><code>>>> python3 --version
Python 3.5.1</code></p>
<p><strong>UPD3</strong> here is my <a href="http://dropmefiles.com/zhkT9" rel="nofollow">file.</a></p>
<p><strong>UPD4</strong> and here is a hexdump: <a href="http://pastebin.com/5R1rbtc3" rel="nofollow">http://pastebin.com/5R1rbtc3</a></p>
<p><strong>UPD5</strong> apparently, this problem can only be reproduced on a Mac. I feel like different behaviour on different platforms is not intended.</p>
| 1 | 2016-10-12T17:53:07Z | 40,005,594 | <p>Characters themselves do not have an encoding - it does not make sense to say a character is UTF-8. UTF-8 is just one of many encodings that can be used to represent a character. You do have non-ASCII characters in your program, and based on the error, the source file is being saved in an encoding other than UTF-8. Because the non-UTF-8 encoding is not declared in the source file, Python does not know what encoding to use instead of UTF-8, resulting in the error. The best solution would be to tell your editor to save the file using UTF-8, but obviously the process for doing so will be specific to your editor.</p>
| 0 | 2016-10-12T18:14:19Z | [
"python",
"python-3.x",
"utf-8",
"character-encoding"
] |
socket.error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted | 40,005,251 | <p>i am trying to make a server-client md5 decription
the server sends how many cores he have(cpu)
and the client slices him th range for multiproccesing
(brute force)
but the server throws me the "socket.error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted" error
any suggestion?</p>
<p>client:</p>
<pre><code>import socket
RANGE=10000
d="7a2b33c672ce223b2aa5789171ddde2f"
d=d.lower()
HOMEADDRES='127.0.0.1'
PORT=2345
ADDRESS=(HOMEADDRES,PORT)
my_socket=socket.socket(socket.AF_INET ,socket.SOCK_STREAM)
my_socket.connect((HOMEADDRES,PORT))
def main():
ranges=""
my_socket.send(d)
cores=int(my_socket.recv(1024))
borders=[0]
for i in range(1,cores+1):
borders.append(RANGE*i/cores)
for i in range(len(borders)):
ranges+=str(borders[i])+"#"
ranges=ranges[:-1]
print ranges
my_socket.send(ranges)
print my_socket.recv(1024)
my_socket.close()
if __name__ == '__main__':
main()
</code></pre>
<p>server:</p>
<pre><code>import socket
import multiprocessing
import hashlib
IP_ADD='0.0.0.0'
PORT=2345
ADDRESS = (IP_ADD,PORT)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(ADDRESS)
server_socket.listen(1)
client_socket, address = server_socket.accept()
print "connected"
def decrypt(low,high,d):
print "1"
i=low
while i<high:
m=hashlib.md5()
m.update(str((i)))
if m.hexdigest()==d:
client_socket.send(i)
client_socket.close()
server_socket.close()
i+=1
def main():
d=client_socket.recv(1024)
client_socket.send(str(multiprocessing.cpu_count()))
borders=client_socket.recv(1024)
borders=borders.split("#")
for i in range(len(borders)-1):
p=multiprocessing.Process(target=decrypt, args=(borders[i],borders[i+1],d))
p.start()
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-10-12T17:54:36Z | 40,005,441 | <p>You're creating your server socket in the module scope so as soon as the module is imported, it is created and bound to (0.0.0.0, 2345).</p>
<p>Multiprocessing will cause the module to be (re)imported in the new process it creates, so that process will immediately try to create the same server socket on port 2345 and that is impossible.</p>
<p>My suggestion is either don't create your server socket in the module scope but do it in main() or move the multiprocessing stuff into its own module.</p>
| 0 | 2016-10-12T18:05:01Z | [
"python",
"sockets",
"multiprocessing",
"md5"
] |
Optimization of for loop in python | 40,005,264 | <p>I am executing the following code for different time stamps and each will have close to one million records. It took more than one hour for one date and I have the data for a total of 35 dates.</p>
<p>Is there a way to optimize this code?</p>
<pre><code>def median(a, b, c,d,e):
I=[a,b,c,d,e]
I.sort()
return I[2]
for i in range(2, len(df['num'])-2):
num_smooth= median(df['num'][i-1], df['num'][i-2], df['num'][i],
df['num'][i+1], df['num'][i+2])
df.set_value(i,'num_smooth',num_smooth)
df['num_smooth'].fillna(df['num'], inplace=True)
...........................................
Remaining code
</code></pre>
| 1 | 2016-10-12T17:55:29Z | 40,005,585 | <p>I'm guessing that your <code>df</code> is a Pandas <code>DataFrame</code> object. Pandas has built-in functionality to compute rolling statistics, including a rolling median. This functionality is available via the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html" rel="nofollow"><code>rolling</code></a> method on Pandas <code>Series</code> and <code>DataFrame</code> objects.</p>
<pre><code>>>> s = pd.Series(np.random.rand(10))
>>> s
0 0.500538
1 0.598179
2 0.747391
3 0.371498
4 0.244869
5 0.930303
6 0.327856
7 0.317395
8 0.190386
9 0.976148
dtype: float64
>>> s.rolling(window=5, center=True).median()
0 NaN
1 NaN
2 0.500538
3 0.598179
4 0.371498
5 0.327856
6 0.317395
7 0.327856
8 NaN
9 NaN
dtype: float64
</code></pre>
<p>See the Pandas documentation on <a href="http://pandas.pydata.org/pandas-docs/stable/computation.html#window-functions" rel="nofollow">Window Functions</a> for more general information on using <code>rolling</code> and related functionality. As a general rule, when performance matters you should prefer using built-in Pandas and NumPy functions and methods over explicit Python-level <code>for</code> loops, though as always, you should profile your solutions to be sure. On my machine, working with a <code>df['num']</code> series containing one million random floats, the <code>rolling</code>-based solution takes approximately 129 seconds, while the <code>for</code>-loop based solution takes around 0.61 seconds, so using <code>rolling</code> speeds the code up by a factor of over 200.</p>
<p>So in your case,</p>
<pre><code>df['num_smooth'] = df['num'].rolling(window=5, center=True).median()
</code></pre>
<p>along with the <code>fillna</code> step that you already have should give you something close to what you need.</p>
<p>Note that the syntax for computing rolling statistics changed in Pandas 0.18, so you'll need at least version 0.18 to use the above code. For earlier versions of Pandas, look into the <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_median.html#pandas-rolling-median" rel="nofollow"><code>rolling_median</code></a> function.</p>
| 4 | 2016-10-12T18:13:58Z | [
"python",
"loops",
"pandas",
"for-loop",
"optimization"
] |
Optimization of for loop in python | 40,005,264 | <p>I am executing the following code for different time stamps and each will have close to one million records. It took more than one hour for one date and I have the data for a total of 35 dates.</p>
<p>Is there a way to optimize this code?</p>
<pre><code>def median(a, b, c,d,e):
I=[a,b,c,d,e]
I.sort()
return I[2]
for i in range(2, len(df['num'])-2):
num_smooth= median(df['num'][i-1], df['num'][i-2], df['num'][i],
df['num'][i+1], df['num'][i+2])
df.set_value(i,'num_smooth',num_smooth)
df['num_smooth'].fillna(df['num'], inplace=True)
...........................................
Remaining code
</code></pre>
| 1 | 2016-10-12T17:55:29Z | 40,006,321 | <p>A nice tool for profiling python code performance line by line is <a href="https://github.com/rkern/line_profiler" rel="nofollow">kernprof</a>.</p>
| 0 | 2016-10-12T18:56:31Z | [
"python",
"loops",
"pandas",
"for-loop",
"optimization"
] |
How to concatenate two columns and update the csv in python? | 40,005,265 | <p>In Excel, I would be able to use something like this:</p>
<pre><code>=CONCATENATE(A1," ",B1)
</code></pre>
<p>(User flood fill's this down the spreadsheet, and then simply deletes A and B, lastly you move results to A)</p>
<p>End Result is expected to have A and B columns merged into one column (A) and separated by one space.</p>
<p>In Python here is what I have so far:</p>
<pre><code>import csv
with open("test.csv","rb") as source:
rdr= csv.reader( source )
with open("result","wb") as result:
wtr= csv.writer( result )
for r in rdr:
print("Adding merged COL1/COL2 into one column for every row...")
wtr.writerow(r+[r[0] + ' ' + r[1]])
print("Deleting COL1/COL2 columns from every row...")
del r[0]
del r[0]
wtr.writerow( r )
result.close();
</code></pre>
<p>Although, the above code does properly merge two columns and append a column to the end of the file, it does not properly delete the first two rows once it is finished, I believe this is because wtr.writerow has already been called. Also, I am unsure how to move the column to the left (back to A), since it always appends to the end.</p>
| 0 | 2016-10-12T17:55:32Z | 40,005,472 | <p>You're calling <code>writerow</code> twice in that loop. I don't think you want that - writing the merged columns and then the others separately? No.</p>
<p>You can simply join the merged columns to the <em>start</em> of the rows, and <em>slice off</em> the old rows:</p>
<pre><code>wtr.writerow([r[0] + ' ' + r[1]] + r[2:])
# ^<- merged rows are added to the start
# ^<- slice off old A1 and B1
</code></pre>
<p>You won't need the <code>del</code> statements any longer, and one call to <code>writerow</code> inserts your modified <em>row</em>:</p>
<pre><code>import csv
with open("test.csv","rb") as source, open("result","wb") as result:
rdr = csv.reader(source)
wtr = csv.writer(result)
for r in rdr:
wtr.writerow([r[0] + ' ' + r[1]] + r[2:])
</code></pre>
<p>Also, note that you can put multiple expressions after a <code>with</code> statement, like I did above.</p>
<hr>
<p>Finally, you don't need to manually close the file - <code>result.close()</code>. The <code>with</code> context already <em>manages</em> that.</p>
| 1 | 2016-10-12T18:07:02Z | [
"python",
"csv"
] |
How to concatenate two columns and update the csv in python? | 40,005,265 | <p>In Excel, I would be able to use something like this:</p>
<pre><code>=CONCATENATE(A1," ",B1)
</code></pre>
<p>(User flood fill's this down the spreadsheet, and then simply deletes A and B, lastly you move results to A)</p>
<p>End Result is expected to have A and B columns merged into one column (A) and separated by one space.</p>
<p>In Python here is what I have so far:</p>
<pre><code>import csv
with open("test.csv","rb") as source:
rdr= csv.reader( source )
with open("result","wb") as result:
wtr= csv.writer( result )
for r in rdr:
print("Adding merged COL1/COL2 into one column for every row...")
wtr.writerow(r+[r[0] + ' ' + r[1]])
print("Deleting COL1/COL2 columns from every row...")
del r[0]
del r[0]
wtr.writerow( r )
result.close();
</code></pre>
<p>Although, the above code does properly merge two columns and append a column to the end of the file, it does not properly delete the first two rows once it is finished, I believe this is because wtr.writerow has already been called. Also, I am unsure how to move the column to the left (back to A), since it always appends to the end.</p>
| 0 | 2016-10-12T17:55:32Z | 40,005,520 | <p>So every row you're reading from (and writing to) csv is a list, right? So take another step or two and create the list you want, then write it.</p>
<p>e.g.</p>
<pre><code>import csv
with open('test.csv') as f:
reader = csv.reader(f)
with open('output.csv', 'w') as g:
writer = csv.writer(g)
for row in reader:
new_row = [' '.join([row[0], row[1]])] + row[2:]
writer.writerow(new_row)
</code></pre>
<p>Also, I doubt you need to read/write binary ('rb', 'wb') from a csv.</p>
| 0 | 2016-10-12T18:09:23Z | [
"python",
"csv"
] |
What can you do with a PyDictValues_Type? | 40,005,285 | <p>While trying to convert some Python/C API code to work in both 2 & 3, I found that, given the following Python</p>
<pre><code>DICT = { ⦠}
class Example(object):
ITEMS = DICT.values()
</code></pre>
<p>and then calling <code>PyObject_GetAttrString(an_example, "ITEMS")</code> would yield a <code>PyObject</code> for which <code>PySequence_Check</code> would return true in 2.7. Now in 3.4, it's yielding a <code>PyObject</code> whose type is <code>PyDictValues_Type</code> and <code>PySequence_Check</code> doesn't return true. The documentation on <code>PyDictValues</code> is, ahem, sparse. What can one do with it? It also response false to <code>PyIter_Check</code>.</p>
| 0 | 2016-10-12T17:56:26Z | 40,005,713 | <p>Basically just <code>iter</code> (<code>PyObject_GetIter</code> in the C API).</p>
<p>There are technically other operations, like <code>==</code> (inherited from <code>object</code>, uninteresting), <code>len</code> (but you'd call that on the dict instead of making a values view if you wanted that), and <code>in</code> (slow, linear scan, avoid it), but the primary use of a values view is as an iterable.</p>
<p>If you want a list, like Python 2, using the C API call <code>PyDict_Values</code> on the dict instead of calling the <code>values</code> method still makes a list.</p>
<p>Keys and items views (<code>keys()</code> and <code>items()</code>) are more interesting. They support all the operations in the <a href="https://docs.python.org/3/library/collections.abc.html#module-collections.abc" rel="nofollow"><code>collections.abc.Set</code></a> interface, which you'd access through the usual C API equivalents of those operations (so things like <code>PyObject_RichCompare</code> or <code>PySequence_Contains</code>, even though they're not sequences).</p>
| 1 | 2016-10-12T18:20:36Z | [
"python",
"python-2.7",
"python-3.4",
"python-c-api"
] |
What can you do with a PyDictValues_Type? | 40,005,285 | <p>While trying to convert some Python/C API code to work in both 2 & 3, I found that, given the following Python</p>
<pre><code>DICT = { ⦠}
class Example(object):
ITEMS = DICT.values()
</code></pre>
<p>and then calling <code>PyObject_GetAttrString(an_example, "ITEMS")</code> would yield a <code>PyObject</code> for which <code>PySequence_Check</code> would return true in 2.7. Now in 3.4, it's yielding a <code>PyObject</code> whose type is <code>PyDictValues_Type</code> and <code>PySequence_Check</code> doesn't return true. The documentation on <code>PyDictValues</code> is, ahem, sparse. What can one do with it? It also response false to <code>PyIter_Check</code>.</p>
| 0 | 2016-10-12T17:56:26Z | 40,005,727 | <p>In Python 2, <code>dict.values()</code> returns a list, but in Python 3, it's a view of dictionary values. The equivalent in Python 2.7 is <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects" rel="nofollow"><code>dict.viewvalues()</code></a>.</p>
<p>In particular views are not sequences because dictionaries don't have orders. So <code>dict.viewkeys()</code> and <code>dict.viewitems()</code> are set-like, because keys have to be unique. <code>dict.viewvalues()</code> is multi-set-like. You can iterate over it, get the length, and do contains checks against it. But you can't index into it like a sequence.</p>
| 1 | 2016-10-12T18:21:21Z | [
"python",
"python-2.7",
"python-3.4",
"python-c-api"
] |
Selenium - Difficulty finding input element on page (Python) | 40,005,293 | <p>I am having trouble finding a search bar on a webpage that I am trying to automate. I have tried a couple approaches but being rather new to selenium, I am not sure what more advanced locating options there are.</p>
<p>Breakdown::
The following is an section of code with the search bar element (corresponding to input) being highlighted</p>
<p><a href="https://i.stack.imgur.com/Zsu6g.png" rel="nofollow">The xpath to the following highlighted section is below</a>:</p>
<pre><code>//*[@id='core-content-container']/div/div[2]/div/div[1]/nav/div/div[2]/form/ul/li[1]/input
</code></pre>
<p>When I try to find this element via find_element_by_xpath however, I get a <code>NoSuchElementException</code> (I have tried shorter xpaths but those provided the same error)</p>
<p>Below is the relevant code bit I am using to try to find this element:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
#DNSMgr
driver.get('https://barista.cac.washington.edu/dnsmgr/#/fqdn')
driver.find_element_by_xpath("//div[@id='core-content-container']/div/div[2]/div/div[1]/nav/div/div[2]/form/ul/li[1]/input")
</code></pre>
<p>Since the exact line that I am trying to get at looks like this:</p>
<pre><code><input type="text" class="form-control ng-pristine ng-untouched ng-valid" ng-model="query" placeholder="Full domain name">
</code></pre>
<p>I then thought that maybe I could get at the element by using</p>
<pre><code>driver.find_element_by_css_selector('input.form-control.ng-pristine.ng-untouched.ng-valid')
</code></pre>
<p>Since this is similar to the example on seleniums python tutorials in section 4.7 I thought that could do the job but that also doesn't work (I get another <code>NoSuchElementException</code>).</p>
| 2 | 2016-10-12T17:57:11Z | 40,005,541 | <p>try with <code>driver.page_source</code> and then use beautifulSoup to find the element.</p>
| -2 | 2016-10-12T18:11:13Z | [
"python",
"selenium"
] |
Selenium - Difficulty finding input element on page (Python) | 40,005,293 | <p>I am having trouble finding a search bar on a webpage that I am trying to automate. I have tried a couple approaches but being rather new to selenium, I am not sure what more advanced locating options there are.</p>
<p>Breakdown::
The following is an section of code with the search bar element (corresponding to input) being highlighted</p>
<p><a href="https://i.stack.imgur.com/Zsu6g.png" rel="nofollow">The xpath to the following highlighted section is below</a>:</p>
<pre><code>//*[@id='core-content-container']/div/div[2]/div/div[1]/nav/div/div[2]/form/ul/li[1]/input
</code></pre>
<p>When I try to find this element via find_element_by_xpath however, I get a <code>NoSuchElementException</code> (I have tried shorter xpaths but those provided the same error)</p>
<p>Below is the relevant code bit I am using to try to find this element:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
#DNSMgr
driver.get('https://barista.cac.washington.edu/dnsmgr/#/fqdn')
driver.find_element_by_xpath("//div[@id='core-content-container']/div/div[2]/div/div[1]/nav/div/div[2]/form/ul/li[1]/input")
</code></pre>
<p>Since the exact line that I am trying to get at looks like this:</p>
<pre><code><input type="text" class="form-control ng-pristine ng-untouched ng-valid" ng-model="query" placeholder="Full domain name">
</code></pre>
<p>I then thought that maybe I could get at the element by using</p>
<pre><code>driver.find_element_by_css_selector('input.form-control.ng-pristine.ng-untouched.ng-valid')
</code></pre>
<p>Since this is similar to the example on seleniums python tutorials in section 4.7 I thought that could do the job but that also doesn't work (I get another <code>NoSuchElementException</code>).</p>
| 2 | 2016-10-12T17:57:11Z | 40,005,639 | <p>If you are getting <code>NoSuchElementException</code> as your provided exception, There could be following reasons :-</p>
<ul>
<li><p>May be when you are going to find element, it would not be present on the <code>DOM</code>, So you should implement <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow"><code>Explicit wait</code></a> using <code>WebDriverWait</code> to wait until element is present as below :-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div#core-content-container input.form-control[ng-model='query'][placeholder='Full domain name']")))
</code></pre></li>
<li><p>May be this element is inside any <code>frame</code> or <code>iframe</code>. If it is, you need to switch that <code>frame</code> or <code>iframe</code> before finding the element as below :-</p>
<pre><code> wait = WebDriverWait(driver, 10)
#Find frame or iframe and switch
wait.until(EC.frame_to_be_available_and_switch_to_it(("frame/iframe id or name")))
#Now find the element
element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div#core-content-container input.form-control[ng-model='query'][placeholder='Full domain name']")))
#Once all your stuff done with this frame need to switch back to default
driver.switch_to_default_content()
</code></pre></li>
</ul>
| 3 | 2016-10-12T18:16:10Z | [
"python",
"selenium"
] |
Fast optimization of "pathological" convex function | 40,005,320 | <p>I have a simple convex problem I am trying to speed up the solution of. I am solving the argmin (<em>theta</em>) of</p>
<p><img src="http://latex.codecogs.com/gif.latex?-%5Csum_%7Bt%3D1%7D%5E%7BT%7D%5Clog%281%20+%20%5Cboldsymbol%7B%5Ctheta%27%7D%20%5Cboldsymbol%7Br_t%7D%29" alt="eq"></p>
<p>where <em>theta</em> and <em>rt</em> is <em>Nx1</em>.</p>
<p>I can solve this easily with <code>cvxpy</code>
</p>
<pre><code>import numpy as np
from scipy.optimize import minimize
import cvxpy
np.random.seed(123)
T = 50
N = 5
R = np.random.uniform(-1, 1, size=(T, N))
cvtheta = cvxpy.Variable(N)
fn = -sum([cvxpy.log(1 + cvtheta.T * rt) for rt in R])
prob = cvxpy.Problem(cvxpy.Minimize(fn))
prob.solve()
prob.status
#'optimal'
prob.value
# -5.658335088091929
cvtheta.value
# matrix([[-0.82105079],
# [-0.35475695],
# [-0.41984643],
# [ 0.66117397],
# [ 0.46065358]])
</code></pre>
<p>But for a larger <code>R</code> this gets too slow, so I am trying a gradient based method with <code>scipy</code>'s <code>fmin_cg</code>:</p>
<p><code>goalfun</code> is a <code>scipy.minimize</code> friendly function that returns the function value and the gradient.</p>
<pre><code>def goalfun(theta, *args):
R = args[0]
N = R.shape[1]
common = (1 + np.sum(theta * R, axis=1))**-1
if np.any( common < 0 ):
return 1e2, 1e2 * np.ones(N)
fun = np.sum(np.log(common))
thetaprime = np.tile(theta, (N, 1)).T
np.fill_diagonal(thetaprime, np.ones(N))
grad = np.sum(np.dot(R, thetaprime) * common[:, None], axis=0)
return fun, grad
</code></pre>
<p>Making sure the function and gradients are correct:</p>
<pre><code>goalfun(np.squeeze(np.asarray(cvtheta.value)), R)
# (-5.6583350819293603,
# array([ -9.12423065e-09, -3.36854633e-09, -1.00983679e-08,
# -1.49619901e-08, -1.22987872e-08]))
</code></pre>
<p>But solving this just yields garbage, regardless of <code>method</code>, iterations, etc. (The only things that yields <code>Optimization terminated successfully</code> is if <code>x0</code> is practically equal to the optimal <em>theta</em>)</p>
<pre><code>x0 = np.random.rand(R.shape[1])
minimize(fun=goalfun, x0=x0, args=R, jac=True, method='CG')
# fun: 3.3690101669818775
# jac: array([-11.07449021, -14.04017873, -13.38560561, -5.60375334, -2.89210078])
# message: 'Desired error not necessarily achieved due to precision loss.'
# nfev: 25
# nit: 1
# njev: 13
# status: 2
# success: False
# x: array([ 0.00892177, 0.24404118, 0.51627475, 0.21119326, -0.00831957])
</code></pre>
<p>I.e. this seemingly innocuous problem that <code>cvxpy</code> handles with ease, turns out to be completely pathological for a non-convex solver. Is this problem really that nasty, or am I missing something? What would be an alternative to speed this up?</p>
| 1 | 2016-10-12T17:58:21Z | 40,006,227 | <p>I believe the issue is that it is possible for <code>theta</code> to be such that the <code>log</code> argument becomes negative. It seems that you have identified this issue, and have <code>goalfun</code> return the tuple <code>(100,100*ones(N))</code> in this case, apparently, as a heuristic attempt to suggest the solver that this "solution" is not <em>preferable</em>. However, a stronger condition must be imposed, i.e., this "solution" is not <em>feasible</em>. Of course, this can be done by providing appropriate constraints. (Interestingly, <code>cvxpy</code> appears to handle this issue automatically.) </p>
<p>Here is a sample run, without bothering with providing derivatives. Note the use of a feasible initial estimate <code>x0</code>.</p>
<pre><code>np.random.seed(123)
T = 50
N = 5
R = np.random.uniform(-1, 1, size=(T, N))
def goalfun(theta, *args):
R = args[0]
N = R.shape[1]
common = (1 + np.sum(theta * R, axis=1))**-1
return np.sum(np.log(common))
def con_fun(theta, *args):
R = args[0]
return 1+np.sum(theta * R, axis=1)
cons = ({'type': 'ineq', 'fun': lambda x: con_fun(x, R)})
x0 = np.zeros(R.shape[1])
minimize(fun=goalfun, x0=x0, args=R, constraints=cons)
</code></pre>
<blockquote>
<pre><code> fun: -5.658334806882614
jac: array([ 0.0019, -0.0004, -0.0003, 0.0005, -0.0015, 0. ]) message: 'Optimization terminated successfully.'
nfev: 92
nit: 12
njev: 12 status: 0 success: True
x: array([-0.8209, -0.3547, -0.4198, 0.6612, 0.4605])
</code></pre>
</blockquote>
<p>Note that when I run this, I get an <code>invalid value encountered in log</code> warning, indicating that at some point in the search a value of <code>theta</code> is checked which barely satisfies the constraints. However, the result is reasonably close to that of <code>cvxpy</code>. It would be interesting to check if the <code>cvxpy</code> solution changes when the constraints are explicitly imposed in the <code>cvxpy.Problem</code> formulation.</p>
| 2 | 2016-10-12T18:51:09Z | [
"python",
"numpy",
"scipy",
"mathematical-optimization",
"cvxopt"
] |
Python script to run docker | 40,005,397 | <p>Flow of the python script:</p>
<ul>
<li>I want to run docker image from python script. </li>
<li>After running docker image, I need to execute a shell script which creates a tar file inside docker container.</li>
<li>I need to copy that tar file to host machine from docker container.</li>
<li>and then python script should continue with some stuff to be executed on host machine.</li>
</ul>
<p>Using docker-py module, I was able to do following:</p>
<pre><code> pip install docker-py
docker version
Client:
Version: 1.12.1
API version: 1.24
Go version: go1.6.3
Git commit: 23cf638
Built: Thu Aug 18 05:22:43 2016
OS/Arch: linux/amd64
Server:
Version: 1.12.1
API version: 1.24
Go version: go1.6.3
Git commit: 23cf638
Built: Thu Aug 18 05:22:43 2016
OS/Arch: linux/amd64
>>> import docker
>>> c = docker.Client(base_url='unix://var/run/docker.sock',version='1.12',timeout=10)
>>> c.images()
[{u'Created': 1476217543, u'Labels': {}, u'VirtualSize': 5712315133, u'ParentId': u'sha256:1ba2be8d70b6ede3b68b1af50759e674345236dd952225fcbfbcc1781f370252', u'RepoTags': [u'ubuntu14.04_64:latest'], u'RepoDigests': None, u'Id': u'sha256:1c8ced0fb34d776adafaed938d41a69e3bab87466beaa8752d49bde0d81230c5', u'Size': 5712315133}]
>>> ctr = c.create_container('ubuntu14.04_64:latest')
>>> c.start(ctr)
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d685766385e7 ubuntu14.04_64:latest "bash" 16 hours ago Up 16 hours focused_fermi
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu14.04_64 latest 1c8ced0fb34d 21 hours ago 5.712 GB
</code></pre>
<p>I see docker image and container running on host, but now if I want to run shell script inside docker container, how can I do that? after that I need to copy tar from container to host also. Can someone suggest how to do this?</p>
| 0 | 2016-10-12T18:02:17Z | 40,005,799 | <p>This is probably the sequence of commands you want (borrowing from <a href="http://stackoverflow.com/a/38308399/2404152">this answer</a>):</p>
<pre><code>docker create --name tmp -it ubuntu14.04_64:latest
docker start tmp
docker exec tmp tar czvf tmp.tgz etc/os-release
docker stop tmp
docker cp tmp:tmp.tgz tmp.tgz
docker rm tmp
</code></pre>
<p>Look through <a href="http://docker-py.readthedocs.io/en/stable/api/" rel="nofollow">this documentation</a> for the equivalent commands with docker-py.</p>
| 1 | 2016-10-12T18:25:16Z | [
"python",
"python-2.7",
"docker",
"docker-compose",
"dockerpy"
] |
Python script to run docker | 40,005,397 | <p>Flow of the python script:</p>
<ul>
<li>I want to run docker image from python script. </li>
<li>After running docker image, I need to execute a shell script which creates a tar file inside docker container.</li>
<li>I need to copy that tar file to host machine from docker container.</li>
<li>and then python script should continue with some stuff to be executed on host machine.</li>
</ul>
<p>Using docker-py module, I was able to do following:</p>
<pre><code> pip install docker-py
docker version
Client:
Version: 1.12.1
API version: 1.24
Go version: go1.6.3
Git commit: 23cf638
Built: Thu Aug 18 05:22:43 2016
OS/Arch: linux/amd64
Server:
Version: 1.12.1
API version: 1.24
Go version: go1.6.3
Git commit: 23cf638
Built: Thu Aug 18 05:22:43 2016
OS/Arch: linux/amd64
>>> import docker
>>> c = docker.Client(base_url='unix://var/run/docker.sock',version='1.12',timeout=10)
>>> c.images()
[{u'Created': 1476217543, u'Labels': {}, u'VirtualSize': 5712315133, u'ParentId': u'sha256:1ba2be8d70b6ede3b68b1af50759e674345236dd952225fcbfbcc1781f370252', u'RepoTags': [u'ubuntu14.04_64:latest'], u'RepoDigests': None, u'Id': u'sha256:1c8ced0fb34d776adafaed938d41a69e3bab87466beaa8752d49bde0d81230c5', u'Size': 5712315133}]
>>> ctr = c.create_container('ubuntu14.04_64:latest')
>>> c.start(ctr)
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d685766385e7 ubuntu14.04_64:latest "bash" 16 hours ago Up 16 hours focused_fermi
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu14.04_64 latest 1c8ced0fb34d 21 hours ago 5.712 GB
</code></pre>
<p>I see docker image and container running on host, but now if I want to run shell script inside docker container, how can I do that? after that I need to copy tar from container to host also. Can someone suggest how to do this?</p>
| 0 | 2016-10-12T18:02:17Z | 40,029,242 | <p>If you want to run a script in a container you should create a <code>Dockerfile</code> which contains that script. An example might look something like this:</p>
<pre><code>FROM ubuntu14.04_64:latest
COPY ./script.sh /code/script.sh
CMD /code/script.sh -o /target/output.tar.gz
</code></pre>
<p>Then your python script would look something like this:</p>
<pre><code>#!/usr/bin/env python
import docker
c = docker.from_env()
c.build('.', image_name)
ctr = c.create_container(image_name, volumes='./target:/target')
c.start(ctr)
# the tarball is now at ./target/output.tar.gz, copy it where you want it
</code></pre>
| 1 | 2016-10-13T19:20:03Z | [
"python",
"python-2.7",
"docker",
"docker-compose",
"dockerpy"
] |
Django django.test Client post request | 40,005,411 | <p>Working on hellowebapp.com</p>
<p>Please help test valid form post using Django test client post request?</p>
<pre><code>response = self.client.post('/accounts/create_thing/', { 'name': dummy_thing.name, 'description': dummy_thing.description, })
</code></pre>
<p>Here's the TestCase Code Snippet:</p>
<pre><code>from django.test import TestCase, RequestFactory
from django.contrib.auth.models import AnonymousUser, User
from collection.models import Thing
from .views import *
from collection.forms import ThingForm
class SampleTest(TestCase):
def setUp(self):
# Every test needs access to the request factory.
self.factory = RequestFactory()
self.dummy_user = User.objects.create_user(username='dummy', password='nothings')
self.dummy_thing = Thing.objects.create(name="Dummy Book",
description="Book For Dummies.",
slug="dummy-book",
user=self.dummy_user)
def test_form(self):
dummy_thing = Thing.objects.get(name="Dummy Book")
form = ThingForm(instance=dummy_thing)
self.assertFalse(form.is_valid()) # No data has been supplied yet.
form = ThingForm({ 'name': dummy_thing.name, 'description': dummy_thing.description, }, instance=dummy_thing)
self.assertTrue(form.is_valid())
def test_form_post(self):
dummy_thing = Thing.objects.get(name="Dummy Book")
self.client.login(username=dummy_thing.user.username, password='nothings')
# Test POST invalid data
response = self.client.post('/accounts/create_thing/', { })
self.assertFormError(response, 'form', 'name', 'This field is required.')
self.assertFormError(response, 'form', 'description', 'This field is required.')
self.assertTemplateUsed(response, 'things/create_thing.html')
self.assertEqual(response.status_code, 200)
# Test POST valid data?
# response = self.client.post('/accounts/create_thing/', { 'name': dummy_thing.name, 'description': dummy_thing.description, })
# self.assertEqual(response.status_code, 200)
</code></pre>
<p>Here's the Model</p>
<p><a href="https://github.com/hellowebapp/hellowebapp-code/blob/master/collection/models.py" rel="nofollow">models.py</a></p>
<pre><code>class Thing(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField(unique=True)
user = models.OneToOneField(User, blank=True, null=True)
</code></pre>
<p>Note: user = models.OneToOneField(User, blank=True, null=True)</p>
<p>"Thing.user" must be a "User" instance.</p>
<p>column user_id is must be unique.</p>
<p><a href="https://github.com/hellowebapp/hellowebapp-code/blob/master/collection/views.py" rel="nofollow">views.py</a></p>
<pre><code>from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from collection.forms import ThingForm
from collection.models import Thing
def index(request):
things = Thing.objects.all()
return render(request, 'index.html', {
'things': things,
})
def thing_detail(request, slug):
# grab the object...
thing = Thing.objects.get(slug=slug)
# and pass to the template
return render(request, 'things/thing_detail.html', {
'thing': thing,
})
@login_required
def edit_thing(request, slug):
# grab the object...
thing = Thing.objects.get(slug=slug)
# grab the current logged in user and make sure they're the owner of the thing
if thing.user != request.user:
raise Http404
# set the form we're using...
form_class = ThingForm
# if we're coming to this view from a submitted form,
if request.method == 'POST':
# grab the data from the submitted form
form = form_class(data=request.POST, instance=thing)
if form.is_valid():
# save the new data
form.save()
return redirect('thing_detail', slug=thing.slug)
# otherwise just create the form
else:
form = form_class(instance=thing)
# and render the template
return render(request, 'things/edit_thing.html', {
'thing': thing,
'form': form,
})
def create_thing(request):
form_class = ThingForm
# if we're coming from a submitted form, do this
if request.method == 'POST':
# grab the data from the submitted form and apply to the form
form = form_class(request.POST)
if form.is_valid():
# create an instance but do not save yet
thing = form.save(commit=False)
# set the additional details
thing.user = request.user
thing.slug = slugify(thing.name)
# save the object
thing.save()
# redirect to our newly created thing
return redirect('thing_detail', slug=thing.slug)
# otherwise just create the form
else:
form = form_class()
return render(request, 'things/create_thing.html', {
'form': form,
})
def browse_by_name(request, initial=None):
if initial:
things = Thing.objects.filter(
name__istartswith=initial).order_by('name')
else:
things = Thing.objects.all().order_by('name')
return render(request, 'search/search.html', {
'things': things,
'initial': initial,
})
</code></pre>
<p>Here's the error:</p>
<pre><code>$ python manage.py test
.ECreating test database for alias 'default'...
Destroying test database for alias 'default'...
======================================================================
ERROR: test_form_post (collection.tests.SampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "E:\Working\Python\Django\Python2.7\Hello-Web-App\GitHub\Test\hellowebapp-code-master\collection\tests.py", line 36, in test_form_post
response = self.client.post('/accounts/create_thing/', { 'name': dummy_thing.name, 'description': dummy_thing.description, })
File "C:\Python27\lib\site-packages\django\test\client.py", line 541, in post
secure=secure, **extra)
File "C:\Python27\lib\site-packages\django\test\client.py", line 343, in post
secure=secure, **extra)
File "C:\Python27\lib\site-packages\django\test\client.py", line 409, in generic
return self.request(**r)
File "C:\Python27\lib\site-packages\django\test\client.py", line 494, in request
six.reraise(*exc_info)
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Working\Python\Django\Python2.7\Hello-Web-App\GitHub\Test\hellowebapp-code-master\collection\views.py", line 77, in create_thing
thing.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 947, in _do_insert
using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1043, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: column user_id is not unique
----------------------------------------------------------------------
Ran 2 tests in 0.687s
FAILED (errors=1)
</code></pre>
<p>Also, tried Django shell in vain:</p>
<pre><code>$ winpty python manage.py shell
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.test import Client
>>> csrf_client = Client(enforce_csrf_checks=True)
>>> c.login(username="dummy", password='nothings')
>>> c = Client()
>>> c.login(username="dummy", password='nothings')
True
>>> response = c.post('http://127.0.0.1:8000/accounts/create_thing/', { 'name': 'dummy book', 'description': 'book for dummies' })
Internal Server Error: /accounts/create_thing/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Working\Python\Django\Python2.7\Hello-Web-App\GitHub\Test\hellowebapp-code-master\collection\views.py", line 77, in create_thing
thing.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 947, in _do_insert
using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1043, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: column user_id is not unique
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\test\client.py", line 541, in post
secure=secure, **extra)
File "C:\Python27\lib\site-packages\django\test\client.py", line 343, in post
secure=secure, **extra)
File "C:\Python27\lib\site-packages\django\test\client.py", line 409, in generic
return self.request(**r)
File "C:\Python27\lib\site-packages\django\test\client.py", line 494, in request
six.reraise(*exc_info)
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Working\Python\Django\Python2.7\Hello-Web-App\GitHub\Test\hellowebapp-code-master\collection\views.py", line 77, in create_thing
thing.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 947, in _do_insert
using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1043, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: column user_id is not unique
>>> from django.contrib.auth.models import User
>>> users = User.objects.all()
>>> users[1]
<User: dummy>
>>> response = c.post('http://127.0.0.1:8000/accounts/create_thing/', { 'name': 'dummy book', 'description': 'book for dummies', 'user_id': users[1].id })
Internal Server Error: /accounts/create_thing/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Working\Python\Django\Python2.7\Hello-Web-App\GitHub\Test\hellowebapp-code-master\collection\views.py", line 77, in create_thing
thing.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 947, in _do_insert
using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1043, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: column user_id is not unique
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\test\client.py", line 541, in post
secure=secure, **extra)
File "C:\Python27\lib\site-packages\django\test\client.py", line 343, in post
secure=secure, **extra)
File "C:\Python27\lib\site-packages\django\test\client.py", line 409, in generic
return self.request(**r)
File "C:\Python27\lib\site-packages\django\test\client.py", line 494, in request
six.reraise(*exc_info)
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Working\Python\Django\Python2.7\Hello-Web-App\GitHub\Test\hellowebapp-code-master\collection\views.py", line 77, in create_thing
thing.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 796, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 824, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 908, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 947, in _do_insert
using=using, raw=raw)
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1043, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: column user_id is not unique
>>>exit()
</code></pre>
<p>Thanks</p>
| 0 | 2016-10-12T18:03:09Z | 40,008,078 | <p>This happens because you have <code>OneToOneField</code>, since that your every new <code>Thing</code> must be connected to <code>User</code> that wasn't picked before. So because you already had <code>dummy_thing</code> with <code>dummy_user</code> as <code>User</code>, you can't save new <code>Thing</code> instance with same <code>dummy_user</code>.</p>
<p>I believe your intention was that every <code>Thing</code> has a <code>User</code>, so you should use <code>ForeignKey</code> instead of <code>OneToOneField</code>.</p>
<p>But if i'm wrong, if you really need <code>OneToOneField</code>, then to test your <code>POST</code> request just create new user and login as new user, then <code>thing.user = request.user</code> will take <code>dummy_user2</code> and there would be no conflicts with unique values.</p>
<pre><code>class SampleTest(TestCase):
def setUp(self):
# Every test needs access to the request factory.
self.factory = RequestFactory()
self.dummy_user = User.objects.create_user(username='dummy', password='nothings')
self.dummy_thing = Thing.objects.create(name="Dummy Book",
description="Book For Dummies.",
slug="dummy-book",
user=self.dummy_user)
self.dummy_user2 = User.objects.create_user(username='dummy2', password='nothing')
def test_form_post(self):
dummy_thing = Thing.objects.get(name="Dummy Book")
self.client.login(username=dummy_thing2.user.username, password='nothing')
# Test POST invalid data
response = self.client.post('/accounts/create_thing/', { })
self.assertFormError(response, 'form', 'name', 'This field is required.')
self.assertFormError(response, 'form', 'description', 'This field is required.')
self.assertTemplateUsed(response, 'things/create_thing.html')
self.assertEqual(response.status_code, 200)
# Test POST valid data?
response = self.client.post('/accounts/create_thing/', { 'name': 'new name', 'description': 'new description', })
self.assertEqual(response.status_code, 200)
</code></pre>
| 1 | 2016-10-12T20:48:01Z | [
"python",
"django",
"django-models",
"django-forms",
"django-views"
] |
Why does my object move in the wrong direction | 40,005,470 | <p>I have a made a simple program which is meant to move a ball left and right horizontally within a canvas. The user will use the left and right keys to move the ball accordingly by 5 pixels a time. If the x coordinate of the ball is less than 40 or more than 240 then it will do nothing.</p>
<pre><code>try:
import tkinter as tk
except ImportError:
import Tkinter as Tk
window = tk.Tk()
game_area = tk.Canvas(width=270, height=400, bd=0, highlightthickness=0,
bg="white")
ball = game_area.create_oval(10, 10, 24, 24, fill="red")
game_area.move(ball, 120, 4)
coords = 120
def move_left(event):
global coords
if coords < 40:
pass
else:
coords = int(coords)- 5
game_area.move(ball, coords, 4)
game_area.update()
def move_right(event):
global coords
if coords > 240:
pass
else:
coords = int(coords)+5
game_area.move(ball, coords, 4)
game_area.update()
window.bind("<Left>", move_left)
window.bind("<Right>", move_right)
game_area.pack()
window.mainloop()
</code></pre>
<p>However, pressing either key moves the ball towards the right (more than 5 pixels across) and off the screen despite the <code>if</code> function which is meant to prevent this.</p>
| 0 | 2016-10-12T18:06:47Z | 40,005,571 | <p>According to the <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.move-method" rel="nofollow">Tkinter Canvas documentation</a>, the second argument to the <code>move</code> method, <code>dx</code>, is an offset. Try calling it like</p>
<pre><code>game_area.move(ball, -5, 4)
</code></pre>
<p>Then you don't need the following line, either.</p>
<pre><code>coords = int(coords)- 5
</code></pre>
| 2 | 2016-10-12T18:13:14Z | [
"python",
"canvas",
"tkinter",
"coordinates"
] |
Python Warm / Cold Declaring Variable outside while loop | 40,005,523 | <p>I'm writing a simple warmer / colder number guessing game in Python.</p>
<p>I have it working but I have some duplicated code that causes a few problems and I am not sure how to fix it.</p>
<pre><code>from __future__ import print_function
import random
secretAnswer = random.randint(1, 10)
gameOver = False
attempts = 0
currentGuess = int(input("Please enter a guess between 1 and 10: "))
originalGuess = currentGuess
while gameOver == False and attempts <= 6:
currentGuess = int(input("Please enter a guess between 1 and 10: "))
attempts += 1
originalDistance = abs(originalGuess - secretAnswer)
currentDistance = abs(currentGuess - secretAnswer)
if currentDistance < originalDistance and currentGuess != secretAnswer:
print("Getting warmer")
elif currentDistance > originalDistance:
print("Getting colder")
if currentDistance == originalDistance:
print("You were wrong, try again")
if currentGuess == secretAnswer or originalGuess == secretAnswer:
print("Congratulations! You are a winner!")
gameOver = True
if attempts >= 6 and currentGuess != secretAnswer:
print("You lose, you have ran out of attempts.")
gameOver = True
print("Secret Answer: ", secretAnswer)
print("Original Dist: ", originalDistance)
print("Current Dist: ", currentDistance)
</code></pre>
<p>It asks for input before I enter the loop, which is to allow me to set an original guess variable helping me to work out the distance from my secret answer.</p>
<p>However, because this requires input before the loop it voids any validation / logic I have there such as the if statements, then requires input directly after this guess, now inside the loop. </p>
<p>Is there a way for me to declare originalGuess inside the loop without it updating to the user input guess each iteration or vice versa without duplicating currentGuess?</p>
<p>Thanks</p>
| 0 | 2016-10-12T18:09:44Z | 40,005,688 | <p>There doesn't seem to be a need to ask the user before you enter the loop... You can just check if guesses = 1 for the first guess...</p>
<pre><code>gameOver=False
guesses = 0
while not gameOver:
guesses += 1
getUserInput
if guesses = 1 and userInput != correctAnswer:
print "try again!"
checkUserInput
print "good job!, it took you {} guesses!".format(guesses)
</code></pre>
| 1 | 2016-10-12T18:18:46Z | [
"python",
"while-loop"
] |
Paramiko Buffer issue | 40,005,531 | <p>I have a problem of buffer using paramiko, I found the same question <a href="http://stackoverflow.com/q/12486623/2662302">here</a> and one of the solutions states that:</p>
<blockquote>
<p>Rather than using .get(), if you just call .open() to get an SFTPFile
instance, then call .read() on that object, or just hand it to the
Python standard library function shutil.copyfileobj() to download the
contents. That should avoid the Paramiko prefetch cache, and allow you
to download the file even if it's not quite as fast.</p>
</blockquote>
<p>Now if I have:</p>
<pre><code>ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host,username=user,password=pwd)
sftp=ssh.open_sftp()
sftp_file=sftp.open(remote_file_adress)
</code></pre>
<p>How I save this file-like-object in a csv in my local pc? (the original file is a csv also)</p>
| 0 | 2016-10-12T18:10:24Z | 40,006,130 | <p>Here is a working example that fetches copies a test file on your local machine. The file is much smaller than 1 GIG but gives the general plan.</p>
<pre><code>import paramiko
import os
import shutil
import time
import getpass
# get params
user = getpass.getuser()
pwd = getpass.getpass("Enter password: ")
bufsize = 2**20
host = 'localhost'
test_file_lines = 1000000
# create test file
now = time.asctime()
testfile_path = os.path.abspath('deleteme')
local_path = 'deleteme.copy'
print('writing test file...')
start = time.time()
with open(testfile_path, 'w') as fp:
for _ in range(test_file_lines):
fp.write(now + '\n')
delta = time.time() - start
file_size = os.stat(testfile_path).st_size
print("file size %d, %d KB/Sec" % (file_size, file_size/1024/delta))
# make connection
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host,username=user,password=pwd)
sftp=ssh.open_sftp()
sftp_file=sftp.open(testfile_path, bufsize=bufsize)
print('copying file...')
start = time.time()
shutil.copyfileobj(sftp_file,
open(local_path, 'wb', bufsize),
bufsize)
delta = time.time() - start
print('%.3f seconds, %d KB/Sec' % (delta, file_size/1024/delta))
#assert open(testfile_path).read() == open(local_path).read(), "files match"
</code></pre>
<p>Running on my machine I got</p>
<pre><code>Enter password:
writing test file...
file size 25000000, 21017 KB/Sec
copying file...
10.225 seconds, 2387 KB/Sec
</code></pre>
<p>We expect some slow down because there is a read and a write plus network costs (its to local host so doesn't really touch the wire), but that does seem kinda slow. I am using a low-powered laptop with 2 cores and between this app and sshd, used much of the cpu, presumably to do the encryption. A higher powered machine may work better.</p>
| 1 | 2016-10-12T18:44:48Z | [
"python",
"csv",
"paramiko"
] |
Why will my build_heap method not stop running? | 40,005,591 | <p>I have written a class for a <code>MinHeap</code> class and created a <code>build_heap</code> method. Whenever I call the <code>build_heap</code> function the program continues to run unless I keyboard interrupt it. The heap appears to built when I interrupt the function call, but I am curious as to why the function appears to be running infinitely.</p>
<p>MinHeap Class:</p>
<pre><code>class MinHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def perc_up(self, index):
while index // 2 > 0:
if self.heap_list[index] < self.heap_list[index // 2]:
temp = self.heap_list[index // 2]
self.heap_list[index // 2] = self.heap_list[index]
self.heap_list[index] = temp
index = index // 2
def perc_down(self, index):
while (index * 2) <= self.current_size:
mc = self.min_child(index)
if self.heap_list[index] > self.heap_list[mc]:
temp = self.heap_list[index]
self.heap_list[index] = self.heap_list[mc]
self.heap_list[mc] = temp
i = mc
def min_child(self, index):
if (index * 2 + 1) > self.current_size:
return index * 2
else:
if self.heap_list[index * 2] < self.heap_list[index * 2 + 1]:
return index * 2
else:
return index * 2 + 1
def insert(self, value):
self.heap_list.append(value)
self.current_size += 1
self.perc_up(self.current_size)
def peek(self):
return self.heap_list[1]
def del_min(self):
ret_val = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.current_size]
self.heap_list.pop()
self.perc_down(1)
return ret_val
def is_empty(self):
if self.current_size == 0:
return True
else:
return False
def size(self):
return self.current_size
def build_heap(self, a_list):
i = len(a_list) // 2
self.current_size = len(a_list)
self.heap_list = [0] + a_list[:]
while (i > 0):
self.perc_down(i)
i = i - 1
</code></pre>
<p>Output when calling build_heap:</p>
<pre><code>>>> heap = MinHeap()
>>> lyst = [ 1, 3, 6, 19, 13, 4, 2]
>>> heap.build_heap(lyst)
</code></pre>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
heap.build_heap(lyst)
File "C:/Users/frost_000/Documents/Python Files/MinHeap.py", line 62, in build_heap
self.perc_down(i)
File "C:/Users/frost_000/Documents/Python Files/MinHeap.py", line 16, in perc_down
while (index * 2) <= self.current_size:
KeyboardInterrupt
</code></pre>
<pre class="lang-python prettyprint-override"><code>>>> heap.heap_list
>>> [0, 1, 3, 2, 19, 13, 4, 6]
</code></pre>
| 2 | 2016-10-12T18:14:06Z | 40,006,405 | <p>The problem is <code>perc_down()</code> never returns when <code>build_help()</code> call it. This is because the condition <code>(index * 2) <= self.current_size</code> never changes and is always <code>True</code> because it's not affected by any of the statements within the <code>while</code> loop.</p>
<p>With the change and addition shown, it seems to now work:</p>
<pre><code>class MinHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def perc_up(self, index):
while index // 2 > 0:
if self.heap_list[index] < self.heap_list[index // 2]:
temp = self.heap_list[index // 2]
self.heap_list[index // 2] = self.heap_list[index]
self.heap_list[index] = temp
index = index // 2
def perc_down(self, index):
while (index * 2) <= self.current_size:
mc = self.min_child(index)
if self.heap_list[index] > self.heap_list[mc]:
temp = self.heap_list[index]
self.heap_list[index] = self.heap_list[mc]
self.heap_list[mc] = temp
index = mc #### changed
def min_child(self, index):
if (index * 2 + 1) > self.current_size:
return index * 2
else:
if self.heap_list[index * 2] < self.heap_list[index * 2 + 1]:
return index * 2
else:
return index * 2 + 1
def insert(self, value):
self.heap_list.append(value)
self.current_size += 1
self.perc_up(self.current_size)
def peek(self):
return self.heap_list[1]
def del_min(self):
ret_val = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.current_size]
self.heap_list.pop()
self.current_size -= 1 #### added
self.perc_down(1)
return ret_val
def is_empty(self):
if self.current_size == 0:
return True
else:
return False
def size(self):
return self.current_size
def build_heap(self, a_list):
i = len(a_list) // 2
self.current_size = len(a_list)
self.heap_list = [0] + a_list[:]
while (i > 0):
print('i: {}'.format(i))
self.perc_down(i)
i = i - 1
heap = MinHeap()
lyst = [ 1, 3, 6, 19, 13, 4, 2]
heap.build_heap(lyst)
</code></pre>
| 1 | 2016-10-12T19:01:36Z | [
"python",
"heap",
"interrupt"
] |
Count number of tabs open in Selenium Python | 40,005,611 | <p>How do I count number of tabs are being opened in Browser by using Python Selenium?</p>
| 0 | 2016-10-12T18:15:09Z | 40,005,827 | <blockquote>
<p>How do I count number of tabs are being opened in Browser by using Python Selenium?</p>
</blockquote>
<p>Since provided <a href="http://sqa.stackexchange.com/questions/9553/counting-the-number-of-browser-windows-opened-by-selenium">link answer</a> doesn't have any answer in python, you can get the count number of tabs opened in browser using <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.window_handles" rel="nofollow"><code>WebDriver#window_handles</code></a> as below :-</p>
<pre><code>len(driver.window_handles)
</code></pre>
| 0 | 2016-10-12T18:26:56Z | [
"python",
"selenium",
"count",
"tabs"
] |
Please tell me why this deadlocks: Reading and writing from Paramiko exec_command() file-like objects -- ChannelFile.close() does not work | 40,005,673 | <pre><code>import paramiko, threading
def Reader(src):
while True:
data = src.readline()
if not data: break
print data
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("172.17.0.2", username="test", password="test")
stdin, stdout, stderr = client.exec_command("dd of=readme.txt")
reader = threading.Thread(target=Reader, args=(stderr, ))
reader.start()
stdin.write("some data")
stdin.flush()
stdin.close()
reader.join()
</code></pre>
<p>This code waits forever at the join(). If I remove the stderr writing thread it works as expected, with the correct text being written to the file 'readme.txt', but I then lose the dd stderr messages.</p>
| 0 | 2016-10-12T18:17:43Z | 40,011,587 | <p>The probblem is in <code>stdin.close()</code>. According to Paramiko's doc (v1.16):</p>
<blockquote>
<p><strong>Warning:</strong> To correctly emulate the file object created from a socketâs <code>makefile()</code> method, a <code>Channel</code> and its <code>ChannelFile</code> should be able to be closed or garbage-collected independently. <strong>Currently, closing the <code>ChannelFile</code> does nothing but <em>flush</em> the buffer.</strong></p>
</blockquote>
<p>So you have to use <code>stdin.channel.close()</code>.</p>
<hr>
<p><strong>UPDATE:</strong></p>
<p>Since <em>stdin</em>, <em>stdout</em> and <em>stderr</em> all share one single channel, <code>stdin.channel.close()</code> will also close <em>stderr</em> so your <code>Reader</code> thread may get nothing. The solution is to use <code>stdin.channel.shutdown_write()</code> which disallows writing to the channel but still allows reading from the channel.</p>
<p>Verified it works fine:</p>
<pre class="lang-none prettyprint-override"><code>[STEP 101] # cat foo.py
import paramiko, threading, paramiko
def Reader(src):
while True:
data = src.read()
if not data: break
print data,
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("10.11.12.13", username="root", password="password")
stdin, stdout, stderr = client.exec_command("dd of=/tmp/file")
reader = threading.Thread(target=Reader, args=(stderr,) )
reader.start()
stdin.write("some data")
stdin.flush()
stdin.channel.shutdown_write()
reader.join()
[STEP 102] # python foo.py
0+1 records in
0+1 records out
[STEP 103] #
</code></pre>
| 2 | 2016-10-13T03:00:58Z | [
"python",
"paramiko"
] |
How to get current user from a Django Channels web socket packet? | 40,005,701 | <p>I was following this tutorial: <a href="https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django" rel="nofollow">Finally, Real-Time Django Is Here: Get Started with Django Channels</a>.</p>
<p>I wanted to extend the app by using Django User objects instead of the <code>handle</code> variable. <strong>But how can I get the current user from the received WebSocket packet in my <code>ws_recieve(message)</code> function?</strong></p>
<p>I noticed that both the <code>csrftoken</code> and the first ten digits of <code>sessionid</code> from the web socket packet match a normal HTTP request. Can I get the current user with this information?</p>
<p>For reference the received packet looks like this:</p>
<pre><code>{'channel': <channels.channel.Channel object at 0x110ea3a20>,
'channel_layer': <channels.asgi.ChannelLayerWrapper object at 0x110c399e8>,
'channel_session': <django.contrib.sessions.backends.db.SessionStore object at 0x110d52cc0>,
'content': {'client': ['127.0.0.1', 52472],
'headers': [[b'connection', b'Upgrade'],
[b'origin', b'http://0.0.0.0:8000'],
[b'cookie',
b'csrftoken=EQLI0lx4SGCpyTWTJrT9UTe1mZV5cbNPpevmVu'
b'STjySlk9ZJvxzHj9XFsJPgWCWq; sessionid=kgi57butc3'
b'zckszpuqphn0egqh22wqaj'],
[b'cache-control', b'no-cache'],
[b'sec-websocket-version', b'13'],
[b'sec-websocket-extensions',
b'x-webkit-deflate-frame'],
[b'host', b'0.0.0.0:8000'],
[b'upgrade', b'websocket'],
[b'sec-websocket-key', b'y2Lmb+Ej+lMYN+BVrSXpXQ=='],
[b'user-agent',
b'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '
b'AppleWebKit/602.1.50 (KHTML, like Gecko) Version'
b'/10.0 Safari/602.1.50'],
[b'pragma', b'no-cache']],
'order': 0,
'path': '/chat-message/',
'query_string': '',
'reply_channel': 'websocket.send!UZaOWhupBefN',
'server': ['127.0.0.1', 8000]},
'reply_channel': <channels.channel.Channel object at 0x110ea3a90>}
</code></pre>
| 3 | 2016-10-12T18:19:38Z | 40,007,005 | <p>You can get access to a <code>user</code> and <code>http_session</code> attributes of your <code>message</code> by changing the decorators in <code>consumers.py</code> to match the docs:</p>
<blockquote>
<p>You get access to a userâs normal Django session using the <code>http_session decorator</code> - that gives you a <code>message.http_session</code> attribute that behaves just like <code>request.session</code>. You can go one further and use <code>http_session_user</code> which will provide a <code>message.user</code> attribute as well as the session attribute. </p>
</blockquote>
<p>so the <a href="https://github.com/jacobian/channels-example/blob/master/chat/consumers.py" rel="nofollow"><code>consumers.py</code></a> file in the example should become the following: </p>
<pre><code>from channels.auth import http_session_user, channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def ws_connect(message):
...
...
@channel_session_user
def ws_receive(message):
# You can check for the user attr like this
log.debug('%s', message.user)
...
...
@channel_session_user
def ws_disconnect(message):
...
...
</code></pre>
<p><strong>Notice the decorators change</strong>.<br>
Also, i suggest you don't build anything upon that example</p>
<p>for more details see: <a href="https://channels.readthedocs.io/en/stable/getting-started.html#authentication" rel="nofollow">https://channels.readthedocs.io/en/stable/getting-started.html#authentication</a> </p>
| 2 | 2016-10-12T19:40:41Z | [
"python",
"django",
"sockets",
"session",
"django-channels"
] |
Posting file to Flask with cURL returns 400 error | 40,005,703 | <p>I want to post a file using cURL to a Flask view. However, I get a 400 error in response. Why does the command below fail?</p>
<pre><code>@app.route('/deploy/partial', methods=['POST'])
def postfile():
try:
file = request.files['file']
filename = secure_filename(file.filename)
file.save(os.path.join('/home/test/test.txt', filename))
return 'OK', 200
except:
print("Unexpected error:", sys.exc_info()[0])
raise
</code></pre>
<pre class="lang-none prettyprint-override"><code>curl -X POST -H "Content-Type: multipart/form-data" -F "file=@FILEPATH" http://127.0.0.1:25252/deploy/partial
Unexpected error: <class 'werkzeug.exceptions.HTTPException.wrap.<locals>.newcls'>
127.0.0.1 - - [12/Oct/2016 22:57:43] "POST /deploy/partial HTTP/1.1" 400
HTTP/1.1 100 Continue
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html
Content-Length: 192
Server: Werkzeug/0.11.11 Python/3.4.3
Date: Wed, 12 Oct 2016 19:31:07 GMT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
</code></pre>
| -1 | 2016-10-12T18:19:58Z | 40,015,377 | <p>I got the </p>
<p>Unexpected error: .newcls'></p>
<p>after I accidentally renamed request.form['name'] to request.form['ame']
(note the wrong 'ame') while my form field is
name = StringField(...)</p>
<p>I changed request.form['ame'] to request.form['name'] and the error disappeared, i.e. flask works</p>
<p>Not sure if this is your case too.</p>
| 0 | 2016-10-13T07:59:03Z | [
"python",
"curl",
"flask"
] |
How does sp_randint work? | 40,005,795 | <p>I am doing hyperparameter optimisation of Random Forest classifier. I am planning to use RandomSearchCV. </p>
<p>So by checking the available code in Scikit learn: What does sp_randint do?
Does it randomly take a value from 1 to 11? Can it be replaced by other function?</p>
<pre><code> from scipy.stats import randint as sp_randint
param_dist = {"n_estimators": sp_randint (1, 11),
"max_depth": [3, None],
"max_features": sp_randint(1, 11),
"min_samples_split": sp_randint(1, 11),
"min_samples_leaf": sp_randint(1, 11),
}
</code></pre>
<p>Thank you.</p>
| 1 | 2016-10-12T16:10:17Z | 40,005,796 | <p><a href="http://scikit-learn.org/0.17/modules/generated/sklearn.grid_search.RandomizedSearchCV.html" rel="nofollow"><code>sklearn.grid_search.RandomizedSearchCV</code></a> can get a <code>param_distributions</code> parameter, mapping parameters to random distributions supporting the <code>rvs</code> method.</p>
<p>In your example, this object will return random integers in the range $[1, 11)$:</p>
<pre><code>In [8]: g = sp_randint(1, 11)
In [9]: g.rvs(20)
Out[9]:
array([ 5, 2, 9, 10, 6, 9, 9, 8, 1, 5, 1, 8, 1, 5, 5, 4, 6,
5, 8, 4])
</code></pre>
<p>You can change it to any other object meaningfully supporting the <code>rvs</code> method, or even a list. For example:</p>
<pre><code>param_dist = {"n_estimators": [1, 3, 4],
"max_depth": [3, None],
"max_features": [1, 3, 4],
"min_samples_split": [1, 3, 4],
"min_samples_leaf": [1, 3, 4],
}
</code></pre>
<p>will work as well.</p>
| 2 | 2016-10-12T17:29:15Z | [
"machine-learning",
"python",
"optimization",
"scikit-learn",
"scipy"
] |
Create a new column based on several lookup tables in Python Pandas | 40,005,854 | <p>I have a large pandas dataframe (<code>df_orig</code>) and several lookup tables (also dataframes) that correspond to each of the segments in <code>df_orig</code>.</p>
<p>Here's a small subset of <code>df_orig</code>:</p>
<pre><code>segment score1 score2
B3 0 700
B1 0 120
B1 400 950
B1 100 220
B1 200 320
B1 650 340
B5 300 400
B5 0 320
B1 0 240
B1 100 360
B1 940 700
B3 100 340
</code></pre>
<p>And here's a lookup table in its entirety for segment B5 called <code>thresholds_b5</code> (there is a lookup table for each segment in the large dataset):</p>
<pre><code>score1 score2
990 220
980 280
970 200
960 260
950 260
940 200
930 240
920 220
910 220
900 220
850 120
800 220
750 220
700 120
650 200
600 220
550 220
500 240
400 240
300 260
200 300
100 320
0 400
</code></pre>
<p>I want to create a new column in my large dataset that analagous to this SQL logic:</p>
<pre class="lang-SQL prettyprint-override"><code>case when segment = 'B5' then
case when score1 = 990 and score2 >= 220 then 1
case when score1 = 980 and score2 >= 280 then 1
.
.
.
else 0
case when segment = 'B1' then
.
.
.
else 0 end as indicator
</code></pre>
<p>I was able to get the correct output using a loop based on the solution to <a href="https://stackoverflow.com/questions/36497396/how-do-i-create-a-new-column-based-on-conditions-of-other-columns-in-pandas">this question</a>:</p>
<pre><code>df_b5 = df_orig[df_orig.loc[:,'segment'] == 'B5']
for i,row in enumerate(thresholds_b5):
value1 = thresholds_b5.iloc[i,0]
value2 = thresholds_b5.iloc[i,1]
df_b5.loc[(df_b5['score1'] == value1) & (df_b5['score2'] >= value2), 'indicator'] = 1
</code></pre>
<p>However, I'd need another loop to run this for each segment and then append all of the resultant dataframes back together, which is a bit messy. Furthermore, while I only have three segments (B1,B3,B5) for now, I'm going to have 20+ segments in the future.</p>
<p>Is there a way to do this more succinctly and preferably without loops? I've been warned that loops over dataframes tend to be slow and given the size of my dataset I think speed will matter.</p>
| 2 | 2016-10-12T18:28:51Z | 40,006,129 | <p>If you are ok with sorting the DataFrames ahead of time, then you can replace your loop example with the new <a href="http://pandas.pydata.org/pandas-docs/version/0.19.0/whatsnew.html#whatsnew-0190-enhancements-asof-merge" rel="nofollow">asof join in pandas 0.19</a>:</p>
<pre><code># query
df_b5 = df_orig.query('segment == "B5"')
# sort ahead of time
df_b5.sort_values('score2', inplace=True)
threshold_b5.sort_values('score2', inplace=True)
# set the default indicator as 1
threshold_b5['indicator'] = 1
# join the tables
df = pd.merge_asof(df_b5, threshold_b5, on='score2', by='score1')
# fill missing indicators as 0
df.indicator = np.int64(df.indicator.fillna(0.0))
</code></pre>
<p>This is what I got:</p>
<pre><code> segment score1 score2 indicator
0 B5 0 320 0
1 B5 300 400 1
</code></pre>
<p>If you need the original order, then save the index in a new column of <code>df_orig</code> and then resort the final DataFrame by that.</p>
<p>Of course, what you'd really want to do is <code>concat</code> all of your thresholds with the <code>segment</code> column set for each one, then invoke <code>merge_asof</code> with <code>by=['segment', 'score1']</code>. Unfortunately the current function <a href="https://github.com/pydata/pandas/issues/13936" rel="nofollow">doesn't allow for multiple <code>by</code> parameters</a>.</p>
| 1 | 2016-10-12T18:44:45Z | [
"python",
"python-2.7",
"pandas"
] |
How can I implement something similar to `value_counts()` in a groupby? | 40,005,993 | <p>Suppose I had the following data</p>
<pre><code>Orchard Tree
1 Apple
2 Peach
1 Peach
3 Apple
</code></pre>
<p>How could I group by <code>orchard</code> and show how many times each tree occurs in the orchard? The result would look like</p>
<pre><code>Tree Apple Peach
Orchard
1 1 1
2 0 1
3 1 0
</code></pre>
| 2 | 2016-10-12T18:36:58Z | 40,006,056 | <p>Is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a> what you want?</p>
<pre><code>In [48]: df
Out[48]:
Orchard Tree
0 1 Apple
1 2 Peach
2 1 Peach
3 3 Apple
In [49]: df.pivot_table(index='Orchard', columns='Tree', aggfunc='size', fill_value=0)
Out[49]:
Tree Apple Peach
Orchard
1 1 1
2 0 1
3 1 0
</code></pre>
<p>or using <code>groupby()</code> and <code>unstack()</code> (that's how <code>pivot_table()</code> does it under the hood):</p>
<pre><code>In [57]: df.groupby(['Orchard','Tree']).size().unstack('Tree', fill_value=0)
Out[57]:
Tree Apple Peach
Orchard
1 1 1
2 0 1
3 1 0
</code></pre>
| 3 | 2016-10-12T18:40:04Z | [
"python",
"pandas",
"dataframe"
] |
How can I implement something similar to `value_counts()` in a groupby? | 40,005,993 | <p>Suppose I had the following data</p>
<pre><code>Orchard Tree
1 Apple
2 Peach
1 Peach
3 Apple
</code></pre>
<p>How could I group by <code>orchard</code> and show how many times each tree occurs in the orchard? The result would look like</p>
<pre><code>Tree Apple Peach
Orchard
1 1 1
2 0 1
3 1 0
</code></pre>
| 2 | 2016-10-12T18:36:58Z | 40,006,329 | <p>Let's not forget good ol' <code>value_counts</code><br>
Just have to make sure to reduce to <code>Tree</code> after the <code>groupby</code></p>
<pre><code>df.groupby('Orchard').Tree.value_counts().unstack(fill_value=0)
</code></pre>
<p><a href="https://i.stack.imgur.com/Gl9ZY.png" rel="nofollow"><img src="https://i.stack.imgur.com/Gl9ZY.png" alt="enter image description here"></a></p>
| 3 | 2016-10-12T18:56:52Z | [
"python",
"pandas",
"dataframe"
] |
How can my user upload an image to email to me [Django] | 40,006,013 | <p>I've got a simple website for a Screenprinting company built using Django 1.10 and Python 3.5.2, but I am having issues with my "Get a Quote" page.</p>
<p>The idea is a user can go to www.example.com/quote/ and they are presented with a form. Here they put in their Name, Email Address, a Brief Message, and most importantly they can upload an image. </p>
<p>When they click submit, this data gets sent to my email address as an email using the EmailMessage method. I have set up a simple email form plenty of times in the past so I know my settings.py file is fine.</p>
<p>Here is my forms.py:</p>
<pre><code>class QuoteForm(forms.Form):
name = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
subject = "Quote"
uploaded_image = forms.ImageField()
message = forms.CharField(widget=forms.Textarea)
</code></pre>
<p>Here is my views.py:</p>
<pre><code>def quote(request):
form = QuoteForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
message = "From: " + name + "\n" + "Return Email: " + from_email + "\n" + "Subject: " + subject + "\n" + "Message: " + message
uploaded_image = form.cleaned_data['uploaded_image']
msg = EmailMessage(subject, message, from_email, ['[email protected]'], reply_to=[from_email])
msg.attach_file(uploaded_image)
try:
msg.send()
except BadHeaderError:
return HttpResponse('Invalid header found')
return HttpResponseRedirect('thankyou')
return render(request, "quote.html", {'form': form})
</code></pre>
<p>When I test this on 127.0.0.1 I click submit and the form refreshes with the same info, except the image is no longer there.</p>
<p>Also, When I test it using the console.EmailBackend there are no errors. In fact, clicking submit doesn't seem to have any effect other than it reloads a few css files.</p>
<p>Any ideas?</p>
| 0 | 2016-10-12T18:38:02Z | 40,006,373 | <p>A file is not in the <code>request.POST</code> attribute, it is in <code>request.FILES</code>. Your <code>views.py</code> should look like this:</p>
<pre><code>def quote(request):
form = QuoteForm(request.POST, request.FILES)
if form.is_valid():
...
uploaded_image = request.FILES.getlist('uploaded_image')
...
</code></pre>
<p>Please note that this is a raw draft. I haven't tested it. Also note that you might have to sanitize the file for your own safety. For example: checking on the maximum filesize and contenttype.</p>
<p>More information about all of this: <a href="https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/</a></p>
| 0 | 2016-10-12T19:00:04Z | [
"python",
"django",
"email",
"upload",
"imagefield"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.