title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
tensorflow placeholder in function | 39,549,472 | <p>Now, I have a bit of code like below:</p>
<pre><code>import tensorflow as tf
x = tf.placeholder(tf.float32, [1, 3])
y = x * 2
with tf.Session() as sess:
result = sess.run(y, feed_dict={x: [2, 4, 6]})
print(result)
</code></pre>
<p>I want to feed values to a function.</p>
<p>Below is an obvious wrong.
Ho... | 0 | 2016-09-17T17:00:59Z | 39,549,778 | <p>One option is to run a session inside of function just as follows: </p>
<pre><code>import tensorflow as tf
def my_func(data):
x = tf.placeholder(tf.float32, [1, 3])
y = x * 2
return sess.run(y, feed_dict = {x: data})
with tf.Session() as sess:
result = my_func([[2, 4, 6]])
print(result)
</co... | 1 | 2016-09-17T17:30:01Z | [
"python",
"tensorflow",
"placeholder"
] |
Why is this implementation of the conditional logit gradient failing? | 39,549,482 | <p>I've written a very simple implementation of the likelihood/gradient for the conditional logit model (explained <a href="http://data.princeton.edu/wws509/notes/c6s3.html" rel="nofollow">here</a>) - the likelihood works fine, but the gradient isn't correct. My two questions are: is my derivation of the gradient corre... | 0 | 2016-09-17T17:02:17Z | 39,565,675 | <p>The derivation was incorrect. In the exponentiation I was only including the feature and coefficient for the partial derivative of the given coefficient. Rather, it should have been e to the dot product of all features and coefficients. </p>
| 0 | 2016-09-19T05:00:40Z | [
"python",
"scipy",
"statistics",
"mathematical-optimization"
] |
Trying to install mathplot.lib for python 2.7.11. But Cannot find a suitable process. Have tried various ways from Youtube Tutorials, but invain | 39,549,494 | <p>I have installed matplotlib-1.5.0.win-amd64-py2.7 from sourcefourge.net after downloading and installing numpy using commandprompt by using pip: pip install numpy. But when I write the following code it Gives me error. Help me out.
Code:</p>
<pre><code>from matplotlib.pylab import *
pylab.plot([1,2,3,4],[1,2,3,4])
... | 2 | 2016-09-17T17:03:16Z | 39,549,700 | <p>There is an easy and complete guide on the <a href="http://matplotlib.org/users/installing.html" rel="nofollow">Matplotlib Website</a>.
Try and follow this one.</p>
| 3 | 2016-09-17T17:21:47Z | [
"python",
"numpy",
"matplotlib"
] |
Trying to install mathplot.lib for python 2.7.11. But Cannot find a suitable process. Have tried various ways from Youtube Tutorials, but invain | 39,549,494 | <p>I have installed matplotlib-1.5.0.win-amd64-py2.7 from sourcefourge.net after downloading and installing numpy using commandprompt by using pip: pip install numpy. But when I write the following code it Gives me error. Help me out.
Code:</p>
<pre><code>from matplotlib.pylab import *
pylab.plot([1,2,3,4],[1,2,3,4])
... | 2 | 2016-09-17T17:03:16Z | 39,550,167 | <p>refer to this answer of mine
<a href="http://stackoverflow.com/a/38618044/5334188">http://stackoverflow.com/a/38618044/5334188</a></p>
<p>install numpy</p>
<p><code>pip install numpy</code></p>
<p>If you face installation issues for numpy, get the pre-built windows installers from <a href="http://www.lfd.uci.edu... | 1 | 2016-09-17T18:12:59Z | [
"python",
"numpy",
"matplotlib"
] |
Run python script from PHP in windows | 39,549,846 | <p>I want to run <code>python</code> script from <code>php</code>. I am on <code>python 3.5 , 64 bit</code> .I have read <a href="http://stackoverflow.com/questions/9283065/run-a-python-script-from-the-prompt-in-windows">StackQ1</a> and <a href="http://stackoverflow.com/questions/28622526/how-to-correctly-run-python-s... | 0 | 2016-09-17T17:37:55Z | 39,549,884 | <p>If you want to capture any output from the python script, you need to use shell_exec. Otherwise you're just running the script and the output isn't going anywhere. There are different commands for different purposes. Exec only runs a command, doesn't care about any potential return values.</p>
<p><a href="http:/... | 0 | 2016-09-17T17:41:46Z | [
"php",
"python"
] |
Plot multiple series with non-overlapping x-axis | 39,549,856 | <p>I have two dataframes, one contains a subset of samples of the other.</p>
<pre><code>df = pd.DataFrame(data= {'A' : [1,2,3,4,3,2,1]}
,index = [1,2,3,4,5,6,7])
df2 = pd.DataFrame(data = {'B' : [0.7, 1.4]}
,index = [2,6])
</code></pre>
<p>I'd like to plot these such that the complete da... | 0 | 2016-09-17T17:38:43Z | 39,550,600 | <p>You should do it the following way. </p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
df = pd.DataFrame(data= {'A' : [1,2,3,4,3,2,1]}
,index = [1,2,3,4,5,6,7])
df2 = pd.DataFrame(data = {'B' : [0.7, 1.4]}
... | 1 | 2016-09-17T18:57:08Z | [
"python",
"pandas",
"plot"
] |
Need to edit subset of rows from MySQL table using Pandas Dataframe | 39,549,887 | <p>I'm in the process of trying to alter a table in my database. However I am finding it difficult using the to_sql method provided by Pandas. My <code>price_data</code> Dataframe looks something like this:</p>
<h2>Initial Dataframe (as rows in the database):</h2>
<p><a href="http://i.stack.imgur.com/5sPFo.jpg" rel="... | 0 | 2016-09-17T17:41:55Z | 39,551,237 | <p>Consider a temp table with exact structure as final table but regularly replaced and will then be used to update existing final table. Try using <a href="http://docs.sqlalchemy.org/en/latest/core/connections.html" rel="nofollow">sqlalchemy engine</a> for both operations. </p>
<p>Specifically, for the latter SQL you... | 0 | 2016-09-17T20:10:14Z | [
"python",
"mysql",
"pandas",
"pandasql"
] |
Copying set of specific columns between Pandas dfs where specific values match | 39,549,889 | <p>I am sure this is going to be a 'doh' moment, but I am having a difficult time trying to copy a set of columns between dataframes where the value of a specific column in df1 is also found in df2.</p>
<p>A simplified version of df1 looks like this:
<a href="http://i.stack.imgur.com/oVzMm.png" rel="nofollow"><img src... | 0 | 2016-09-17T17:41:59Z | 39,550,218 | <p>If I'm not mistaken, I think you're looking for a join operation. </p>
<p>In particular, this statement in your description: </p>
<pre><code>df2.loc[df2['a_people_id']==df1['p_people_id'][0],np.array(cols)]
</code></pre>
<p>Means "look in <code>df2</code> for all rows where <code>p_people_id</code> matches the f... | 1 | 2016-09-17T18:18:08Z | [
"python",
"pandas",
"dataframe"
] |
Bit shifting of negative integer? | 39,549,971 | <p>I am trying to understand the bit shift operation <code>>></code> on a negative integer.</p>
<pre><code>-2 >> 1 # -1
-3 >> 1 # -2
-5 >> 1 # -3
-7 >> 1 # -4
</code></pre>
<p>Can someone explain how this is done? I know it is related to Two's complement, but I can't related that to the ... | 1 | 2016-09-17T17:50:33Z | 39,550,074 | <p>The full explanation is provided <a href="https://wiki.python.org/moin/BitwiseOperators" rel="nofollow">here</a></p>
<blockquote>
<p>Two's Complement binary for Negative Integers:</p>
<p>Negative numbers are written with a leading one instead of a leading
zero. So if you are using only 8 bits for your twos... | 2 | 2016-09-17T18:02:12Z | [
"python",
"bit-manipulation"
] |
Convert Pandas Dataframe from Row based to Columnar | 39,550,147 | <p>My Dataframe (df) looks like this:</p>
<pre><code>Date FieldA ValueA ValueB
09-02-2016 TypeA 3 5
09-02-2016 TypeB 6 7
</code></pre>
<p>I want the dataframe to look like below:</p>
<pre><code>Date TypeA_ValueA TypeA_ValueB TypeB_ValueA TypeB_ValueB
09-02-2016 3 5 ... | 0 | 2016-09-17T18:10:13Z | 39,550,196 | <pre><code>df1 = df.set_index(['Date', 'FieldA']).unstack()
df1.columns = df1.columns.map('_'.join)
df1.reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/Q583z.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q583z.png" alt="enter image description here"></a></p>
<hr>
<h3>Setup Reference</h3>
... | 2 | 2016-09-17T18:15:39Z | [
"python",
"sql",
"pandas",
"pyspark",
"spark-dataframe"
] |
Convert Pandas Dataframe from Row based to Columnar | 39,550,147 | <p>My Dataframe (df) looks like this:</p>
<pre><code>Date FieldA ValueA ValueB
09-02-2016 TypeA 3 5
09-02-2016 TypeB 6 7
</code></pre>
<p>I want the dataframe to look like below:</p>
<pre><code>Date TypeA_ValueA TypeA_ValueB TypeB_ValueA TypeB_ValueB
09-02-2016 3 5 ... | 0 | 2016-09-17T18:10:13Z | 39,551,015 | <pre><code>In [36]: df
Out[36]:
Date FieldA ValueA ValueB
0 2016-09-02 TypeA 3 5
1 2016-09-02 TypeB 6 7
2 2016-09-03 TypeA 4 8
3 2016-09-03 TypeB 3 9
In [37]: v_cols = df.columns.difference(['FieldA', 'Date'])
In [38]: def func(x):
...: d = {'_'.... | 0 | 2016-09-17T19:43:23Z | [
"python",
"sql",
"pandas",
"pyspark",
"spark-dataframe"
] |
Convert Pandas Dataframe from Row based to Columnar | 39,550,147 | <p>My Dataframe (df) looks like this:</p>
<pre><code>Date FieldA ValueA ValueB
09-02-2016 TypeA 3 5
09-02-2016 TypeB 6 7
</code></pre>
<p>I want the dataframe to look like below:</p>
<pre><code>Date TypeA_ValueA TypeA_ValueB TypeB_ValueA TypeB_ValueB
09-02-2016 3 5 ... | 0 | 2016-09-17T18:10:13Z | 39,552,056 | <p>Use <code>pd.pivot_table</code>.</p>
<pre><code>In [1]: pd.pivot_table(df, index='Date', columns='FieldA', values=['ValueA', 'ValueB'])
Out[1]:
ValueA ValueB
FieldA TypeA TypeB TypeA TypeB
Date
09-02-2016 3 6 5 7
</code></pre>
<p>As a ... | 0 | 2016-09-17T21:47:41Z | [
"python",
"sql",
"pandas",
"pyspark",
"spark-dataframe"
] |
Error in parsing strings to ints | 39,550,210 | <p>I have these two and it seems that bytes2integer is wrong, but I eliminated all the other issues. What is wrong? <a href="https://github.com/construct/construct/blob/master/construct/lib/py3compat.py" rel="nofollow">p3compat</a> provides some helper functions. On side note, <code>-int(data[1:], 2)</code> also doesnt... | 2 | 2016-09-17T18:17:28Z | 39,550,811 | <p>Bytes were reversed wrongly, and then it parsed the sign bit into number. Two bugs fixed.</p>
<pre><code>def onebit2integer(b):
if b in (b"0", b"\x00"):
return 0
if b in (b"1", b"\x01"):
return 1
raise ValueError(r"bit was not recognized as one of: 0 1 \x00 \x01")
def bits2integer(data... | 0 | 2016-09-17T19:20:47Z | [
"python",
"parsing"
] |
PANDAS Combine Rows And Preserve Column Order | 39,550,212 | <p>I have a "long" format pandas dataframe of the following general structure:</p>
<pre><code>id,date,color,size,density
1,201201,val1,val2,val3
1,201301,val1,val2,val3
1,201301,val1,val2,val3
2,201201,val1,val2,val3
2,201202,val1,val2,val3
</code></pre>
<p>The new "wide" format I am looking to create is this:</p>
<... | 1 | 2016-09-17T18:17:30Z | 39,550,921 | <p>You could use the concat method, but I tried making your long dataframe and found it unwieldy and fragile even in your toy example. I would suggest using the groupby method.</p>
<pre><code>grouped = df.sort('date', ascending=True).groupby('id')
</code></pre>
<p>If you need the concatenated version, try this:</p>
... | 1 | 2016-09-17T19:32:32Z | [
"python",
"pandas"
] |
How can I apply a function to a single row or column of a matrix using numpy and python | 39,550,238 | <p>I am learning numpy and using python and asking for help. I would like to sort a SINGLE row or column as a learning experience. Looking through their docs i see apply_along_axis but there isnt a parameter in their docs on how to indicate a splice/selector in choosing which rows or columns to apply it to.</p>
<p>I o... | 2 | 2016-09-17T18:20:37Z | 39,550,499 | <p>There's an inplace sort method.</p>
<pre><code>In [75]: A=np.array(A).reshape(3,-1)
In [76]: A
Out[76]:
array([[ 29, -11, 10],
[-160, 61, -55],
[ 55, -21, 19]])
In [77]: A[1,:].sort()
In [78]: A
Out[78]:
array([[ 29, -11, 10],
[-160, -55, 61],
[ 55, -21, 19]])
</c... | 4 | 2016-09-17T18:46:41Z | [
"python",
"numpy"
] |
How would a parent class call its own method within itself in Python | 39,550,288 | <p>I am trying to create the concrete class <code>Val15</code> class with the Mixins, <code>MyCollection</code>, <code>Val5</code>, <code>Val10</code>. <code>Val15</code> is trying to inherit <code>values</code> from <code>MyCollection</code>. When <code>Val15</code> is instantiated, I am trying to call both <code>Val1... | 0 | 2016-09-17T18:26:06Z | 39,551,113 | <p>This is the interesting part:</p>
<pre><code>class Val10(object):
def value(self):
return 10
class Val5(object):
def value(self):
return 5
</code></pre>
<p>To get the sum of parents' values, you have to call each of them:</p>
<pre><code>class Val15(Val10, Val5):
def value(self):
... | 1 | 2016-09-17T19:55:03Z | [
"python",
"inheritance",
"mixins"
] |
TypeError: both int and float | 39,550,293 | <pre><code>class Account(object):
def __init__(self,holder, number, balance, credit_line = 1500):
self.holder = holder
self.number = number
self.balance = balance
self.credit_line = credit_line
def deposit(self, amount):
self.balance = amount
def withdraw(self, amoun... | -2 | 2016-09-17T18:26:41Z | 39,550,328 | <p>You are overriding method <code>balance</code> in your <code>__init__</code> method. You could either change the field name to <code>_balance</code> or just remove <code>balance</code> method and use <code>Guido.balance</code>.</p>
<p>Also note, that you should name your variables starting with lowercase character ... | 1 | 2016-09-17T18:31:00Z | [
"python",
"python-2.7"
] |
TypeError: both int and float | 39,550,293 | <pre><code>class Account(object):
def __init__(self,holder, number, balance, credit_line = 1500):
self.holder = holder
self.number = number
self.balance = balance
self.credit_line = credit_line
def deposit(self, amount):
self.balance = amount
def withdraw(self, amoun... | -2 | 2016-09-17T18:26:41Z | 39,555,750 | <pre><code>class Account(object):
def __init__(self,holder, number, balance, credit_line = 1500):
self.holder = holder
self.number = number
self.balance = balance
self.credit_line = credit_line
def deposit(self, amount):
self.balance = amount
def withdraw(self, amoun... | 0 | 2016-09-18T08:45:34Z | [
"python",
"python-2.7"
] |
urllib read() changing attributes | 39,550,348 | <p>I have a basic script, which is requesting websites to get the html source code.
while crawling several websites I figured out that different attributes in the source code are being represented wrong.</p>
<p>Example:</p>
<pre><code>from urllib import request
opener = request.build_opener()
with opener.open("https... | 0 | 2016-09-17T18:32:45Z | 39,550,415 | <p><code>responce.read()</code> will return a <code>bytes</code> object, when printed its escape sequences don't get interpreted, see:</p>
<pre><code>print(b'hello\nworld') # prints b'hello\nworld'
</code></pre>
<p>You'll need to <code>decode</code> it to <code>str</code> which, when printed, evaluates the escapes co... | 0 | 2016-09-17T18:38:25Z | [
"python",
"python-3.x",
"urllib"
] |
Is there a way to avoid a new line while using `end=` | 39,550,446 | <p>I've just started using python and I'm creating a simple program that will ask whoever the user is a question and then from the text file I will extract a specific line and print that line and along with the line - at the end I will add their answer. here's the code.</p>
<pre><code> question = input("do you want... | -1 | 2016-09-17T18:41:45Z | 39,550,524 | <p>Have you tried simply omitting the "end="?
I don't think it's necessary you put it there.</p>
| 0 | 2016-09-17T18:48:51Z | [
"python",
"python-3.5"
] |
Is there a way to avoid a new line while using `end=` | 39,550,446 | <p>I've just started using python and I'm creating a simple program that will ask whoever the user is a question and then from the text file I will extract a specific line and print that line and along with the line - at the end I will add their answer. here's the code.</p>
<pre><code> question = input("do you want... | -1 | 2016-09-17T18:41:45Z | 39,550,589 | <p>The problem is that the lines returned by <code>readlines()</code> contain the ending newline:</p>
<pre><code>$ echo 'a
> b
> c
> ' > test_file.txt
$ python3
Python 3.5.2 (default, Jul 5 2016, 12:43:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information... | 0 | 2016-09-17T18:56:19Z | [
"python",
"python-3.5"
] |
Selenium returns wrong element when search by class/xpath/css | 39,550,448 | <p>I'm trying to make simple python script that finds non-faded elements on site and click them.</p>
<p>My code:</p>
<pre><code>from selenium import webdriver
ffprofile = webdriver.FirefoxProfile(r"C:/Users/Dan/AppData/Roaming/Mozilla/Firefox/Profiles/q3fhuchn.QAtest")
driver = webdriver.Firefox(ffprofile)
driver.ge... | 0 | 2016-09-17T18:41:52Z | 39,550,550 | <p>You can try to click on required element using <code>XPath</code>:</p>
<pre><code>driver.find_element_by_xpath('//a[@class="giveaway__heading__name"]').click()
</code></pre>
| 0 | 2016-09-17T18:51:47Z | [
"python",
"html",
"selenium"
] |
Selenium returns wrong element when search by class/xpath/css | 39,550,448 | <p>I'm trying to make simple python script that finds non-faded elements on site and click them.</p>
<p>My code:</p>
<pre><code>from selenium import webdriver
ffprofile = webdriver.FirefoxProfile(r"C:/Users/Dan/AppData/Roaming/Mozilla/Firefox/Profiles/q3fhuchn.QAtest")
driver = webdriver.Firefox(ffprofile)
driver.ge... | 0 | 2016-09-17T18:41:52Z | 39,550,576 | <p>What you're seeing is correct. The element</p>
<pre><code><div class="giveaway__row-inner-wrap is-faded">
</code></pre>
<p>has in fact two classes: <code>giveaway__row-inner-wrap</code> and <code>is-faded</code> therefore it's correct that Selenium returns it. I suspect that you have two elements in that lis... | 0 | 2016-09-17T18:55:02Z | [
"python",
"html",
"selenium"
] |
Selenium returns wrong element when search by class/xpath/css | 39,550,448 | <p>I'm trying to make simple python script that finds non-faded elements on site and click them.</p>
<p>My code:</p>
<pre><code>from selenium import webdriver
ffprofile = webdriver.FirefoxProfile(r"C:/Users/Dan/AppData/Roaming/Mozilla/Firefox/Profiles/q3fhuchn.QAtest")
driver = webdriver.Firefox(ffprofile)
driver.ge... | 0 | 2016-09-17T18:41:52Z | 39,551,520 | <p>I don't know why, but this string works perfectly for my scenario, so I use it to create a list of non-faded elements:</p>
<pre><code>elements = driver.find_elements_by_xpath("//div[@class='giveaway__row-inner-wrap']//a[@class='giveaway__heading__name']")
elements[x].click()
</code></pre>
| 0 | 2016-09-17T20:40:54Z | [
"python",
"html",
"selenium"
] |
Python version of Java regular expression? | 39,550,452 | <p>I am a Java developer, and new to Python. I would like to define a regex accepting all the alphabetic characters except for some of them. I want to exclude just the vowels and the character 'y', be it in upper- or lowercase. </p>
<p>The regex in Java for it would be as follows:</p>
<pre><code> "[a-zA-Z&&[^... | 0 | 2016-09-17T18:42:07Z | 39,550,636 | <p>Like <code>(?i)[b-df-hj-np-tv-xz]</code> or <code>(?i)\w(?<![_aeiouy\d])</code>. Test <a href="https://regex101.com/#python" rel="nofollow">here</a>.</p>
| 0 | 2016-09-17T19:01:12Z | [
"python",
"regex"
] |
Python version of Java regular expression? | 39,550,452 | <p>I am a Java developer, and new to Python. I would like to define a regex accepting all the alphabetic characters except for some of them. I want to exclude just the vowels and the character 'y', be it in upper- or lowercase. </p>
<p>The regex in Java for it would be as follows:</p>
<pre><code> "[a-zA-Z&&[^... | 0 | 2016-09-17T18:42:07Z | 39,550,784 | <blockquote>
<p><strong>(?=...)</strong> Positive lookahead assertion. This succeeds if the contained
regular expression, represented here by ..., successfully matches at
the current location, and fails otherwise. But, once the contained
expression has been tried, the matching engine doesnât advance at all;
... | 0 | 2016-09-17T19:18:11Z | [
"python",
"regex"
] |
Python version of Java regular expression? | 39,550,452 | <p>I am a Java developer, and new to Python. I would like to define a regex accepting all the alphabetic characters except for some of them. I want to exclude just the vowels and the character 'y', be it in upper- or lowercase. </p>
<p>The regex in Java for it would be as follows:</p>
<pre><code> "[a-zA-Z&&[^... | 0 | 2016-09-17T18:42:07Z | 39,550,987 | <p>I don't think the current python regular expression module has exactly what you're looking for. The eventual replacement <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><code>regex</code></a> does have what you need, and you can install it should you wish.</p>
<p>Other than that, a negation might be the... | 2 | 2016-09-17T19:40:58Z | [
"python",
"regex"
] |
Dealing with QVariants in a settings-module with python 2.7.6 / PyQt4 | 39,550,456 | <p>I have previously read several topics on this site and other platforms, but my code does still not work as desired. I seem not to be able to put all the puzzle pieces together and need someone to look over my code. </p>
<p>I'm writing a plugin for the program QtiPlot. Im using Python 2.7.6 and PyQt4. I created the... | 2 | 2016-09-17T18:42:36Z | 39,551,768 | <p>The best solution is to use <code>sip.setapi</code>. But to get it to work properly, it <strong>must</strong> be invoked before the <em>first</em> import of PyQt in your application. So it needs to go in the main script, not the config module:</p>
<pre><code>#========================================================... | 1 | 2016-09-17T21:07:33Z | [
"python",
"pyqt4"
] |
Dealing with QVariants in a settings-module with python 2.7.6 / PyQt4 | 39,550,456 | <p>I have previously read several topics on this site and other platforms, but my code does still not work as desired. I seem not to be able to put all the puzzle pieces together and need someone to look over my code. </p>
<p>I'm writing a plugin for the program QtiPlot. Im using Python 2.7.6 and PyQt4. I created the... | 2 | 2016-09-17T18:42:36Z | 39,574,513 | <p>As in Python 2 and with SIP old API, <code>toString()</code> will return a <code>QString</code>. You have to force it to a Python string with <code>str</code> for both the <code>get</code> and the <code>set</code> methods. Concerning the <code>QCheckBox</code>, I used the <code>toInt</code> method instead of the <co... | 1 | 2016-09-19T13:32:24Z | [
"python",
"pyqt4"
] |
Scrapy - send form data with multiple options | 39,550,477 | <p>I'm using scrapy to parse a website that has the following form:</p>
<pre><code><form id="form1"...>
<select name="codes" multiple="multiple"...>
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option... | 0 | 2016-09-17T18:45:18Z | 39,557,714 | <p>to send form with multiple options, you should try passing formdata in following format</p>
<pre><code>formdata = {}
formdata['codes[]'] = ["0","1","2","3"]
yield scrapy.FormRequest.from_response(
response=response,
formid='UserLoginForm',
formdata=formdata,
callback... | 0 | 2016-09-18T12:39:06Z | [
"python",
"forms",
"scrapy"
] |
How to use 'saveas' function to send a pdf file to client side? Openerp | Odoo | 39,550,479 | <p>I wrote a module to consume a .wsdl webservice, using python suds library, this service returns a PDF file in base64, I'm able to save this file in a binary fild, so I want a button to download this file on client side, How can I do that? I was reading that I can use 'saveas' method available on '/web/controllers/ma... | 0 | 2016-09-17T18:45:27Z | 39,552,496 | <p>If you are adding a button in the backend that you wish to download your pdf. You won't have access to template structures. You can get around this using a technique like this example.</p>
<p>You need a link, which you can wrap around a button (which does nothing) and you can use javascript if you need to manipulat... | 0 | 2016-09-17T22:54:36Z | [
"python",
"pdf",
"openerp",
"odoo-8",
"openerp-7"
] |
parsing and inserting raw text data into mysql database using python or shell | 39,550,534 | <p>I have a text file which has data in the following format:
these are 2 lines from the text file which is ncdc raw weather data:
The highlighted part is the air temperature which will be (Degree Celsius *100) Thats just one of the columns that i need to insert into database.
The temperature position always remains th... | 0 | 2016-09-17T18:50:31Z | 39,551,665 | <p>In python you could do something like:</p>
<pre><code>f = open("data.txt", "r") #assuming this is your file
data = f.read()
f.close()
for line in data.split("\n"): #split all data in lines
print line[88:93]
</code></pre>
<p>Last step would be inserting it in the DB instead of just printing it, eg:</p>
<pre>... | 1 | 2016-09-17T20:57:19Z | [
"python",
"mysql",
"bash"
] |
Django: View didn't return an HttpResponse object. It returned None instead | 39,550,577 | <p>Basically I would like a user to input a number in a field and the fibonacci result to be printed but once the input is inserted into the input field I recieve that it returned None instead of an object</p>
<p>I have this code over here for my html form:</p>
<pre><code>{% block content %}
<form method="POST" ... | 0 | 2016-09-17T18:55:08Z | 39,550,753 | <p>In your <em>views.py</em> file, is there any <em>fibb</em> function that return a HTTPResponse? In the error trace, Django cannot find that response in <em>fibb</em> function in <em>fibb.views</em>. You can check the url directed to <em>fibb</em> function. Maybe it should be directed to <em>fibocal</em> function as ... | 0 | 2016-09-17T19:14:26Z | [
"python",
"django"
] |
Hexadecimal file is loading with 2 back slashes before each byte instead of one | 39,550,744 | <p>I have a hex file in this format: <code>\xda\xd8\xb8\x7d</code></p>
<p>When I load the file with Python, it loads with two back slashes instead of one.</p>
<pre><code>with open('shellcode.txt', 'r') as file:
shellcode = file.read().replace('\n', '')
</code></pre>
<p>Like this: <code>\\xda\\xd8\\xb8\\x7d</code... | 0 | 2016-09-17T19:13:32Z | 39,550,787 | <p>Here is an example </p>
<pre><code>>>> h = "\\x123"
>>> h
'\\x123'
>>> print h
\x123
>>>
</code></pre>
<p>The two backslashes are needed because \ is an escape character, and so it needs to be escaped. When you print h, it shows what you want</p>
| 1 | 2016-09-17T19:18:50Z | [
"python",
"escaping",
"hex"
] |
Hexadecimal file is loading with 2 back slashes before each byte instead of one | 39,550,744 | <p>I have a hex file in this format: <code>\xda\xd8\xb8\x7d</code></p>
<p>When I load the file with Python, it loads with two back slashes instead of one.</p>
<pre><code>with open('shellcode.txt', 'r') as file:
shellcode = file.read().replace('\n', '')
</code></pre>
<p>Like this: <code>\\xda\\xd8\\xb8\\x7d</code... | 0 | 2016-09-17T19:13:32Z | 39,550,982 | <p>Backshlash (<code>\</code>) is an escape character. It is used for changing the meaning of the character(s) following it.</p>
<p>For example, if you want to create a string which contains a quote, you have to escape it:</p>
<pre><code>s = "abc\"def"
print s # prints: abc"def
</code></pre>
<p>If there was no back... | 0 | 2016-09-17T19:40:13Z | [
"python",
"escaping",
"hex"
] |
Hexadecimal file is loading with 2 back slashes before each byte instead of one | 39,550,744 | <p>I have a hex file in this format: <code>\xda\xd8\xb8\x7d</code></p>
<p>When I load the file with Python, it loads with two back slashes instead of one.</p>
<pre><code>with open('shellcode.txt', 'r') as file:
shellcode = file.read().replace('\n', '')
</code></pre>
<p>Like this: <code>\\xda\\xd8\\xb8\\x7d</code... | 0 | 2016-09-17T19:13:32Z | 39,551,396 | <p>You can make a <code>bytes</code> object with a <code>utf-8</code> encoding, and then decode as <code>unicode-escape</code>.</p>
<pre><code>>>> x = "\\x61\\x62\\x63"
>>> y = bytes(x, "utf-8").decode("unicode-escape")
>>> print(x)
\x61\x62\x63
>>> print(y)
abc
</code></pre>
| 0 | 2016-09-17T20:27:21Z | [
"python",
"escaping",
"hex"
] |
NumPy MemoryError when using array constructors | 39,550,796 | <p>I'm creating a couple of arrays using numpy and list constructors, and I can't figure out why this is failing. My code is:</p>
<pre><code>import numpy as np
A = np.ndarray( [i for i in range(10)] ) # works fine
B = np.ndarray( [i**2 for i in range(10)] ) # fails, with MemoryError
</code></pre>
<p>I've also tried j... | 0 | 2016-09-17T19:19:28Z | 39,550,955 | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html</a> is a low-level method that we normally don't use. Its first argument is the <code>shape</code>.</p>
<pre><code>In [98]: np.ndarray([x for x in r... | 2 | 2016-09-17T19:36:18Z | [
"python",
"arrays",
"list",
"numpy",
"constructor"
] |
How to extract data from complex Json using python | 39,550,808 | <pre><code>{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "A... | 0 | 2016-09-17T19:20:29Z | 39,550,839 | <p>You can follow the documentation for json library from the links: <a href="https://docs.python.org/2/library/json.html" rel="nofollow">python2</a> or <a href="https://docs.python.org/3/library/json.html" rel="nofollow">python3</a>
If you have any spesific questions, you can define traces or code parts to find correc... | 0 | 2016-09-17T19:23:43Z | [
"python",
"json"
] |
How to extract data from complex Json using python | 39,550,808 | <pre><code>{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "A... | 0 | 2016-09-17T19:20:29Z | 39,550,853 | <p>Actually, simple JSONs and complex JSONs are not that different. You can say that a <em>complex JSON</em> has many <em>simpler JSONs</em> inside, so if you know how to get data from simple ones, you end up knowing how to get data from complexes </p>
<p>Anyway, think of JSON objects as <code>dictionaries</code> and ... | 3 | 2016-09-17T19:24:44Z | [
"python",
"json"
] |
How to program 'Sunfounder sensor kit V1.0' for Raspberry Pi | 39,550,838 | <p>I am an beginner programmer and I purchased the above kit to learn how to program in Python. (Unfortunately, the included instructions were written in C and I'm very new to Python)</p>
<p>All I want to do is plug the sensor into my breadboard and run a script to see the results.</p>
<p>Sensors include: Humiture se... | -1 | 2016-09-17T19:23:39Z | 39,650,182 | <p>The SunFounder kit includes a lot of different sensors, so you'll have to look up how to use each one individually. You should probably start by looking at the tutorials available at the SunFounder Tutorial <a href="https://www.sunfounder.com/learn" rel="nofollow" title="SunFounder tutorial">https://www.sunfounder.... | 0 | 2016-09-22T23:08:28Z | [
"python",
"sensor",
"raspberry-pi3"
] |
Splitting stacked dataframe in pandas | 39,550,927 | <p>I have a dataframe like</p>
<pre><code> age sex values
time
2015 10 F 589628.0
2015 10 M 458390.0
2015 11 F 108018.0
2015 11 M 764350.0
....
2000 60 M 34676.0
2000 60 F 45488.0
</code></pre>
<p>I would like to creat... | 1 | 2016-09-17T19:33:04Z | 39,551,188 | <p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow">reset_index</a>:</p>
<pre><code>In [17]: df
Out[17]:
age sex val... | 1 | 2016-09-17T20:04:05Z | [
"python",
"pandas",
"dataframe"
] |
Splitting stacked dataframe in pandas | 39,550,927 | <p>I have a dataframe like</p>
<pre><code> age sex values
time
2015 10 F 589628.0
2015 10 M 458390.0
2015 11 F 108018.0
2015 11 M 764350.0
....
2000 60 M 34676.0
2000 60 F 45488.0
</code></pre>
<p>I would like to creat... | 1 | 2016-09-17T19:33:04Z | 39,551,368 | <p>I can't confirm this but it should be</p>
<pre><code>df.set_index(['age', 'sex'], append=True)['values'].unstack().reset_index('age')
</code></pre>
| 2 | 2016-09-17T20:23:48Z | [
"python",
"pandas",
"dataframe"
] |
Django queryset order_by dates near today | 39,550,997 | <p>I want to show the records near to today's date at top and then all records in the past at bottom:</p>
<p>Today<br>
Tomorrow<br>
Tomorrow + 1<br>
.<br>
.<br>
.<br>
Yesterday<br>
Yesterday -1 </p>
| 0 | 2016-09-17T19:41:58Z | 39,551,190 | <p>Yes you can, what you want is the descending behavior of the <strong><a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.order_by" rel="nofollow">order_by</a></strong>.</p>
<p><strong>Oldest items first.</strong></p>
<pre><code>Model.objects.order_by('creation_time... | 0 | 2016-09-17T20:04:33Z | [
"python",
"django",
"sorting",
"sql-order-by"
] |
How to use flask flash messages in 2 different app.route | 39,551,157 | <p>I'm fresh developer in flask framework, and I got stuck on these methods for showing error message, and I don't understand how to use flask flash message. I was thinking about it for 3 or 4 days and I got some idea how to handle this problem. so my plan is simple, I make some authentication login in my viewer. If it... | -1 | 2016-09-17T19:59:43Z | 39,551,224 | <p>In Python, you have to call:</p>
<pre><code>flask.flash('This is the message')
</code></pre>
<p>Then, in the template use <code>get_flashed_messages</code> to get the flashed messages and display them, e.g.:</p>
<pre><code>{% with messages = get_flashed_messages(with_categories=True) %}
{% for category, messa... | 1 | 2016-09-17T20:08:14Z | [
"python",
"python-3.x",
"flask",
"flash-message"
] |
Interpret serialdata in python | 39,551,238 | <p>I'm currently struggling with an issue. I have an arduino sending serialdata to my raspberry pi. The raspberry pi reads the data and stores it in a database. What i'm struggling with is to get data in the correct order. If i start the script at the correct time, the values get read properly. If i don't they get mixe... | 0 | 2016-09-17T20:10:22Z | 39,552,807 | <p>Your method isn't particularly efficient; you could send everything as a struct from the Arduino (header + data) and parse it on the RPi side with the <code>struct</code> module though your way does have the advantage of simplicity. But, if 999 is the highest value you expect in your readings, then it makes more sen... | 0 | 2016-09-17T23:51:48Z | [
"python",
"arduino",
"serial-port",
"raspberry-pi3"
] |
Creating output variables and copying attributes in python xarray netcdf4 | 39,551,245 | <p>I can create variables and copy over attributes in netcdf4 like this:</p>
<pre><code>out_var = hndl_out_nc.createVariable(name_var, var.datatype, var.dimensions)
out_var.setncatts({k: var.getncattr(k) for k in var.ncattrs()})
</code></pre>
<p>What is the corresponding version for xarray?</p>
| 0 | 2016-09-17T20:10:53Z | 39,562,266 | <p>If <code>var</code> is an <code>xarray.DataArray</code>, you can put it (along with attributes) into a new <code>xarray.Dataset</code> simply by writing <code>ds[name_] = var</code>. Or you can construct a new DataArray piece by piece with <code>xarray.DataArray(var.data, var.coords, var.dims, var.attrs)</code>.</p>... | 1 | 2016-09-18T20:18:18Z | [
"python",
"python-xarray",
"netcdf4"
] |
sklearn SVM performing awfully poor | 39,551,264 | <p>I have 9164 points, where 4303 are labeled as the class I want to predict and 4861 are labeled as not that class. They are no duplicate points.</p>
<p>Following <a href="http://stackoverflow.com/questions/39500894/how-to-split-into-train-test-and-evaluation-sets-in-sklearn">How to split into train, test and evaluat... | 0 | 2016-09-17T20:13:00Z | 39,551,445 | <p>Most estimators in scikit-learn such as SVC are initiated with a number of input parameters, also known as hyper parameters. Depending on your data, you will have to figure out what to pass as inputs to the estimator during initialization. If you look at the SVC documentation in scikit-learn, you see that it can be ... | 3 | 2016-09-17T20:32:10Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"classification"
] |
sklearn SVM performing awfully poor | 39,551,264 | <p>I have 9164 points, where 4303 are labeled as the class I want to predict and 4861 are labeled as not that class. They are no duplicate points.</p>
<p>Following <a href="http://stackoverflow.com/questions/39500894/how-to-split-into-train-test-and-evaluation-sets-in-sklearn">How to split into train, test and evaluat... | 0 | 2016-09-17T20:13:00Z | 39,584,093 | <p>After the comments of sascha and the answer of shahins, I did this eventually:</p>
<pre><code>df = pd.DataFrame(dataset)
train, validate, test = np.split(df.sample(frac=1), [int(.6*len(df)), int(.8*len(df))])
train_labels = construct_labels(train)
train_data = construct_data(train)
test_labels = construct_labels(... | 0 | 2016-09-20T00:47:08Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"classification"
] |
Python - download video from indirect url | 39,551,320 | <p>I have a link like this</p>
<pre><code>https://r9---sn-4g57knle.googlevideo.com/videoplayback?id=10bc30daeba89d81&itag=22&source=picasa&begin=0&requiressl=yes&mm=30&mn=sn-4g57knle&ms=nxu&mv=m&nh=IgpwcjA0LmZyYTE2KgkxMjcuMC4wLjE&pl=19&sc=yes&mime=video/mp4&lmt=14395... | -5 | 2016-09-17T20:19:11Z | 39,551,444 | <p>You can use <a href="http://pycurl.io/docs/latest/quickstart.html" rel="nofollow">pycurl</a></p>
<pre><code>#!/bin/usr/env python
import sys
import pycurl
c = pycurl.Curl()
c.setopt(c.FOLLOWLOCATION, 1)
c.setopt(c.URL, sys.argv[1])
with open(sys.argv[2], 'w') as f:
c.setopt(c.WRITEFUNCTION, f.write)
c.perf... | 0 | 2016-09-17T20:32:01Z | [
"python",
"url",
"video",
"web-scraping"
] |
Why isn't this regex matching a string with percentage symbol? | 39,551,333 | <p>I have a file which has the following input : </p>
<pre><code>xa%1bc
ba%1bc
.
.
</code></pre>
<p>and so on. I want to use <code>match</code> and <code>regex</code> to identify the lines which have <code>a%1b</code>in them.
I am using </p>
<pre><code> import re
p1 = re.compile(r'\ba%1b\b', flags=re.I)
if re.mat... | -1 | 2016-09-17T20:20:50Z | 39,551,391 | <p>You can try</p>
<pre><code>if 'a%1b' in linefromfile:
</code></pre>
<p><strong>OR</strong></p>
<p>if you need regex</p>
<pre><code>if re.match('a%1b', linefromfile):
</code></pre>
| 0 | 2016-09-17T20:27:00Z | [
"python",
"regex",
"string",
"match",
"word-boundary"
] |
Why isn't this regex matching a string with percentage symbol? | 39,551,333 | <p>I have a file which has the following input : </p>
<pre><code>xa%1bc
ba%1bc
.
.
</code></pre>
<p>and so on. I want to use <code>match</code> and <code>regex</code> to identify the lines which have <code>a%1b</code>in them.
I am using </p>
<pre><code> import re
p1 = re.compile(r'\ba%1b\b', flags=re.I)
if re.mat... | -1 | 2016-09-17T20:20:50Z | 39,551,422 | <p><code>match</code> only search the pattern at the beginning of the string, if you want to find out if a string contains a pattern, use <code>search</code> instead. Besides you don't need the word boundary, <code>\b</code>:</p>
<blockquote>
<p>re.search(pattern, string, flags=0) </p>
<p>Scan through string lo... | 1 | 2016-09-17T20:30:15Z | [
"python",
"regex",
"string",
"match",
"word-boundary"
] |
Receiving intermittent error when querying BigQuery database from Django App hosted on Apache2 Server | 39,551,379 | <p>Not sure if I'm allowed, but for the sake of those who wants to see my issue first hand, I am adding url of my development environment (www.blesque.tv). Issue is easily reproducible by reloading that page multiple times.</p>
<p>I switched the home page of my site to query data from my BigQuery database. When I am r... | 0 | 2016-09-17T20:24:43Z | 39,559,348 | <p>Have you considered using the <a href="https://googlecloudplatform.github.io/google-cloud-python/" rel="nofollow">Python API client</a> to query BQ?</p>
<p>There's a code sample <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigquery/cloud-client/sync_query.py" rel="nofollow">here</... | 0 | 2016-09-18T15:27:12Z | [
"python",
"django",
"apache",
"google-bigquery"
] |
Receiving intermittent error when querying BigQuery database from Django App hosted on Apache2 Server | 39,551,379 | <p>Not sure if I'm allowed, but for the sake of those who wants to see my issue first hand, I am adding url of my development environment (www.blesque.tv). Issue is easily reproducible by reloading that page multiple times.</p>
<p>I switched the home page of my site to query data from my BigQuery database. When I am r... | 0 | 2016-09-17T20:24:43Z | 39,604,562 | <p>After trying many different methods to make a workaround for this issue, I ended up developing a hack that works for now I guess. But I really think there is a bug in Google API's Authentication. I mean if you want to test it out, visit www.blesque.tv. You can see that now it works good. Slower than if I was hitting... | 0 | 2016-09-20T22:13:52Z | [
"python",
"django",
"apache",
"google-bigquery"
] |
How to separately use the encoder of an Autoencoder in keras? | 39,551,478 | <p>I have trained the following autoencoder model:</p>
<pre><code>input_img = Input(shape=(1, 32, 32))
x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = MaxPooling2D((2,... | 1 | 2016-09-17T20:34:56Z | 39,552,164 | <p>You can just create a model after training that only uses the encoder:</p>
<pre><code>autoencoder = Model(input_img, encoded)
</code></pre>
<p>If you want to add further layers after the encoded portion, you can do that as well:</p>
<pre><code>classifier = Dense(nb_classes, activation='softmax')(encoded)
model = ... | 1 | 2016-09-17T22:07:57Z | [
"python",
"neural-network",
"deep-learning",
"keras",
"autoencoder"
] |
Python POST request error "image format unsupported" using Microsoft Face API | 39,551,502 | <p>I'm trying to send a binary image file to test the Microsoft Face API. Using POSTMAN works perfectly and I get back a <code>faceId</code> as expected. However, I try to transition that to Python code and it's currently giving me this error: </p>
<pre><code>{"error": {"code": "InvalidImage", "message": "Decoding err... | 0 | 2016-09-17T20:38:16Z | 39,552,568 | <p>So the API endpoint takes a byte array but also requires the input body param as <code>data</code>, not <code>files</code>. Anyway, this code below works for me. </p>
<pre><code>url = "https://api.projectoxford.ai/face/v1.0/detect"
headers = {
'ocp-apim-subscription-key': "<key>",
'Content-Type': "applic... | 3 | 2016-09-17T23:07:21Z | [
"python",
"azure",
"python-requests",
"azure-api-apps",
"microsoft-cognitive"
] |
Why is the network not learning as effective (Tensorflow - LSTMs for text generation)? | 39,551,564 | <p>So my query is this: when I initially ran a 2 LSTM network (each 512 units) on the Shakespeare corpus, I got a pretty decent output after 2 epochs of training (where each epoch = one cycle through the dataset).
Here it is: </p>
<p><em>best ward of mine</em>
<em>him that you a man of make the pein to the noble from... | 1 | 2016-09-17T20:45:50Z | 39,577,340 | <p>I don't have an answer for this model, but have you tried starting with an existing example for a Shakespeare-generating LSTM, like this one?</p>
<p><a href="https://github.com/sherjilozair/char-rnn-tensorflow" rel="nofollow">https://github.com/sherjilozair/char-rnn-tensorflow</a></p>
<p>It should be a bit quicker... | 1 | 2016-09-19T15:59:01Z | [
"python",
"tensorflow",
"deep-learning",
"lstm"
] |
Create a set from a series in pandas | 39,551,566 | <p>I have a dataframe extracted from Kaggle's San Fransico Salaries: <a href="https://www.kaggle.com/kaggle/sf-salaries" rel="nofollow">https://www.kaggle.com/kaggle/sf-salaries</a>
and I wish to create a set of the values of a column, for instance 'Status'.</p>
<p>This is what I have tried but it brings a list of all... | 0 | 2016-09-17T20:46:07Z | 39,551,952 | <p>If you only need to get list of unique values, you can just use <code>unique</code> method.
If you want to have Python's set, then do <code>set(some_series)</code></p>
<pre><code>In [1]: s = pd.Series([1, 2, 3, 1, 1, 4])
In [2]: s.unique()
Out[2]: array([1, 2, 3, 4])
In [3]: set(s)
Out[3]: {1, 2, 3, 4}
</code></p... | 1 | 2016-09-17T21:33:14Z | [
"python",
"pandas",
"dataframe",
"series"
] |
Failing to update pygame surfaces | 39,551,648 | <p>I'm making a pygame game. I have 3 surfaces: <code>gameDisplay</code> (where the character and background is directly rendered to), <code>guiSurf</code> and <code>invSurf</code>
I have a clock made in core pyhon which displays the game time with the pygame font. I blit the clock to <code>guiSurf</code> and then in m... | 1 | 2016-09-17T20:54:27Z | 39,551,817 | <p>Make sure you 'clear' the area of where the time is being printed by blitting another image over the spot where the text is. When you draw your surfaces to the screen it simply becomes one 'surface' that is always drawn until overwritten by something else. You need to clear this surface before you blit something els... | 0 | 2016-09-17T21:14:24Z | [
"python",
"python-3.x",
"pygame",
"python-3.5",
"pygame-surface"
] |
Failing to update pygame surfaces | 39,551,648 | <p>I'm making a pygame game. I have 3 surfaces: <code>gameDisplay</code> (where the character and background is directly rendered to), <code>guiSurf</code> and <code>invSurf</code>
I have a clock made in core pyhon which displays the game time with the pygame font. I blit the clock to <code>guiSurf</code> and then in m... | 1 | 2016-09-17T20:54:27Z | 39,551,840 | <p>Visibly, the clock is blitted twice on the guiSurf. And I guess it keeps stacking the previous image of time (7:00, then 7:01, then 7.02 and so on). You need to clear the surface holding the clock before drawing time into it : <code>clock_surf.fill(clearcolor, clock_surf.get_rect())</code>.</p>
| 0 | 2016-09-17T21:18:04Z | [
"python",
"python-3.x",
"pygame",
"python-3.5",
"pygame-surface"
] |
Incomplete reads from file written by Popen()-based subprocess | 39,551,660 | <p>i'm trying to read the output from one function into another one.</p>
<p>if i break things down into two steps, call the first function(journal.py) from the command line, and then call the second(ip_list.py) i get the results that i'm looking for.</p>
<p>if i try to import the first and run it in the second the re... | 1 | 2016-09-17T20:56:32Z | 39,552,417 | <p>You should wait for <code>Popen()</code> to finish.
Assign its return value to a variable and call <code>wait()</code> on it:</p>
<pre><code>p = Popen('journalctl ...')
p.wait()
</code></pre>
<p>When you run the journal script separately, the parent process will only return when all of its children have terminated... | 1 | 2016-09-17T22:44:26Z | [
"python",
"file-io",
"popen"
] |
Docker : How to export/save classifying results outside a Docker (tensorflow) box? | 39,551,771 | <p>I just followed this tutorial to easily train an image classifier with tensorflow :</p>
<p><a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/" rel="nofollow">https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/</a></p>
<p>I now have a Docker box on my Ubuntu laptop, I m... | 1 | 2016-09-17T21:07:55Z | 39,558,966 | <h2>use volumes</h2>
<p>Share a so called host volume with your host, laptop, to write down the results directly on the host. e.g when starting your image</p>
<p><code>docker run -v /home/me/docker/results:/data/results <image></code></p>
<p>In your container, when you write on /data/results, all files will be... | 0 | 2016-09-18T14:50:38Z | [
"python",
"csv",
"docker",
"tensorflow"
] |
Detecting `<Enter>` and `<Leave>` events for a frame in tkinter | 39,551,850 | <p>I have a menu which when the user moves their mouse off I want to disappear. The menu consists of a <code>Frame</code> packed with several <code>Label</code>/<code>Button</code> widgets. I can detect the user moving their mouse off a <code>Label</code>/<code>Button</code> with simply binding to the <code><Enter&g... | -1 | 2016-09-17T21:19:39Z | 39,556,152 | <p>If you're just trying to simplify maintenance of the callbacks on the widgets, then I don't think binding events to the containing frame is the best approach. (I guess it's possible to generate virtual events in the callbacks on the buttons and labels, and bind the virtual event to the frame, but it seems rather co... | 0 | 2016-09-18T09:34:25Z | [
"python",
"tkinter"
] |
How do I copy values from one dictionary to a second dictionary with new keys? | 39,551,853 | <p>I am trying to make weapons in my game exclusive to certain classes. I have an item database in form:</p>
<pre><code>itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "light"},
3: {"name": "Studded Leather Armor", ... | 1 | 2016-09-17T21:19:58Z | 39,551,994 | <p>How do you feel about making <code>itemsList</code> an array instead of a dict? Seems like you're using it as an array anyhow. That way, you could do something like</p>
<pre><code>itemsList2 = [weapon for weapon in itemsList if weapon.type == "dagger"]
</code></pre>
<p>or if the weapon types are stored in, say, <c... | 0 | 2016-09-17T21:38:42Z | [
"python",
"dictionary",
"key"
] |
How do I copy values from one dictionary to a second dictionary with new keys? | 39,551,853 | <p>I am trying to make weapons in my game exclusive to certain classes. I have an item database in form:</p>
<pre><code>itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "light"},
3: {"name": "Studded Leather Armor", ... | 1 | 2016-09-17T21:19:58Z | 39,552,123 | <p>You could create a dict with usable items by class, so that for a given class, you have the list of the IDs it can equip as such :</p>
<pre><code>classItem = {
'rogue' : [1,2,3,12,13,14,15],
'mage' : [13,15,16,18],
'soldier' : [1,2,3,4,5,6,7],
}
</code></pre>
<p>Then t... | 0 | 2016-09-17T22:00:23Z | [
"python",
"dictionary",
"key"
] |
How to make loop repeat until the sum is a single digit? | 39,551,886 | <p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>T... | 2 | 2016-09-17T21:24:34Z | 39,551,939 | <p>You don't need to convert your integer to a float here; just use the <a href="https://docs.python.org/3/library/functions.html#divmod" rel="nofollow"><code>divmod()</code> function</a> in a loop:</p>
<pre><code>def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
... | 1 | 2016-09-17T21:31:30Z | [
"python"
] |
How to make loop repeat until the sum is a single digit? | 39,551,886 | <p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>T... | 2 | 2016-09-17T21:24:34Z | 39,551,949 | <p>You could utilize recursion.</p>
<p>Try this:</p>
<pre><code>def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
</code></pre>
| 1 | 2016-09-17T21:32:56Z | [
"python"
] |
How to make loop repeat until the sum is a single digit? | 39,551,886 | <p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>T... | 2 | 2016-09-17T21:24:34Z | 39,551,970 | <p>This should work, no division involved.</p>
<pre><code>n = int(input("Input an integer:"))
while n > 9:
n = sum([int(i) for i in str(n)])
print(n)
</code></pre>
<p>It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater... | 3 | 2016-09-17T21:35:04Z | [
"python"
] |
How to make loop repeat until the sum is a single digit? | 39,551,886 | <p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>T... | 2 | 2016-09-17T21:24:34Z | 39,552,059 | <p>I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.</p>
<pre><code>n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number... | 0 | 2016-09-17T21:48:12Z | [
"python"
] |
How to make loop repeat until the sum is a single digit? | 39,551,886 | <p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>T... | 2 | 2016-09-17T21:24:34Z | 39,552,332 | <p>If you like <strong>recursion</strong>, and you must:</p>
<pre><code>>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
</code></pre>
| 0 | 2016-09-17T22:32:41Z | [
"python"
] |
My celery redis task isn't working in my django app on heroku server | 39,551,927 | <p>I have a task that was working fine on my local server but when I pushed it to Heroku, nothing happens. there are no error messages. I am a newbie when it comes to this and locally I would start the worker by doing </p>
<pre><code>celery worker -A blog -l info.
</code></pre>
<p>So I'm guessing that's the issue ma... | 0 | 2016-09-17T21:30:08Z | 39,552,041 | <p>You need to add an entry in your Procfile to tell Heroku to start the Celery worker:</p>
<pre><code>worker:celery worker -A blog -l info
</code></pre>
| 1 | 2016-09-17T21:45:36Z | [
"python",
"django",
"heroku",
"deployment",
"redis"
] |
Python Twitter API Stream tweepy trying to save data to a CSV file | 39,551,928 | <pre><code>from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey = 'hidden due to question'
csecret = 'hidden due to question'
atoken = 'hidden due to question'
asecret = 'hidden due to question'
class listener(StreamListener):
def on_data(self, data):
... | 1 | 2016-09-17T21:30:09Z | 39,551,969 | <p>You open a <code>try</code> block without catching the exception.</p>
<p><a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">https://docs.python.org/3/tutorial/errors.html</a></p>
<p>Also be careful, python is case sensitive, so <code>saveFile</code> is not <code>saveFIle</code>, nor <code>save... | 0 | 2016-09-17T21:35:01Z | [
"python",
"api",
"csv",
"twitter"
] |
Apply a weight formula over a Dataframe using Numpy | 39,552,158 | <p>I have a Dataframe and am looking to divide the float value of a cell by the sum of the row where it resides. For this I use a numpy formula. This therefore would give me a weight for that cell for that row. I have this dataframe <code>df1</code>:</p>
<pre class="lang-none prettyprint-override"><code> ... | 0 | 2016-09-17T22:07:04Z | 39,552,360 | <p>The message error is quite informative in this case: <strong>you are trying to set an array element (<em>x</em>) with a sequence.</strong></p>
<p>Try to load your dataframe <code>df1</code> in a Python prompt and print the expression <code>np.sum(df1,axis=1)</code>: it returns a sequence -a vector- containing the s... | 4 | 2016-09-17T22:37:08Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Apply a weight formula over a Dataframe using Numpy | 39,552,158 | <p>I have a Dataframe and am looking to divide the float value of a cell by the sum of the row where it resides. For this I use a numpy formula. This therefore would give me a weight for that cell for that row. I have this dataframe <code>df1</code>:</p>
<pre class="lang-none prettyprint-override"><code> ... | 0 | 2016-09-17T22:07:04Z | 39,554,468 | <p>Try the following bit of code, which uses pandas features instead of an explicit function.</p>
<p>The function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow">div</a> performs an element wise division. You feed the total sums as a series to that function, and... | 1 | 2016-09-18T05:35:21Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Loading multiple PNGs in pyglet window | 39,552,160 | <p>If I loaded two partially transparent PNGs in succession (onDraw), would I still be able to see the first image if the second image was transparent in that area? These images would be drawn into a window. I would use Sprites but I couldn't get them to work. Thanks!</p>
| 0 | 2016-09-17T22:07:18Z | 39,744,446 | <p>There's no code in your question and quite frankly there's so many solutions to what I think is your problem that you could have at least 10 different answers here.</p>
<p>I'll vote to close this question but seeing as these are so rare and they usually don't get much response on either closing requests or down vot... | 0 | 2016-09-28T10:11:11Z | [
"python",
"pyglet"
] |
Functions and List Index Out Of Range | 39,552,170 | <p>I'm working on a simple yahtzee style dice game for class but I keep running into issues. Namely right now I'm having an issue with lists. I keep getting </p>
<pre><code> File "C:/Users/u1069284/Desktop/HW3_LandonShoaf.py", line 90, in scoring
counts[value] = counts[value] + 1
IndexError: list index out of ra... | 0 | 2016-09-17T22:08:39Z | 39,552,212 | <p>Try this : </p>
<pre><code>counts = [0]*7
for value in dice:
counts[value] += 1
</code></pre>
| 0 | 2016-09-17T22:14:40Z | [
"python"
] |
Functions and List Index Out Of Range | 39,552,170 | <p>I'm working on a simple yahtzee style dice game for class but I keep running into issues. Namely right now I'm having an issue with lists. I keep getting </p>
<pre><code> File "C:/Users/u1069284/Desktop/HW3_LandonShoaf.py", line 90, in scoring
counts[value] = counts[value] + 1
IndexError: list index out of ra... | 0 | 2016-09-17T22:08:39Z | 39,552,215 | <p>This:</p>
<pre><code>counts = [] * 7
for value in dice:
counts[value] = counts[value] + 1
</code></pre>
<p>Is not a valid way to initialize a list of <code>0</code> values, as you are expecting. Simply print out <code>[] * 7</code> at an interpreter, and you will see that your assumption was incorrect. It prod... | 0 | 2016-09-17T22:15:18Z | [
"python"
] |
Generator expression evaluation with several ... for ... in ... parts | 39,552,213 | <p><strong>Question</strong>: What does Python do under the hood when it sees this kind of expression? </p>
<pre><code>sum(sum(i) for j in arr for i in j)
</code></pre>
<hr>
<p><strong>My thoughts</strong>: <em>The above expression works.</em> But as it is written in <a href="https://docs.python.org/3.5/reference/e... | 0 | 2016-09-17T22:14:44Z | 39,552,306 | <p>Whether it is a generator or a list comprehension, the comprehension nesting is the same. It is easier to see what is going on with a list comprehension and that is what I will use in the examples below.</p>
<p>Given:</p>
<pre><code>>>> arr
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
</code></pre>... | 1 | 2016-09-17T22:29:59Z | [
"python",
"python-3.x",
"scope",
"nested",
"generator"
] |
Generator expression evaluation with several ... for ... in ... parts | 39,552,213 | <p><strong>Question</strong>: What does Python do under the hood when it sees this kind of expression? </p>
<pre><code>sum(sum(i) for j in arr for i in j)
</code></pre>
<hr>
<p><strong>My thoughts</strong>: <em>The above expression works.</em> But as it is written in <a href="https://docs.python.org/3.5/reference/e... | 0 | 2016-09-17T22:14:44Z | 39,552,690 | <blockquote>
<p>What does Python do under the hood when it sees this kind of expression?</p>
<pre><code> sum(sum(i) for j in array for i in j)
</code></pre>
</blockquote>
<p>It becomes something equivalent to:</p>
<pre><code>def __gen(it):
# "it" is actually in locals() as ".0"
for j in it:
for i i... | 2 | 2016-09-17T23:29:53Z | [
"python",
"python-3.x",
"scope",
"nested",
"generator"
] |
Loading local file in sc.textFile | 39,552,235 | <p>I try to load a local file as below</p>
<pre><code>File = sc.textFile('file:///D:/Python/files/tit.csv')
File.count()
</code></pre>
<p>Full traceback</p>
<pre><code>IllegalArgumentException Traceback (most recent call last)
<ipython-input-72-a84ae28a29dc> in <module>()
----> 1 Fil... | 1 | 2016-09-17T22:19:06Z | 39,557,033 | <p>Update:
There seems to be an issue with ":" in hadoop...</p>
<pre><code>filenames with ':' colon throws java.lang.IllegalArgumentException
</code></pre>
<p><a href="https://issues.apache.org/jira/browse/HDFS-13" rel="nofollow">https://issues.apache.org/jira/browse/HDFS-13</a></p>
<p>and </p>
<pre><code>Path shou... | 1 | 2016-09-18T11:13:40Z | [
"python",
"apache-spark"
] |
Loading local file in sc.textFile | 39,552,235 | <p>I try to load a local file as below</p>
<pre><code>File = sc.textFile('file:///D:/Python/files/tit.csv')
File.count()
</code></pre>
<p>Full traceback</p>
<pre><code>IllegalArgumentException Traceback (most recent call last)
<ipython-input-72-a84ae28a29dc> in <module>()
----> 1 Fil... | 1 | 2016-09-17T22:19:06Z | 39,557,162 | <p>I've done</p>
<pre><code>import os
os.path.normpath("file:///D:/Python/files/tit.csv")
Out[131]: 'file:/D:/Python/files/tit.csv'
</code></pre>
<p>then</p>
<pre><code>inputfile = sc.textFile(os.path.normpath("file:/D:/Python/files/tit.csv"))
inputfile.count()
IllegalArgumentException: u'java.net.URISyntaxException... | 0 | 2016-09-18T11:29:41Z | [
"python",
"apache-spark"
] |
Installing Python packages in command prompt not working well | 39,552,257 | <p>First, I'm very new to Python, and am having trouble getting any installs to work properly in command prompt. Here is the most recent example where, at the suggestion in the command prompt, I tried to upgrade to 'pip version 8.1.2', but got the messages indicated in the picture.</p>
<p><a href="http://i.stack.imgu... | -1 | 2016-09-17T22:22:20Z | 39,552,264 | <p>As your Python is installed in Program Files (a protected directory), you'll need to run command prompt as an administrator.</p>
| 0 | 2016-09-17T22:23:35Z | [
"python"
] |
Unable to print wanted item from json api | 39,552,276 | <p>I'm trying to print the 'temp' item from a json urlfile. The problem is, I can't just type in <code>print(item['temp']</code>
If i do I get this error: </p>
<blockquote>
<p>TypeError: string indices must be integers</p>
</blockquote>
<p>So I figured I had to use an integer instead, which is what I did. But when ... | -1 | 2016-09-17T22:25:31Z | 39,552,456 | <p><code>data['weather']</code> is a <em>dictionary</em>, and looping directly over a dictionary produces the keys in that dictionary. Here each key is a string; either <code>'curren_weather'</code> or <code>'forecast'</code>. As such, <code>item[0]</code> takes the first letter of each of these keys, so you end up pri... | 0 | 2016-09-17T22:49:22Z | [
"python",
"json",
"api",
"python-3.x",
"urllib"
] |
PyCharm ImportError: No module named googleapiclient | 39,552,299 | <p>I'm new to PyCharm and am trying to build/deploy a simple app to AppEngine. I've gone to PyCharm-->Preferences, clicked the Project Interpreter, and installed google-api-python-client which includes googleapiclient. However, when I run this app and load the page, it dies on this line:</p>
<pre><code>from googleap... | 0 | 2016-09-17T22:29:10Z | 39,558,553 | <p>From the client library's <a href="https://developers.google.com/api-client-library/python/guide/google_app_engine#installation" rel="nofollow">Installation instructions</a>:</p>
<blockquote>
<p>For information on installing the source for the library into your App
Engine project, see the <a href="https://devel... | 0 | 2016-09-18T14:12:44Z | [
"python",
"google-app-engine",
"pycharm",
"google-api-client"
] |
Can't install pyethereum module | 39,552,333 | <p>I'm new in Ethereum, so probably that's a silly question.</p>
<p>Now I'm trying to install serpent and pyethereum according to this <a href="https://github.com/ethereum/wiki/wiki/Serpent" rel="nofollow">tutorial</a>. Everything works well, but when I'm launching Python's code:</p>
<pre><code>import serpent
import ... | 1 | 2016-09-17T22:32:45Z | 39,552,445 | <p>Follow the installation instructions from <a href="https://github.com/ethereum/pyethereum" rel="nofollow">Pytherium's Readme</a>, which read:</p>
<pre><code>git clone https://github.com/ethereum/pyethereum/
cd pyethereum
python setup.py install
</code></pre>
<p>In the tutorial's instructions, <code>develop</code> ... | 1 | 2016-09-17T22:48:13Z | [
"python",
"ubuntu",
"ethereum"
] |
Can't install pyethereum module | 39,552,333 | <p>I'm new in Ethereum, so probably that's a silly question.</p>
<p>Now I'm trying to install serpent and pyethereum according to this <a href="https://github.com/ethereum/wiki/wiki/Serpent" rel="nofollow">tutorial</a>. Everything works well, but when I'm launching Python's code:</p>
<pre><code>import serpent
import ... | 1 | 2016-09-17T22:32:45Z | 39,553,016 | <p>The module's name is <code>ethereum</code>, not <code>pyethereum</code>. Using the following:</p>
<pre><code>import serpent
import ethereum
</code></pre>
<p>should work just fine.</p>
| 1 | 2016-09-18T00:34:54Z | [
"python",
"ubuntu",
"ethereum"
] |
How do I upload files to a specific folder in Django? | 39,552,338 | <p>After the user uploads 2 .ini files, I would like it to save both files inside the following folder.</p>
<p>MEDIA/uploadedconfigs/Printer/Plastic/</p>
<p>However, it's currently saving to the address below.</p>
<p>MEDIA/uploadedconfigs/None/</p>
<p><br></p>
<p>Below is the code that uploads the files. <br>
mode... | 1 | 2016-09-17T22:33:55Z | 39,552,420 | <p>You could replace the function <code>UploadedConfigPath</code> with this :</p>
<pre><code>def UploadedConfigPath(instance, filename):
return os.path.join('uploadedconfigs', 'Printer', 'Plastic', filename)
</code></pre>
<p><strong>Edit :</strong></p>
<p>This should do it :</p>
<pre><code>def UploadedConfigPat... | 1 | 2016-09-17T22:45:09Z | [
"python",
"django"
] |
How do I upload files to a specific folder in Django? | 39,552,338 | <p>After the user uploads 2 .ini files, I would like it to save both files inside the following folder.</p>
<p>MEDIA/uploadedconfigs/Printer/Plastic/</p>
<p>However, it's currently saving to the address below.</p>
<p>MEDIA/uploadedconfigs/None/</p>
<p><br></p>
<p>Below is the code that uploads the files. <br>
mode... | 1 | 2016-09-17T22:33:55Z | 39,552,422 | <p>try to use original approach by setting parameter in settings.py</p>
<pre><code> MEDIA_ROOT = join(PROJECT_ROOT, '../media/')"
MEDIA_URL = '/media/'
</code></pre>
<p>In your file:</p>
<pre><code>def UploadedConfigPath(instance, filename):
return os.path.join(settings.MEDIA_ROOT, 'uploadedconfigs/', str(in... | 2 | 2016-09-17T22:45:18Z | [
"python",
"django"
] |
Python sum() has a different result after importing numpy | 39,552,458 | <p>I came across this problem by Jake VanderPlas and I am not sure if my understanding of why the result differs after importing the numpy module is entirely correct.</p>
<pre><code>>>print(sum(range(5),-1)
>> 9
>> from numpy import *
>> print(sum(range(5),-1))
>> 10
</code></pre>
<p>It ... | 2 | 2016-09-17T22:49:36Z | 39,552,503 | <p><em>"the behavior of the function seems to have modified as the second arg is used to specify the axis along which the sum should be performed."</em></p>
<p>You have basically answered your own question!</p>
<p>It is not technically correct to say that the behavior of the function has been <em>modified</em>. <cod... | 10 | 2016-09-17T22:55:55Z | [
"python",
"numpy",
"sum"
] |
Python sum() has a different result after importing numpy | 39,552,458 | <p>I came across this problem by Jake VanderPlas and I am not sure if my understanding of why the result differs after importing the numpy module is entirely correct.</p>
<pre><code>>>print(sum(range(5),-1)
>> 9
>> from numpy import *
>> print(sum(range(5),-1))
>> 10
</code></pre>
<p>It ... | 2 | 2016-09-17T22:49:36Z | 39,552,721 | <p>Only to add my 5 pedantic coins to <a href="http://stackoverflow.com/a/39552503/6793085">@Warren Weckesser</a> answer. Really <code>from numpy import *</code> <strong>does not overwrite</strong> the <code>builtins</code> <code>sum</code> function, it only <strong>shadows</strong> <code>__builtins__.sum</code>, becau... | 6 | 2016-09-17T23:36:44Z | [
"python",
"numpy",
"sum"
] |
Exercise python: how to group element in a list? | 39,552,491 | <p>I've tried to solve the following exercise, without using datetime!</p>
<p>Exercise:</p>
<blockquote>
<p>Given a list of int, such that the First three int represent a date,
the second three elementi represent a date etc..modify lst by grouping
every triple in One string with the numbers separeted by "/".</p... | -1 | 2016-09-17T22:53:51Z | 39,552,518 | <p>You can use <code>zip</code> to create tuples and then format them to your strings:</p>
<pre><code>>>> ['%d/%d/%d' % parts for parts in zip(lst[::3], lst[1::3], lst[2::3])]
['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
<p>Starting from an offset (first argument to slicing) while skipping items (th... | 2 | 2016-09-17T22:58:53Z | [
"python",
"list"
] |
Exercise python: how to group element in a list? | 39,552,491 | <p>I've tried to solve the following exercise, without using datetime!</p>
<p>Exercise:</p>
<blockquote>
<p>Given a list of int, such that the First three int represent a date,
the second three elementi represent a date etc..modify lst by grouping
every triple in One string with the numbers separeted by "/".</p... | -1 | 2016-09-17T22:53:51Z | 39,552,542 | <p>You can group the list by it's index using <code>groupby</code> from <code>itertools</code>:</p>
<pre><code>from itertools import groupby
['/'.join(str(i[1]) for i in g) for _, g in groupby(enumerate(lst), key = lambda x: x[0]/3)]
# ['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
| 1 | 2016-09-17T23:03:07Z | [
"python",
"list"
] |
Exercise python: how to group element in a list? | 39,552,491 | <p>I've tried to solve the following exercise, without using datetime!</p>
<p>Exercise:</p>
<blockquote>
<p>Given a list of int, such that the First three int represent a date,
the second three elementi represent a date etc..modify lst by grouping
every triple in One string with the numbers separeted by "/".</p... | -1 | 2016-09-17T22:53:51Z | 39,552,592 | <p>This is more of a functional approach where the answer is passed around with the recursive function. </p>
<pre><code>lst1 = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000]
lst2 = []
lst3 = [1,2, 2015]
lst4 = [1,2]
lst5 = [1]
lst6 = [1,2,2013, 23, 9]
def groupToDate(lst, acc):
if len(lst) < 3:
return acc
... | 0 | 2016-09-17T23:11:25Z | [
"python",
"list"
] |
16 bit hex into 14 bit signed int python? | 39,552,549 | <p>I get a 16 bit Hex number (so 4 digits) from a sensor and want to convert it into a signed integer so I can actually use it.
There are plenty of codes on the internet that get the job done, but with this sensor it is a bit more arkward.</p>
<p>In fact, the number has only 14 bit, the first two (from the left) are i... | 0 | 2016-09-17T23:04:40Z | 39,552,600 | <p>There is a general algorithm for sign-extending a two's-complement integer value <code>val</code> whose number of bits is <code>nbits</code> (so that the top-most of those bits is the sign bit).</p>
<p>That algorithm is:</p>
<ol>
<li>treat the value as a non-negative number, and if needed, mask off additional bits... | 1 | 2016-09-17T23:12:48Z | [
"python",
"cut",
"bits",
"data-conversion"
] |
16 bit hex into 14 bit signed int python? | 39,552,549 | <p>I get a 16 bit Hex number (so 4 digits) from a sensor and want to convert it into a signed integer so I can actually use it.
There are plenty of codes on the internet that get the job done, but with this sensor it is a bit more arkward.</p>
<p>In fact, the number has only 14 bit, the first two (from the left) are i... | 0 | 2016-09-17T23:04:40Z | 39,552,656 | <p>Let's define a conversion function:</p>
<pre><code>>>> def f(x):
... r = int(x, 16)
... return r if r < 2**15 else r - 2**16
...
</code></pre>
<p>Now, let's test the function against the values that the datahsheet provided:</p>
<pre><code>>>> f('1FFE')
8190
>>> f('E002')
-819... | 2 | 2016-09-17T23:23:26Z | [
"python",
"cut",
"bits",
"data-conversion"
] |
Extract multiple substrings from a file and list them in another place using python/shell | 39,552,662 | <p>I've got a log file similar to below:</p>
<pre><code>/* BUG: axiom too complex: SubClassOf(ObjectOneOf([NamedIndividual(http://www.sem.org/sina/onto/2015/7/TSB-GCL#t_Xi_xi)]),DataHasValue(DataProperty(http://www.code.org/onto/ont.owl#XoX_type),^^(periodic,http://www.mdos.org/1956/21/2-rdf-syntax-ns#PlainLiteral))) ... | 0 | 2016-09-17T23:24:46Z | 39,552,763 | <pre><code>$ awk -F'#|\\^\\^\\(' '{for (i=2; i<NF; i++) printf "%s%s", gensub(/[^[:alnum:]_].*/,"",1,$i), (i<(NF-1) ? OFS : ORS) }' file
t_Xi_xi XoX_type periodic
t_Ziz YoY_type latency
</code></pre>
<p>The above uses GNU awk for gensub(), with other awks you'd use sub() and a separate printf statement.</p>
| 1 | 2016-09-17T23:44:04Z | [
"python",
"string",
"shell",
"sed",
"substring"
] |
threading.Lock() performance issues | 39,552,670 | <p>I have multiple threads:</p>
<pre><code>dispQ = Queue.Queue()
stop_thr_event = threading.Event()
def worker (stop_event):
while not stop_event.wait(0):
try:
job = dispQ.get(timeout=1)
job.waitcount -= 1
dispQ.task_done()
except Queue.Empty, msg:
c... | 0 | 2016-09-17T23:25:39Z | 39,552,982 | <p>About the only way to "optimize" threading would be to break the processing down in blocks or chunks of work that can be performed at the same time. This mostly means doing input or output (I/O) because that is the only time the interpreter will release the Global Interpreter Lock, aka the GIL.</p>
<p>In actuality ... | 1 | 2016-09-18T00:25:13Z | [
"python",
"multithreading"
] |
threading.Lock() performance issues | 39,552,670 | <p>I have multiple threads:</p>
<pre><code>dispQ = Queue.Queue()
stop_thr_event = threading.Event()
def worker (stop_event):
while not stop_event.wait(0):
try:
job = dispQ.get(timeout=1)
job.waitcount -= 1
dispQ.task_done()
except Queue.Empty, msg:
c... | 0 | 2016-09-17T23:25:39Z | 39,564,266 | <p>It's hard to answer your question based on your code. Locks do have some inherent cost, nothing is free, but normally it is quite small. If your jobs are very small, you might want to consider "chunking" them, that way you have many fewer acquire/release calls relative to the amount of work being done by each thread... | 1 | 2016-09-19T01:42:26Z | [
"python",
"multithreading"
] |
Printing a X using * in Python | 39,552,673 | <p>I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *</p>
<p>I have been experimenting over the past couple... | 1 | 2016-09-17T23:26:07Z | 39,552,715 | <p>I'll give you a hint :</p>
<pre><code>n = int(input("Please type in an odd integer."))
for i in range(n):
print('x', end='')
print()
</code></pre>
<p>This prints a x, n times on the same line and then go back to next line.</p>
<p>I'll let you figure out how you print this same line n times.</p>
| 0 | 2016-09-17T23:35:35Z | [
"python",
"for-loop",
"nested-loops"
] |
Printing a X using * in Python | 39,552,673 | <p>I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *</p>
<p>I have been experimenting over the past couple... | 1 | 2016-09-17T23:26:07Z | 39,552,934 | <p>This should do it:</p>
<p><strong>Python 2</strong></p>
<pre><code>N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print '*',
else:
print ' ',
print ''
</code></pre>
<p><strong>Python 3</strong></p>
<pre><code>N = 5
for i in range(N)... | 0 | 2016-09-18T00:16:50Z | [
"python",
"for-loop",
"nested-loops"
] |
Printing a X using * in Python | 39,552,673 | <p>I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *</p>
<p>I have been experimenting over the past couple... | 1 | 2016-09-17T23:26:07Z | 39,554,568 | <p>Using single for loop:</p>
<pre><code>for i in range(num):
a = [' '] * num
a[i] = '*'
a[num-i-1] = '*'
print(''.join(a))
</code></pre>
<p>Using nested for loops:</p>
<pre><code>for i in range(num):
s = ''
for j in range(num):
if j in [i, num-i-1]:
s += '*'
else:... | 0 | 2016-09-18T05:50:22Z | [
"python",
"for-loop",
"nested-loops"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.