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 |
|---|---|---|---|---|---|---|---|---|---|
df.mean is not the real mean of the Series? | 38,947,278 | <p>I'm debugging and run into the following strange behavior.
I'm calculating the mean of a pandas series which contains all exactly the same numbers. However, the <code>pd.mean()</code> gives a different number.</p>
<p>question1: why mean of this Series is a different number?</p>
<p>question2: <code>tmm[-1]== tmm.mean()</code> gives <code>False</code> now. Any way to ignore this small difference and make the results True? I don't prefer <code>abs(tmm[-1]-tmm.mean()) < xxx</code> </p>
<p>methods because not sure how to define <code>xxx</code>.</p>
<pre><code>import pandas as pd
import decimal
tmm = pd.Series(14.9199999999999999289457264239899814128875732421875,
index=range(30))
for t in tmm:
print(decimal.Decimal(t))
print('mean is')
print(decimal.Decimal(tmm.mean()))
</code></pre>
<p>results:</p>
<pre><code>14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
14.9199999999999999289457264239899814128875732421875
mean is
14.9200000000000034816594052244909107685089111328125
</code></pre>
| 1 | 2016-08-14T22:46:30Z | 38,948,126 | <p>Try using <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html" rel="nofollow">np.isclose()</a></p>
<pre><code>tmm[20]== tmm.mean()
False
np.isclose(tmm[20], tmm.mean())
True
</code></pre>
| 1 | 2016-08-15T01:18:10Z | [
"python",
"pandas"
] |
python script that imports matplotlib succeeds butfrozen binary of script fails | 38,947,330 | <p>My script needed to import <code>numpy</code>, <code>sklearn</code>, and <code>matplotlib</code> but I couldn't install sklearn. A very helpful response to my question <a href="http://http://stackoverflow.com/questions/38733220/difference-between-scikit-learn-and-sklearn" rel="nofollow">http://http://stackoverflow.com/questions/38733220/difference-between-scikit-learn-and-sklearn</a> explained that I needed to reinstall numpy. Using pip to update numpy failed because OS X 10.11 SIP prevented uninstalling the current numpy. The very helpful answer to a question about pip and SIP by mfripp <a href="http://http://apple.stackexchange.com/questions/209572/how-to-use-pip-after-the-os-x-el-capitan-upgrade" rel="nofollow">http://http://apple.stackexchange.com/questions/209572/how-to-use-pip-after-the-os-x-el-capitan-upgrade</a> provided a detailed solution to the problem. I followed those instruction exactly and used <code>pip</code> to reinstall <code>numpy</code>, <code>matplotlib</code>, <code>scipy</code> and <code>sklearn</code> for all users.</p>
<p>When I ran my completed script using the command </p>
<blockquote>
<p>python DistMatPlot.py Random10A.matrix Random10A.pdf</p>
</blockquote>
<p>the script ran perfectly, writing all expected output files.</p>
<p>However, I always saw: </p>
<blockquote>
<p>"/Library/Python/2.7/site-packages/matplotlib/font_manager.py:273:
UserWarning: Matplotlib is building the font cache using fc-list. This
may take a moment. warnings.warn('Matplotlib is building the font
cache using fc-list. This may take a moment.')"</p>
</blockquote>
<p>which I had never seen with other matplotlib scripts before updating numpy, matplotlib, etc. The 2 second delay was only mildly annoying.</p>
<p>I compiled a frozen binary using pyinstaller and during the compiling I got several messages similar to that above.
The resulting frozen binary run failed with the command:</p>
<blockquote>
<p>./DistMatPlot Random10A.matrix Random10A.pdf</p>
</blockquote>
<p>produced the following:</p>
<blockquote>
<p>/var/folders/8x/7_zp_33h8xj6td0059b72p9h0000gp/T/_MEIhIysTV/matplotlib/font_manager.py:273:
UserWarning: Matplotlib is building the font cache using fc-list. This
may take a moment. Traceback (most recent call last): File
"", line 13, in File
"/Library/Python/2.7/site-packages/PyInstaller/loader/pyimod03_importers.py",
line 389, in load_module
exec(bytecode, module.<strong>dict</strong>) File "matplotlib/pyplot.py", line 114, in File "matplotlib/backends/<strong>init</strong>.py", line
32, in pylab_setup File
"/Library/Python/2.7/site-packages/PyInstaller/loader/pyimod03_importers.py",
line 389, in load_module
exec(bytecode, module.<strong>dict</strong>) File "matplotlib/backends/backend_macosx.py", line 24, in File
"/Library/Python/2.7/site-packages/PyInstaller/loader/pyimod03_importers.py",
line 546, in load_module
module = imp.load_module(fullname, fp, filename, ext_tuple) RuntimeError: Python is not installed as a framework. The Mac OS X
backend will not be able to function correctly if Python is not
installed as a framework. See the Python documentation for more
information on installing Python as a framework on Mac OS X. Please
either reinstall Python as a framework, or try one of the other
backends. If you are Working with Matplotlib in a virtual enviroment
see 'Working with Matplotlib in Virtual environments' in the
Matplotlib FAQ DistMatPlot returned -1</p>
</blockquote>
<p>I have looked at similar questions and tried their suggested solutions to no avail.</p>
<p>(1) Why does matplotlib need to rebuild a font cache each time it is run?</p>
<p>(2) Why does the frozen binary fail when the script itself succeeds? Do I need some additional option other than -F when running pyinstaller?</p>
| 0 | 2016-08-14T22:55:19Z | 38,961,350 | <p>The issue with the frozen binary turned out to be "RuntimeError: Python is not installed as a framework."</p>
<p>Several posts discussed that issue and suggested adding these two lines before "import matplotlib.pyplot as plt":</p>
<p>import matplotlib<br>
matplotlib.use('TkAgg')</p>
<p>That did not work, but this slight modification did work:
import matplotlib<br>
matplotlib.use('Agg')</p>
<p>I suspect that 'Agg" may be specific to either OS X or to the version of python that is included with OS X 10.11</p>
| 0 | 2016-08-15T19:04:19Z | [
"python",
"matplotlib"
] |
Pandas: Loop through dataframe with out counter | 38,947,347 | <p>I have a data frame <code>df</code> which has dates in it:</p>
<pre><code>df['Survey_Date'].head(4)
Out[65]:
0 1990-09-28
1 1991-07-26
2 1991-11-23
3 1992-10-15
</code></pre>
<p>I am interested in calculating a metric between two of the dates, using a separate data frame <code>flow_df</code>. </p>
<p><code>flow_df</code> looks like:</p>
<pre><code> date flow
0 1989-01-01 7480
1 1989-01-02 5070
2 1989-01-03 6410
3 1989-01-04 10900
4 1989-01-05 11700
</code></pre>
<p>For instance, I would like to query another data frame based on the <code>current_date</code> and <code>early_date</code>. The first time period of interest would be:</p>
<pre><code>current_date = 1991-07-26
early_date = 1990-09-28
</code></pre>
<p>I have written a clunky for loop and it gets the job done, but I am sure there is a more elegant way:</p>
<p>My approach with a counter and for loop:</p>
<pre><code>def find_peak(early_date,current_date,flow_df):
mask = (flow_df['date']>= early_date) & (flow_df['date'] < current_date)
query = flow_df.loc[mask]
peak_flow = np.max(query['flow'])*0.3048**3
return peak_flow
n=0
for thing in df['Survey_Date'][1:]:
early_date = df['Survey_Date'][n]
current_date = thing
peak_flow = find_peak(early_date,current_date,flow_df)
n+=1
df['Avg_Stage'][n] = peak_flow
</code></pre>
<p>How can I do this without a counter and for loop?</p>
<p>The desired output looks like:</p>
<pre><code> Survey_Date Avg_Stage
0 1990-09-28
1 1991-07-26 574.831986
2 1991-11-23 526.693347
3 1992-10-15 458.732915
4 1993-04-01 855.168767
5 1993-11-17 470.059653
6 1994-04-07 419.089330
7 1994-10-21 450.237861
8 1995-04-24 498.376500
9 1995-06-23 506.871554
</code></pre>
| 0 | 2016-08-14T22:57:17Z | 38,947,462 | <p>You can use <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow"><code>zip()</code></a>:</p>
<pre><code>for early_date, current_date in zip(df['Survey_Date'], df['Survey_Date'][1:]):
#do whatever yo want.
</code></pre>
<p>Of course you can put it into a <a class='doc-link' href="http://stackoverflow.com/documentation/python/5265/list-comprehensions#t=201608142330382529237">list comprehension</a>:</p>
<pre><code>[some_metric(early_date, current_date) for early_date, current_date in zip(df['Survey_Date'], df['Survey_Date'][1:])]
</code></pre>
| 0 | 2016-08-14T23:16:35Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: Loop through dataframe with out counter | 38,947,347 | <p>I have a data frame <code>df</code> which has dates in it:</p>
<pre><code>df['Survey_Date'].head(4)
Out[65]:
0 1990-09-28
1 1991-07-26
2 1991-11-23
3 1992-10-15
</code></pre>
<p>I am interested in calculating a metric between two of the dates, using a separate data frame <code>flow_df</code>. </p>
<p><code>flow_df</code> looks like:</p>
<pre><code> date flow
0 1989-01-01 7480
1 1989-01-02 5070
2 1989-01-03 6410
3 1989-01-04 10900
4 1989-01-05 11700
</code></pre>
<p>For instance, I would like to query another data frame based on the <code>current_date</code> and <code>early_date</code>. The first time period of interest would be:</p>
<pre><code>current_date = 1991-07-26
early_date = 1990-09-28
</code></pre>
<p>I have written a clunky for loop and it gets the job done, but I am sure there is a more elegant way:</p>
<p>My approach with a counter and for loop:</p>
<pre><code>def find_peak(early_date,current_date,flow_df):
mask = (flow_df['date']>= early_date) & (flow_df['date'] < current_date)
query = flow_df.loc[mask]
peak_flow = np.max(query['flow'])*0.3048**3
return peak_flow
n=0
for thing in df['Survey_Date'][1:]:
early_date = df['Survey_Date'][n]
current_date = thing
peak_flow = find_peak(early_date,current_date,flow_df)
n+=1
df['Avg_Stage'][n] = peak_flow
</code></pre>
<p>How can I do this without a counter and for loop?</p>
<p>The desired output looks like:</p>
<pre><code> Survey_Date Avg_Stage
0 1990-09-28
1 1991-07-26 574.831986
2 1991-11-23 526.693347
3 1992-10-15 458.732915
4 1993-04-01 855.168767
5 1993-11-17 470.059653
6 1994-04-07 419.089330
7 1994-10-21 450.237861
8 1995-04-24 498.376500
9 1995-06-23 506.871554
</code></pre>
| 0 | 2016-08-14T22:57:17Z | 38,947,738 | <p>Since the question is unclear, I'm posting this idea of using filters:</p>
<pre><code>flow_df[(flow_df["Date"] <= '1991-07-26' ) & (flow_df["Date"] >= '1990-09-26' ) ].max()
current_date = '1991-07-26'
early_date = '1990-09-28'
flow_df[(flow_df["Date"] <= current_date) & (flow_df["Date"] >= early_date ) ].max()
</code></pre>
| -1 | 2016-08-15T00:06:38Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: Loop through dataframe with out counter | 38,947,347 | <p>I have a data frame <code>df</code> which has dates in it:</p>
<pre><code>df['Survey_Date'].head(4)
Out[65]:
0 1990-09-28
1 1991-07-26
2 1991-11-23
3 1992-10-15
</code></pre>
<p>I am interested in calculating a metric between two of the dates, using a separate data frame <code>flow_df</code>. </p>
<p><code>flow_df</code> looks like:</p>
<pre><code> date flow
0 1989-01-01 7480
1 1989-01-02 5070
2 1989-01-03 6410
3 1989-01-04 10900
4 1989-01-05 11700
</code></pre>
<p>For instance, I would like to query another data frame based on the <code>current_date</code> and <code>early_date</code>. The first time period of interest would be:</p>
<pre><code>current_date = 1991-07-26
early_date = 1990-09-28
</code></pre>
<p>I have written a clunky for loop and it gets the job done, but I am sure there is a more elegant way:</p>
<p>My approach with a counter and for loop:</p>
<pre><code>def find_peak(early_date,current_date,flow_df):
mask = (flow_df['date']>= early_date) & (flow_df['date'] < current_date)
query = flow_df.loc[mask]
peak_flow = np.max(query['flow'])*0.3048**3
return peak_flow
n=0
for thing in df['Survey_Date'][1:]:
early_date = df['Survey_Date'][n]
current_date = thing
peak_flow = find_peak(early_date,current_date,flow_df)
n+=1
df['Avg_Stage'][n] = peak_flow
</code></pre>
<p>How can I do this without a counter and for loop?</p>
<p>The desired output looks like:</p>
<pre><code> Survey_Date Avg_Stage
0 1990-09-28
1 1991-07-26 574.831986
2 1991-11-23 526.693347
3 1992-10-15 458.732915
4 1993-04-01 855.168767
5 1993-11-17 470.059653
6 1994-04-07 419.089330
7 1994-10-21 450.237861
8 1995-04-24 498.376500
9 1995-06-23 506.871554
</code></pre>
| 0 | 2016-08-14T22:57:17Z | 38,948,404 | <p>You can define a new variable that identifies survey period and use <code>pandas.DataFrame.groupby</code> to avoid <code>for</code> loop. It should be much faster when <code>flow_df</code> is large.</p>
<pre><code>#convert both to datetime, if they are not
df['Survey_Date'] = pd.to_datetime(df['Survey_Date'])
flow_df['date'] = pd.to_datetime(flow_df['date'])
#Merge Survey_Date to flow_df. Most rows of flow_df['Survey_Date'] should be NaT
flow_df = flow_df.merge(df, left_on='date', right_on='Survey_Date', how='outer')
# In case not all Survey_Date in flow_df['date'] or data not sorted by date.
flow_df['date'].fillna(flow_df['Survey_Date'], inplace=True)
flow_df.sort_values('date', inplace=True)
#Identify survey period. In your example: [1990-09-28, 1991-07-26) is represented by 0; [1991-07-26, 1991-11-23) = 1; etc.
flow_df['survey_period'] = flow_df['Survey_Date'].notnull().cumsum()
#calc Avg_Stage in each survey_period. I did .shift(1) because you want to align period [1990-09-28, 1991-07-26) to 1991-07-26
df['Avg_Stage'] = (flow_df.groupby('survey_period')['flow'].max()*0.3048**3).shift(1)
</code></pre>
| 2 | 2016-08-15T02:08:35Z | [
"python",
"pandas",
"dataframe"
] |
How to selectively iterate over files with Python | 38,947,428 | <p>I would like to iterate through files in a specified directory which are bigger then 100 kb and end with a *.zip.</p>
<p>How can this be done in a efficient way?</p>
<p>Will go through any zip files but not necessarily files which are bigger than 100kb;</p>
<pre><code>for i in os.listdir(os.getcwd()):
if i.endswith(".zip"):
##print i
continue
else:
continue
</code></pre>
<p>How can I incoprporate it in the if conditions? ie (<code>if i.endswith(".zip") and >100kb</code>). How could I used this file as an argument with <code>myOtherPythonScript.py</code>? </p>
| 0 | 2016-08-14T23:11:09Z | 38,947,618 | <p>You could try something like this...</p>
<pre><code>for i in os.listdir(os.getcwd()):
if i.endswith(".zip"):
if os.path.getsize(i) > 10240:
print i
continue
else:
continue
</code></pre>
| 1 | 2016-08-14T23:45:44Z | [
"python"
] |
How to selectively iterate over files with Python | 38,947,428 | <p>I would like to iterate through files in a specified directory which are bigger then 100 kb and end with a *.zip.</p>
<p>How can this be done in a efficient way?</p>
<p>Will go through any zip files but not necessarily files which are bigger than 100kb;</p>
<pre><code>for i in os.listdir(os.getcwd()):
if i.endswith(".zip"):
##print i
continue
else:
continue
</code></pre>
<p>How can I incoprporate it in the if conditions? ie (<code>if i.endswith(".zip") and >100kb</code>). How could I used this file as an argument with <code>myOtherPythonScript.py</code>? </p>
| 0 | 2016-08-14T23:11:09Z | 38,947,660 | <p><code>endswith</code> and <code>os.path.getsize</code> are the two functions you want.</p>
<pre><code>import os
file_names = [os.path.join(path, file_name) for file_name in os.listdir(path)]
for file_name in file_names:
if file_name.endswith('zip') and os.path.getsize(file_name) >= 100*1024:
pass
else:
pass
</code></pre>
| 0 | 2016-08-14T23:53:49Z | [
"python"
] |
Chrome Not Starting When Using ChromeDriver | 38,947,469 | <p>I'm trying to use Selenium and ChromeDriver to write a scraping job. When I run the following code though nothing happens, in the sense that Chrome doesn't appear to start, but I don't get an error.</p>
<pre><code>import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get(r"http://www.python.org")
time.sleep(10)
driver.quit()
</code></pre>
<p>Is there something else that I need to do to make Chrome start?</p>
| 1 | 2016-08-14T23:17:45Z | 38,947,851 | <p>You need to download chromedriver from <a href="https://sites.google.com/a/chromium.org/chromedriver/" rel="nofollow">here</a> and put it in your path. I also see that you have a typo in driver.get, make sure you have a correct URL as well</p>
<p>Below is the typo I was talking about </p>
<pre><code>driver.get(r"http://www.python.org")
</code></pre>
| 1 | 2016-08-15T00:29:57Z | [
"python",
"selenium",
"selenium-chromedriver"
] |
Run python-rq worker process on application start | 38,947,480 | <p>I hosted my Django app on Heroku but due to few limitations I moved from Heroku to cloud based server. I followed this <a href="https://devcenter.heroku.com/articles/python-rq" rel="nofollow">tutorial</a> on running background tasks in Python. Everything is running fine except that I have to manually run <code>python worker.py</code> to start worker process.</p>
<p>On Heroku we can use Procfile to run processes when app starts but now I am on a cloud based server running ubuntu 14.04. So what is the alternative to Procfile?</p>
<p><strong>worker.py</strong></p>
<pre><code>import os
import redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__':
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
</code></pre>
| 0 | 2016-08-14T23:19:24Z | 38,951,814 | <p>Use a process manager like upstart, systemd or supervisor.</p>
| 0 | 2016-08-15T08:33:27Z | [
"python",
"django",
"heroku",
"python-rq"
] |
Run python-rq worker process on application start | 38,947,480 | <p>I hosted my Django app on Heroku but due to few limitations I moved from Heroku to cloud based server. I followed this <a href="https://devcenter.heroku.com/articles/python-rq" rel="nofollow">tutorial</a> on running background tasks in Python. Everything is running fine except that I have to manually run <code>python worker.py</code> to start worker process.</p>
<p>On Heroku we can use Procfile to run processes when app starts but now I am on a cloud based server running ubuntu 14.04. So what is the alternative to Procfile?</p>
<p><strong>worker.py</strong></p>
<pre><code>import os
import redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__':
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
</code></pre>
| 0 | 2016-08-14T23:19:24Z | 38,951,911 | <p>I ended up using upstart. I created a new config file <code>rqworker.py</code> using <code>sudo nano \etc\init\rqworker.conf</code> with the following code:</p>
<pre><code>description "Job queues for directory"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
setuid myuser
setgid www-data
exec python3.5 worker.py
</code></pre>
<p>Then I just started the service <code>sudo service rqworker start</code> and now my worker processes are running in the background.</p>
| 1 | 2016-08-15T08:41:20Z | [
"python",
"django",
"heroku",
"python-rq"
] |
Repeating elements in a list | 38,947,499 | <p>I have a list with elements:</p>
<pre><code>a = ['Monica', 'Mark', 'Nick', 'Margaret']
</code></pre>
<p>and I'd like to obtain the following list of names:</p>
<pre><code>['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'Margaret']
</code></pre>
<p>The simplest solution I came up with is:</p>
<pre><code>lnames = []
for i, j in zip(a,a):
lnames.append(i)
lnames.append(j)
</code></pre>
<p>I've also tried to use a comprehension list:</p>
<pre><code>lnames2 = [list(x) for x in zip(a,a)]
</code></pre>
<p>but in this case I'm getting:</p>
<pre><code>[['Monica', 'Monica'], ['Mark', 'Mark'], ['Nick', 'Nick'], ['Margaret', 'Margaret']]
</code></pre>
<p>and don't know how to get the desire list from that point.</p>
<p>I'd like to ask you what are your solutions for this task. </p>
| -4 | 2016-08-14T23:24:40Z | 38,947,581 | <p>Try this</p>
<pre><code>def repeat(collection, count):
for x in collection:
for i in range(count):
yield x
a = ['Monica', 'Mark', 'Nick', 'Margaret']
print [x for x in repeat(a, 2)]
</code></pre>
<p>prints</p>
<pre><code>['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'Margaret']
</code></pre>
| 1 | 2016-08-14T23:36:58Z | [
"python",
"pandas"
] |
Repeating elements in a list | 38,947,499 | <p>I have a list with elements:</p>
<pre><code>a = ['Monica', 'Mark', 'Nick', 'Margaret']
</code></pre>
<p>and I'd like to obtain the following list of names:</p>
<pre><code>['Monica', 'Monica', 'Mark', 'Mark', 'Nick', 'Nick', 'Margaret', 'Margaret']
</code></pre>
<p>The simplest solution I came up with is:</p>
<pre><code>lnames = []
for i, j in zip(a,a):
lnames.append(i)
lnames.append(j)
</code></pre>
<p>I've also tried to use a comprehension list:</p>
<pre><code>lnames2 = [list(x) for x in zip(a,a)]
</code></pre>
<p>but in this case I'm getting:</p>
<pre><code>[['Monica', 'Monica'], ['Mark', 'Mark'], ['Nick', 'Nick'], ['Margaret', 'Margaret']]
</code></pre>
<p>and don't know how to get the desire list from that point.</p>
<p>I'd like to ask you what are your solutions for this task. </p>
| -4 | 2016-08-14T23:24:40Z | 38,947,662 | <p>Here's a working example:</p>
<pre><code>import itertools
a = ['Monica', 'Mark', 'Nick', 'Margaret']
num_repeats = 2
lnames2 = list(itertools.chain(*[[x] * num_repeats for x in a]))
print(lnames2)
</code></pre>
| 1 | 2016-08-14T23:54:06Z | [
"python",
"pandas"
] |
How to make a specific type of python face tracker | 38,947,519 | <p>Recently I have been working on a face tracker using python 3 and opencv and my laptops webcam, I've made it so that a window will pop up and display the webcam feed when you run the .pyw script, and I've mad a python script that detects a face on a frozen image with haarcascades, but I cant seem to combine the two,
so here's the webcam program;</p>
<pre><code> import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
vc.release()
cv2.destroyWindow("preview")
</code></pre>
<p>Here is the face detect script, which I have In a folder with the haar xml file and a jpg, I have created a desktop shortcut to the script which runs it with the picture and the frontal face xml upon a double click of the shortcut.</p>
<pre><code>import cv2
import sys
import time
imagePath = sys.argv[1]
cascPath = sys.argv[2]
faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(30, 30))#,flags = cv2.cv.CV_HAAR_IMAGE_SCALE)
print("Found {0} faces!".format(len(faces)))
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found" ,image)
cv2.waitKey(0)&0xFF
</code></pre>
<p>Remember all I need to do is make a live face tracker using the first block of code, also note I am a beginner, so please explain - Thanks!</p>
<p>Oh yeah, combined they look like;</p>
<pre><code>import cv2
import sys
import time
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
imagePath = sys.argv[1]
cascPath = sys.argv[2]
faceCascade = cv2.CascadeClassifier(cascPath)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(30, 30))#,flags = cv2.cv.CV_HAAR_IMAGE_SCALE)
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
vc.release()
cv2.destroyWindow("preview")
</code></pre>
<p>My errors are as follows,</p>
<p>Traceback (most recent call last):
File "C:\Users\tcwissemann\Desktop\WebDetect.pyw", line 8, in
imagePath = sys.argv[1]
IndexError: list index out of range</p>
| 0 | 2016-08-14T23:27:06Z | 38,964,472 | <p>Never mind, I already fixed it.</p>
<pre><code>import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
vc = cv2.VideoCapture(0)
while -1:
ret, img = vc.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,171),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,188,255),2)
smiling = smile_cascade.detectMultiScale(roi_gray, 1.7, 5)
for (sx,sy,sw,sh) in smiling:
cv2.rectangle(roi_color,(sx,sy),(sx+sw,sy+sh),(240,19,93),2)
cv2.imshow('WebDetect',img)
k = cv2.waitKey(30) & 0xff
if k == 27:
vc.release()
cv2.destroyAllWindows()
</code></pre>
| 0 | 2016-08-15T23:26:43Z | [
"python",
"python-3.x",
"opencv"
] |
Convert pandas (python) categorical x-axis to continuous values when plotting | 38,947,522 | <p>I am plotting a pandas series in python using the matplotlib <code>plot</code> command (i.e. <code>series.plot()</code>, where <code>series</code> is my series). Part of the series is as follows:</p>
<pre><code>(1, 1.1] 0.000000
(1.1, 1.2] 0.000000
(1.2, 1.3] 0.000000
(1.3, 1.4] 0.003115
(1.4, 1.5] 0.002625
(1.5, 1.6] 0.000000
(1.6, 1.7] 0.001464
... ...
(4.9, 5.0] 0.737385
Name: series, dtype: float64
</code></pre>
<p>A plot of my dataframe is <a href="http://i.stack.imgur.com/yklf0.png" rel="nofollow">shown here</a> (the red line in this case). I want the x-axis to go from 1.0 to 5.0 instead of showing the bin categories. How can I achieve this? Using <code>plt.xticks</code> doesn't seem to work. </p>
| 1 | 2016-08-14T23:27:19Z | 38,948,031 | <p>Where does the series come from? Usually, I have a big dataframe of continuous-valued columns <code>X</code> and <code>Y</code>, and then define <code>X-bins</code>s according to <code>X</code> values. After that, group by <code>X-bins</code> to calculate average (or weighted average, or sum, or any other aggregation function) of <code>Y</code> to get the series like yours. If that's the case, I would suggest calculate mean of <code>X</code> in this process and plot against average <code>X</code> instead of <code>X-bins</code>. This will be more precise than taking left/right end points or mid-points of the bins for plotting. E.g.,</p>
<pre><code>df['Xbin'] = pd.cut(df['X'], np.arange(0,10,0.1))
</code></pre>
<p>Instead of </p>
<pre><code>ser = df.groupby('Xbin')['Y'].mean()
ser.plot()
</code></pre>
<p>do</p>
<pre><code>df2 = df.groupby('Xbin')[['X','Y']].mean()
df2.plot(x='X', y='Y')
</code></pre>
| 0 | 2016-08-15T00:59:11Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Convert pandas (python) categorical x-axis to continuous values when plotting | 38,947,522 | <p>I am plotting a pandas series in python using the matplotlib <code>plot</code> command (i.e. <code>series.plot()</code>, where <code>series</code> is my series). Part of the series is as follows:</p>
<pre><code>(1, 1.1] 0.000000
(1.1, 1.2] 0.000000
(1.2, 1.3] 0.000000
(1.3, 1.4] 0.003115
(1.4, 1.5] 0.002625
(1.5, 1.6] 0.000000
(1.6, 1.7] 0.001464
... ...
(4.9, 5.0] 0.737385
Name: series, dtype: float64
</code></pre>
<p>A plot of my dataframe is <a href="http://i.stack.imgur.com/yklf0.png" rel="nofollow">shown here</a> (the red line in this case). I want the x-axis to go from 1.0 to 5.0 instead of showing the bin categories. How can I achieve this? Using <code>plt.xticks</code> doesn't seem to work. </p>
| 1 | 2016-08-14T23:27:19Z | 38,948,056 | <p>Based on our discussion, your series has an index that is a string of the intervals, eg. <code>'(1,1.1]'</code> is the index of the first item in the series. </p>
<p>I was able to reproduce your issue using the following code:</p>
<pre><code>import pandas as pd
import numpy as np
x1 = np.arange(0,5,.1)
x2 = np.arange(0.1,5.1,.1)
y = x1**2
df = pd.DataFrame(np.vstack((x1,x2,y)).T, columns=['x1','x2','y'])
df['xRange'] = '(' + df.x1.map(str) + ', ' + df.x2.map(str) + ']'
series = df.set_index('xRange', drop=True)['y']
series.plot()
</code></pre>
<p>To get the ticks labelled correctly <strong>using just the</strong> <code>series</code> object, you need to strip the index off and pull out the first part of the interval.</p>
<p>You can recover the dataframe for plotting purposes via:</p>
<pre><code>new_df = pd.DataFrame(series)
new_index = series.index.map(lambda s: float(s.split(',')[0].replace('(','')))
new_df.set_index(new_index, inplace=True)
new_df.plot()
</code></pre>
| 1 | 2016-08-15T01:04:28Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
imshow() giving error in Python for image | 38,947,627 | <pre><code>import cv2
import numpy as np
img=cv2.imread("drop.jpg",cv2.IMREAD_GRAYSCALE)
cv2.imshow("blue", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p>The <code>imshow</code> function is giving error, the rest of the code is working fine.</p>
<p>Error message:</p>
<blockquote>
<p>OpenCV Error: Assertion failed (size.width>0 && size.height>0) in
cv::imshow, file
D:\Build\OpenCV\opencv-3.1.0\modules\highgui\src\window.cpp, line 289
Traceback (most recent call last): File "C:\Users\D\Desktop\new
2.py", line 6, in
cv2.imshow("image",img) cv2.error: D:\Build\OpenCV\opencv-3.1.0\modules\highgui\src\window.cpp:289:
error: (-215) size.width>0 && size.height>0 in function cv::imshow</p>
</blockquote>
| 0 | 2016-08-14T23:47:14Z | 39,305,527 | <p><code>cv2.imread()</code> couldn't locate your image file i.e drop.jpg</p>
| 1 | 2016-09-03T09:47:36Z | [
"python",
"opencv"
] |
Avoid Nesting If Statements? (Python 2.7) | 38,947,628 | <p>I got the idea for this guessing game from a book, Invent With Python. I didn't like that the original script didn't cover the possibilities of re-guessing a number or incorrectly using a number not in 1 - 20, so I modified it. The program works great, however, I'm just wrapping my head around if/elif/else code blocks. </p>
<p>I'd like to rewrite the script without having to nest and if inside of an if. I can't even begin to wrap my head around how to do that. Can anyone please help me--just one example of how this program could work without nesting would be great!</p>
<p>Here's the little script in its entirety:</p>
<pre><code>from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
try:
guess = int(raw_input("Take a guess: "))
if guess >= 1 and guess <= 20 and guess not in already_guessed:
already_guessed.append(guess)
guesses_left -= 1
if guess == secret_number:
print "You win! %d was my secret number!" % secret_number
exit(0)
elif guess < secret_number:
print "Your guess is too low!"
elif guess > secret_number:
print "Your guess is too high!"
elif guess in already_guessed:
print "You already guessed that!"
else:
print "Not a number between 1 - 20!"
print "Please try again!"
print "You have %d guesses left!" % guesses_left
except ValueError:
print "Invalid input! Please try again!"
</code></pre>
| 1 | 2016-08-14T23:47:15Z | 38,947,762 | <p>Just change the nested if statements to elif like so:</p>
<pre><code>from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
try:
guess = int(raw_input("Take a guess: "))
if guess <= 1 and guess >= 20 and guess not in already_guessed:
already_guessed.append(guess)
guesses_left -= 1
elif guess == secret_number:
print "You win! %d was my secret number!" % secret_number
exit(0)
elif guess < secret_number:
print "Your guess is too low!"
elif guess > secret_number:
print "Your guess is too high!"
elif guess in already_guessed:
print "You already guessed that!"
else:
print "Not a number between 1 - 20!"
print "Please try again!"
print "You have %d guesses left!" % guesses_left
except ValueError:
print "Invalid input! Please try again!"
</code></pre>
<p>This would be simplest way i see to solve your dilema</p>
| 1 | 2016-08-15T00:11:15Z | [
"python",
"nested"
] |
Avoid Nesting If Statements? (Python 2.7) | 38,947,628 | <p>I got the idea for this guessing game from a book, Invent With Python. I didn't like that the original script didn't cover the possibilities of re-guessing a number or incorrectly using a number not in 1 - 20, so I modified it. The program works great, however, I'm just wrapping my head around if/elif/else code blocks. </p>
<p>I'd like to rewrite the script without having to nest and if inside of an if. I can't even begin to wrap my head around how to do that. Can anyone please help me--just one example of how this program could work without nesting would be great!</p>
<p>Here's the little script in its entirety:</p>
<pre><code>from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
try:
guess = int(raw_input("Take a guess: "))
if guess >= 1 and guess <= 20 and guess not in already_guessed:
already_guessed.append(guess)
guesses_left -= 1
if guess == secret_number:
print "You win! %d was my secret number!" % secret_number
exit(0)
elif guess < secret_number:
print "Your guess is too low!"
elif guess > secret_number:
print "Your guess is too high!"
elif guess in already_guessed:
print "You already guessed that!"
else:
print "Not a number between 1 - 20!"
print "Please try again!"
print "You have %d guesses left!" % guesses_left
except ValueError:
print "Invalid input! Please try again!"
</code></pre>
| 1 | 2016-08-14T23:47:15Z | 38,947,941 | <p>Try it like this, using <code>continue</code> to exit the current iteration of the loop and start again at the top of the loop. </p>
<p>You also had a logic bug here:</p>
<pre><code>if guess <= 1 and guess >= 20 and guess not in already_guessed:
</code></pre>
<p>A number cannot possibly be both less than or equal to 1, and greater than or equal to 20. Your <code>and</code> should have been an <code>or</code> like this:</p>
<pre><code>if (guess <= 1 or guess >= 20) and guess not in already_guessed:
</code></pre>
<p>Or simpler:</p>
<pre><code>if 1 <= guess <= 20 and guess not in already_guessed:
</code></pre>
<p>Also, keep your <code>try/except</code> only around the things that can actually raise an exception (or shouldn't happen if an exception occurs:</p>
<pre><code>from random import randint
import sys
name = raw_input("Hello! What's your name? ")
print "Well {}, I'm thinking of a number between 1 and 20.".format(name)
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
print "You have {} guesses left!".format(guesses_left)
try:
guess = int(raw_input("Take a guess: "))
except ValueError:
print "Invalid input! Please try again!\n"
continue
# If the number is not between 1 and 20...
if not (1 <= guess <= 20):
print "Not a number between 1 - 20!"
print "Please try again!\n"
continue
if guess in already_guessed:
print "You already guessed that!\n"
continue
guesses_left -= 1
already_guessed.append(guess)
if guess == secret_number:
print "You win! {} was my secret number!".format(secret_number)
sys.exit(0)
elif guess < secret_number:
print "Your guess is too low!\n"
elif guess > secret_number:
print "Your guess is too high!\n"
</code></pre>
<p>Here's an example run:</p>
<pre><code>Hello! What's your name? :)
Well :), I'm thinking of a number between 1 and 20.
Since I'm a benevolent computer program, I'll give you 6 guesses.
You have 6 guesses left!
Take a guess: 2
Your guess is too low!
You have 5 guesses left!
Take a guess: 2
You already guessed that!
You have 5 guesses left!
Take a guess: 3
Your guess is too low!
You have 4 guesses left!
Take a guess: 7
Your guess is too high!
You have 3 guesses left!
Take a guess: 5
Your guess is too high!
You have 2 guesses left!
Take a guess: 4
You win! 4 was my secret number!
</code></pre>
| 4 | 2016-08-15T00:43:42Z | [
"python",
"nested"
] |
Get the Key and Value of a dictionary while using random | 38,947,650 | <p>I'm new to python and I'm trying to make a simple "Game"
I'm trying to get the health of the monsters but only the names come up.
I can do <code>(random.choice(list(Monster.health.keys())))</code> and <code>(random.choice(list(Monster.health.Values())))</code> to store both the name and health in a variable but I'm using <code>random</code> so the name might say 'goblin' but the health may say '50' which is wrong.</p>
<p>How can I store the variable in <code>random_mon_name_health</code> and access both 'keys' and 'value'</p>
<pre><code>class Monster:
health = {'goblin': 15, 'giant': 50}
class EncounterM(Monster):
random_mon_name_health = ''
def basic_monster(self):
import random
self.random_mon_name_health = (random.choice(list(Monster.health.keys())))
def test(self):
print(self.random_mon_name_health)
beta_user = EncounterM()
beta_user.basic_monster()
beta_user.test()
# This is only a section of the game that I'm having trouble with
</code></pre>
| 0 | 2016-08-14T23:51:31Z | 38,947,881 | <p>You only need to call <code>choice</code> once, like so:</p>
<pre><code>class Monster:
health = {'goblin': 15, 'giant': 50}
class EncounterM(Monster):
def __init__(self):
self.random_mon_name = ''
self.random_mon_health = 0
def basic_monster(self):
import random
self.random_mon_name, self.random_mon_health = \
random.choice(list(Monster.health.items()))
def test(self):
print(self.random_mon_name, self.random_mon_health)
beta_user = EncounterM()
beta_user.basic_monster()
beta_user.test()
</code></pre>
| 0 | 2016-08-15T00:34:04Z | [
"python",
"dictionary",
"random"
] |
Get the Key and Value of a dictionary while using random | 38,947,650 | <p>I'm new to python and I'm trying to make a simple "Game"
I'm trying to get the health of the monsters but only the names come up.
I can do <code>(random.choice(list(Monster.health.keys())))</code> and <code>(random.choice(list(Monster.health.Values())))</code> to store both the name and health in a variable but I'm using <code>random</code> so the name might say 'goblin' but the health may say '50' which is wrong.</p>
<p>How can I store the variable in <code>random_mon_name_health</code> and access both 'keys' and 'value'</p>
<pre><code>class Monster:
health = {'goblin': 15, 'giant': 50}
class EncounterM(Monster):
random_mon_name_health = ''
def basic_monster(self):
import random
self.random_mon_name_health = (random.choice(list(Monster.health.keys())))
def test(self):
print(self.random_mon_name_health)
beta_user = EncounterM()
beta_user.basic_monster()
beta_user.test()
# This is only a section of the game that I'm having trouble with
</code></pre>
| 0 | 2016-08-14T23:51:31Z | 38,947,886 | <p>If you want to store both key an value at <code>self.random_mon_name_health</code> you can change your method to something like that and it will return a tuple with the monster name and its associated health.</p>
<pre><code>def basic_monster(self):
import random
random_key = (random.choice(list(Monster.health.keys())))
self.random_mon_name_health = random_key, Monster.health[random_key]
</code></pre>
| 0 | 2016-08-15T00:35:09Z | [
"python",
"dictionary",
"random"
] |
TypeError when writing to .txt file Python | 38,947,656 | <p>I'm taking data from a website, and writing it to a .txt file. </p>
<pre><code>head = 'mpg123 -q '
tail = ' &'
url = 'http://www.ndtv.com/article/list/top-stories/'
r = requests.get(url)
soup = BeautifulSoup(r.content)
g_data = soup.find_all("div",{"class":"nstory_intro"})
log = open("/home/pi/logs/newslog.txt","w")
soup = BeautifulSoup(g_data)
# Will grab data from website, and write it to .txt file
for item in g_data:
shorts = textwrap.wrap(item.text, 100)
text_file = open("Output.txt", "w")
text_file.write("%s" % g_data)
print 'Wrote Data Locally On Pi'
text_file.close()
for sentance in shorts:
print 'End.'
# text_file = open("Output.txt", "w")
# text_file.close()
</code></pre>
<p>I know the website pulls the correct information, however, when I run it in the console, I keep getting this error:</p>
<pre><code>TypeError: 'ResultSet' does not have the buffer interface
</code></pre>
<p>I tried looking around on Google, and I'm seeing this a lot for strings in a <code>TypeError: 'str' does not have the buffer interface</code> between Python 2.x and Python 3.x. I tried implementing some of those solutions within the code, but It still keep getting the <code>'ResultSet'</code> error. </p>
| 0 | 2016-08-14T23:53:07Z | 38,948,521 | <p><code>ResultSet</code> is type of your <code>g_data</code>:</p>
<pre><code>In [8]: g_data = soup.find_all('div',{'class':'nstory_intro'})
In [9]: type(g_data)
Out[9]: bs4.element.ResultSet
</code></pre>
<p>With your write code, DON'T use <code>open</code> then <code>close</code>. Use <a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow">context manager</a> to handle the open and close automatically.</p>
<p>If you just want to write text content of <code>g_data</code> to <code>Output.txt</code>, you should do this:</p>
<pre><code>with open('Output.txt', 'w') as f:
for item in g_data:
f.write(item.text + '\n')
</code></pre>
| 0 | 2016-08-15T02:25:47Z | [
"python",
"text-files",
"typeerror"
] |
TensorFlow saving into/loading a graph from a file | 38,947,658 | <p>From what I've gathered so far, there are several different ways of dumping a TensorFlow graph into a file and then loading it into another program, but I haven't been able to find clear examples/information on how they work. What I already know is this:</p>
<ol>
<li>Save the model's variables into a checkpoint file (.ckpt) using a <code>tf.train.Saver()</code> and restore them later (<a href="https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html" rel="nofollow">source</a>)</li>
<li>Save a model into a .pb file and load it back in using <code>tf.train.write_graph()</code> and <code>tf.import_graph_def()</code> (<a href="https://github.com/tensorflow/tensorflow/issues/616" rel="nofollow">source</a>)</li>
<li>Load in a model from a .pb file, retrain it, and dump it into a new .pb file using Bazel (<a href="https://petewarden.com/2016/02/28/tensorflow-for-poets/" rel="nofollow">source</a>)</li>
<li>Freeze the graph to save the graph and weights together (<a href="https://www.tensorflow.org/versions/r0.9/how_tos/tool_developers/index.html#freezing" rel="nofollow">source</a>)</li>
<li>Use <code>as_graph_def()</code> to save the model, and for weights/variables, map them into constants (<a href="http://stackoverflow.com/questions/34343259/is-there-an-example-on-how-to-generate-protobuf-files-holding-trained-tensorflow">source</a>)</li>
</ol>
<p>However, I haven't been able to clear up several questions regarding these different methods:</p>
<ol>
<li>Regarding checkpoint files, do they only save the trained weights of a model? Could checkpoint files be loaded into a new program, and be used to run the model, or do they simply serve as ways to save the weights in a model at a certain time/stage?</li>
<li>Regarding <code>tf.train.write_graph()</code>, are the weights/variables saved as well?</li>
<li>Regarding Bazel, can it only save into/load from .pb files for retraining? Is there a simple Bazel command just to dump a graph into a .pb?</li>
<li>Regarding freezing, can a frozen graph be loaded in using <code>tf.import_graph_def()</code>?</li>
<li>The Android demo for TensorFlow loads in Google's Inception model from a .pb file. If I wanted to substitute my own .pb file, how would I go about doing that? Would I need to change any native code/methods?</li>
<li>In general, what exactly is the difference between all these methods? Or more broadly, what is the difference between <code>as_graph_def()</code>/.ckpt/.pb?</li>
</ol>
<p>In short, what I'm looking for is a method to save both a graph (as in, the various operations and such) and its weights/variables into a file, which can then be used to load the graph and weights into another program, for use (not necessarily continuing/retraining).</p>
<p>Documentation about this topic isn't very straightforward, so any answers/information would be greatly appreciated.</p>
| 2 | 2016-08-14T23:53:27Z | 38,950,073 | <p>There are many ways to approach the problem of saving a model in TensorFlow, which can make it a bit confusing. The <a class='doc-link' href="http://stackoverflow.com/documentation/tensorflow/5000/saving-and-restoring-a-model-in-tensorflow#t=201608150606555812336">documentation on this topic</a> is taking shape, but doesn't cover all of the details in your question. Taking each of your sub-questions in turn:</p>
<ol>
<li><p>The checkpoint files (produced e.g. by calling <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Saver.save" rel="nofollow"><code>saver.save()</code></a> on a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Saver" rel="nofollow"><code>tf.train.Saver</code></a> object) contain only the weights, and any other variables defined in the same program. To use them in another program, you must re-create the associated graph structure (e.g. by running code to build it again, or calling <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#import_graph_def" rel="nofollow"><code>tf.import_graph_def()</code></a>), which tells TensorFlow what to do with those weights. Note that calling <code>saver.save()</code> also produces a file containing a <a href="https://www.tensorflow.org/versions/r0.10/how_tos/meta_graph/index.html" rel="nofollow"><code>MetaGraphDef</code></a>, which contains a graph and details of how to associate the weights from a checkpoint with that graph. See <a href="https://www.tensorflow.org/versions/r0.10/how_tos/meta_graph/index.html" rel="nofollow">the tutorial</a> for more details.</p></li>
<li><p><a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#write_graph" rel="nofollow"><code>tf.train.write_graph()</code></a> only writes the graph structure; not the weights.</p></li>
<li><p>Bazel is unrelated to reading or writing TensorFlow graphs. (Perhaps I misunderstand your question: feel free to clarify it in a comment.)</p></li>
<li><p>A frozen graph can be loaded using <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#import_graph_def" rel="nofollow"><code>tf.import_graph_def()</code></a>. In this case, the weights are (typically) embedded in the graph, so you don't need to load a separate checkpoint.</p></li>
<li><p>The main change would be to the names of the tensor(s) that are fed into the model, and the names of the tensor(s) that are fetched from the model. In the TensorFlow Android demo, this would correspond to the <code>inputName</code> and <code>outputName</code> strings that are passed to <a href="https://github.com/tensorflow/tensorflow/blob/d67ce6c449fabb3bebccd85815d9d291f114e6e4/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowClassifier.java#L34" rel="nofollow"><code>TensorFlowClassifier.initializeTensorFlow()</code></a>.</p></li>
<li><p>The <code>GraphDef</code> is the program structure, which typically does not change through the training process. The checkpoint is a snapshot of the state of a training process, which typically changes at every step of the training process. As a result, TensorFlow uses different storage formats for these types of data, and the low-level API provides different ways to save and load them. Higher-level libraries, such as the <a href="https://www.tensorflow.org/versions/r0.10/how_tos/meta_graph/index.html" rel="nofollow"><code>MetaGraphDef</code></a> libraries, <a href="https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model" rel="nofollow">Keras</a>, and <a href="https://github.com/tensorflow/skflow#saving--restoring-models" rel="nofollow">skflow</a> build on these mechanisms to provide more convenient ways to save and restore an entire model.</p></li>
</ol>
| 4 | 2016-08-15T06:07:47Z | [
"python",
"tensorflow",
"protocol-buffers"
] |
python reduce: find total size of all lists inside list of tuples | 38,947,667 | <p>my data structure looks as below</p>
<pre><code>itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
</code></pre>
<p>I want to find total number of items in the list of tuples above. For above example, len([1,2,3,4] + len([1,2]) + len([1,2,3]) = 9 </p>
<pre><code>reduce(lambda x,y: len(x[1]) + len(y[1]), itemsData )
</code></pre>
<p>error i get is </p>
<pre><code>TypeError: 'int' object has no attribute '__getitem__'
</code></pre>
| 2 | 2016-08-14T23:55:16Z | 38,947,696 | <p>You could simply try:</p>
<pre><code>sum([len(elem[1]) for elem in itemsData])
</code></pre>
<p>E.g.</p>
<pre><code>>>> itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
>>> sum([len(elem[1]) for elem in itemsData])
9
</code></pre>
| 4 | 2016-08-14T23:58:57Z | [
"python",
"lambda",
"reduce"
] |
python reduce: find total size of all lists inside list of tuples | 38,947,667 | <p>my data structure looks as below</p>
<pre><code>itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
</code></pre>
<p>I want to find total number of items in the list of tuples above. For above example, len([1,2,3,4] + len([1,2]) + len([1,2,3]) = 9 </p>
<pre><code>reduce(lambda x,y: len(x[1]) + len(y[1]), itemsData )
</code></pre>
<p>error i get is </p>
<pre><code>TypeError: 'int' object has no attribute '__getitem__'
</code></pre>
| 2 | 2016-08-14T23:55:16Z | 38,947,745 | <p>I will explain why your code does not work</p>
<p>from <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow">https://docs.python.org/2/library/functions.html#reduce</a>,</p>
<blockquote>
<p>The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable</p>
</blockquote>
<p>So in the first iteration, your code
<code>len(x[1]) + len(y[1])</code> works since <code>x=('data1', [1, 2, 3, 4])</code>, <code>y=('data2', [1, 2])</code>, and the result is <code>6</code>,</p>
<p>However in the second iteration, you get <code>x=6</code>, <code>y=('data3', [1, 2, 3])]</code>,
so <code>len(x[1])</code> is invalid.</p>
<p>The correct code using reduce, is</p>
<pre><code>reduce(lambda x,y: x+len(y[1]), itemsData, 0)
</code></pre>
<p>This works since</p>
<pre><code>1st iteration ... x = 0, y = ('data1', [1, 2, 3, 4]), result = 4
2nd iteration ... x = 4, y = ('data2', [1, 2]), result = 6
3rd iteration ... x = 6, y = ('data3', [1, 2, 3]), result = 9
</code></pre>
| 4 | 2016-08-15T00:08:16Z | [
"python",
"lambda",
"reduce"
] |
How to reassign object to a variable in python? | 38,947,715 | <p>If I assign a variable (in this case b) to a button and put it on screen with pack(), then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? I guess the question could be asked about any data type or object, but this is case stands out because the button is left on the screen. Example:</p>
<pre><code>import tkinter as tk
root=tk.Tk()
root.geometry('300x300')
b=tk.Button(root, text="button b")
b.pack()
b=1
root.mainloop()
</code></pre>
| 0 | 2016-08-15T00:02:34Z | 38,947,748 | <p>Save a reference somewhere with another assignment.</p>
<pre><code>b = tk.Button(root, text="button b")
saved = b
b = 1
saved.pack()
</code></pre>
| 1 | 2016-08-15T00:08:51Z | [
"python",
"tkinter"
] |
How to reassign object to a variable in python? | 38,947,715 | <p>If I assign a variable (in this case b) to a button and put it on screen with pack(), then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? I guess the question could be asked about any data type or object, but this is case stands out because the button is left on the screen. Example:</p>
<pre><code>import tkinter as tk
root=tk.Tk()
root.geometry('300x300')
b=tk.Button(root, text="button b")
b.pack()
b=1
root.mainloop()
</code></pre>
| 0 | 2016-08-15T00:02:34Z | 38,947,749 | <blockquote>
<p>... then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? </p>
</blockquote>
<p>Short answer: you can't. In order to refer to something you must keep a reference. That being said,tkinter provides some alternatives.</p>
<p>If you're wanting to refer to the button in the callback, you can pass it in. This requires creating the button and then defining the callback in a separate step:</p>
<pre><code>b = tk.Button(...)
b.configure(command=lambda button=b: do_something)
...
def do_something(button):
print("the widget is:", button)
</code></pre>
<p>Also, if you're using bindings, when the bound function is called it will be passed an event object that has an attribute that contains a reference to the widget.</p>
<pre><code>b.bind("<1>", do_something)
...
def do_something(event):
print("the widget is:", event.widget)
</code></pre>
<p>Finally, you can ask tkinter for a list of child widgets (eg: <code>root.winfo_children</code>), and if you know whether you've used <code>pack</code>, <code>place</code> or <code>grid</code>, you can use the <code>slaves</code> method to query all of the widgets being managed inside a particular container (eg: <code>root.grid_slaves()</code>, <code>root.pack_slaves()</code>, <code>root.place_slaves()</code>)</p>
| 1 | 2016-08-15T00:08:54Z | [
"python",
"tkinter"
] |
How to reassign object to a variable in python? | 38,947,715 | <p>If I assign a variable (in this case b) to a button and put it on screen with pack(), then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? I guess the question could be asked about any data type or object, but this is case stands out because the button is left on the screen. Example:</p>
<pre><code>import tkinter as tk
root=tk.Tk()
root.geometry('300x300')
b=tk.Button(root, text="button b")
b.pack()
b=1
root.mainloop()
</code></pre>
| 0 | 2016-08-15T00:02:34Z | 38,947,937 | <p>You can access all widgets of the root window with the method:</p>
<pre><code>list_of_widgets = root.pack_slaves()
</code></pre>
<p>and then check for the type of the object. ( Which is not a good practice ... )
Thus, i would recommend you to save the required references in a separeate object, for clearly seperating the interface to tkinter from your application. From then on, you should only access the widgets through your interface object. This creates much cleaner code. </p>
| 1 | 2016-08-15T00:43:26Z | [
"python",
"tkinter"
] |
wxPython, using a field from an imported class | 38,947,725 | <p>First important to state that I am an amateur programmer.</p>
<p>Building a personal software in python/wxPython connected to a MySQL DB</p>
<p>My problem:</p>
<p>trying to write one form that will access classes from an imported file.
The form accesses at any one time 4 related tables on the database.</p>
<p>Three(3) of these tables are always the same. The fourth can be one of two tables.</p>
<p>The tables that are always accessed : session, cardio and notes
The tables that can vary are: physical or machine</p>
<p>I have placed the data fields in wx.Panel classes for each of the tables mentioned above. The mainForm's menu calls the input form with a reference to either the physical or the machine parameter. The appropriate form is displayed with its data fields.</p>
<p>My problem is I can't access these imported fields to load data from the database.</p>
<p>Sections of my code:</p>
<p>Mainform: dailyResultsV2.py</p>
<pre><code>import inputForm as IF
# Menu Event:
</code></pre>
<p>def OnShowBikeRecs(self, event):</p>
<pre><code>self.bikeedit = IF.inputForm(None, -1, "Bike Record Management", size=(925,650), name="bike")
self.bikeedit.Show()
self.bikeedit.Center()
</code></pre>
<p>Called Form: inputForm.py</p>
<pre><code>class inputForm(wx.Frame):
def __init__(self, parent, *args, **kwargs):
wx.Frame.__init__(self, parent, *args, **kwargs)
self.EXERCISE = kwargs['name']
# create a panel
self.panel = wx.Panel(self)
self.panel.BackgroundColour = (200, 230, 250)
self.filterSetup()
self.sessionSection = IFC.tblSession(self.panel,-1)
self.sessionSection.BackgroundColour = (200, 230, 250)
if self.EXERCISE == 'walk':
self.physicalSection = IFC.tblPhysical(self.panel,-1)
else:
self.machineSection = IFC.tblMachine(self.panel,-1)
self.cardioSection = IFC.tblcardio(self.panel,-1)
self.notesSection = IFC.tblNotes(self.panel,-1)
self.buttonSetup()
self.topsizer()
</code></pre>
<p>The preceding class creates an input form which will include all the fields from the physical table or the machine table.</p>
<p>My problem how to I access these fields to add data from the database or update the database. (One side note this is a physical training database). </p>
<p>example of the imported classes: inputFormClasses.py</p>
<pre><code>class tblMachine(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.BackgroundColour = (200, 230, 250)
# The columns
# machine_ID - not displayed machine_session_FK - not displayed machine_level - not displayed
# machine_Type_FK machine_Distance machine_AvgSpeed machine_MaxSpeed machine_Duration machine_ODO machine_RunFK - ComboBox
self.runNames = [] # ComboBox List
self.machineLabel_st = wx.StaticText(self, -1, "Machine", style=wx.ALIGN_LEFT)
self.machineType_st = wx.StaticText(self, -1, "Type", style=wx.ALIGN_LEFT)
self.machineType_tc = wx.TextCtrl(self, -1, value="Biking", style=wx.TE_CENTRE)
self.machineDistance_st = wx.StaticText(self, -1, "Distance", style=wx.ALIGN_LEFT)
self.machineDistance_tc = wx.TextCtrl(self, -1, style=wx.TE_CENTRE)
self.machineAvgSpeed_st = wx.StaticText(self, -1, "Avg. Speed", style=wx.ALIGN_LEFT)
self.machineAvgSpeed_tc = wx.TextCtrl(self, -1, style=wx.TE_CENTRE)
self.machineMaxSpeed_st = wx.StaticText(self, -1, "Max Speed", style=wx.ALIGN_LEFT)
self.machineMaxSpeed_tc = wx.TextCtrl(self, -1, style=wx.TE_CENTRE)
self.machineDuration_st = wx.StaticText(self, -1, "Duration", style=wx.ALIGN_LEFT)
self.machineDuration_mtc = masked.TimeCtrl(self, -1, fmt24hr=True)
self.machineODO_st = wx.StaticText(self, -1, "Odometer", style=wx.ALIGN_LEFT)
self.machineODO_tc = wx.TextCtrl(self, -1, style=wx.TE_CENTRE)
self.machineRun_st = wx.StaticText(self, -1, "Run", style=wx.ALIGN_LEFT)
self.machineRun_cbo = wx.ComboBox(self, -1, choices = self.getRunNames(self.runNames), style=wx.CB_READONLY) # get the list of runs for comboBox
# create machine sizer
self.MachineSizer = wx.GridBagSizer(hgap=5, vgap=5)
</code></pre>
<p>How to I access for example: self.machineType_tc on my form ?</p>
| 0 | 2016-08-15T00:04:13Z | 38,948,164 | <p>Check out sqlite3 library: I used it to do something similar:</p>
<pre><code>import sqlite3
def insert_user(cursor,username,password,port,steps,lat,long):
try:
cursor.execute("INSERT INTO mydb VALUES(?,?,?,?,?,?)", (username,password,port,steps,lat,long))
return "Success"
except Exception as e:
print e
return "Failure"
</code></pre>
<p>I hope this helps.</p>
| 0 | 2016-08-15T01:27:34Z | [
"python",
"wxpython"
] |
Re-initialize variables in Tensorflow | 38,947,754 | <p>I am using a Tensorflow <code>tf.Saver</code> to load a pre-trained model and I want to re-train a few of its layers by erasing (re-initializing to random) their appropriate weights and biases, then training those layers and saving the trained model. I can not find a method that re-initializes the variables. I tried <code>tf.initialize_variables(fine_tune_vars)</code> but it did not work (I'd assume because the variables are already initialized), I have also seen that you can pass variables to the <code>tf.Saver</code> so that you partially load the model, however that is half of what I want to achieve (because when I save the trained model, I want it to save all variables not only the ones I loaded).</p>
<p>Thank you in advance!</p>
| 0 | 2016-08-15T00:09:35Z | 38,949,245 | <p><code>initialize_all_variables</code> should work to re-initialize previously initialized var.</p>
<p>Just did this sanity check in 0.10</p>
<pre><code>tf.reset_default_graph()
a = tf.Variable(tf.ones_initializer(()))
init_op = tf.initialize_all_variables()
modify_op = a.assign(5.0)
sess = tf.InteractiveSession()
sess.run(init_op)
print(a.eval())
sess.run(modify_op)
print(a.eval())
sess.run(init_op)
print(a.eval())
</code></pre>
<p>Result</p>
<pre><code>1.0
5.0
1.0
</code></pre>
| 1 | 2016-08-15T04:15:04Z | [
"python",
"machine-learning",
"computer-vision",
"neural-network",
"tensorflow"
] |
Code works but does not work the correct way-python | 38,947,809 | <p>I am trying to create this modified version of road trip in python 3.4.3 and it is not working like I want. The problem is that when the player selects anything but a "y" when taking a hit for getting stuck, it assumes the player wants to take a chance when he/she doesn't. I have tried use the else statement and I tried the not in front of it. You will see that in my code. This same thing occurs for choosing a prize or to continue. I know it has to be the same error. This is just the first round so I will be adding more to it but I need to get this solved before I can continue. Thanks in advance.</p>
<pre><code>import random
import time
import math
print("Welcome to ATV Road Trip!!!")
time.sleep(2)
stuck=0
print("Good luck because your gonna need it...")
time.sleep(2)
first_round=0
second_round=0
third_round=0
while True:
print("You need 250 miles to complete the first round")
time.sleep(2)
first_number_1=random.choice([100,200,300])
second_number_1=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_1=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_1=first_number_1+second_number_1+third_number_1
first_roll_1=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_1,mystery_1,mystery_1])
if first_roll_1==mystery_1:
print("Mystery miles!!!")
time.sleep(2)
print("You got a mile of:",first_roll_1)
first_round=first_round+first_roll_1
time.sleep(2)
print("Your total miles so far in this round is:", first_round)
time.sleep(3)
first_number_2=random.choice([100,200,300])
second_number_2=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_2=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_2=first_number_2+second_number_2+third_number_2
first_roll_2=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_2,mystery_2,mystery_2])
print("Rolling again...")
time.sleep(2)
if first_roll_2==mystery_2:
print("Mystery!!!")
time.sleep(2)
print("You got a mile of:", first_roll_2)
first_round=first_round+first_roll_2
time.sleep(2)
print("Your total miles so far in this round is:", first_round)
time.sleep(3)
first_number_3=random.choice([100,200,300])
second_number_3=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_3=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_3=first_number_3+second_number_3+third_number_3
first_roll_3=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_3,mystery_3,mystery_3])
print("Rolling again...")
time.sleep(2)
if first_roll_3==mystery_3:
print("Mystery!!!")
time.sleep(2)
print("You got a mile of:", first_roll_3)
first_round=first_round+first_roll_3
time.sleep(2)
print("You got a total milage of:", first_round)
time.sleep(3)
print("Congratulations on your total milage, but you might get stuck!")
time.sleep(4)
print("Lets find out! You have a 50/50 shot of getting stuck!")
time.sleep(3)
print("""If you get stuck, you can choose to take the lose of 50 miles or
you can take a chance on another 50/50. If you win that, you get 50 miles added
to your total milage for this round and no points off. However, if you lose, then
you get 100 miles off! If you do not get stuck, nothing happens to your score.""")
time.sleep(10)
chance_1=random.randint(1,2)
if chance_1==1:
print("Congratulations on not getting stuck!!!")
time.sleep(3)
if chance_1==2:
print("Sorry, you got stuck!!!")
stuck=stuck+1
print("It happens, sorry buddy.")
time.sleep(4)
lose_choice_1=input("Press y to take a chance of getting out and added score or n for taking the hit:")
if lose_choice_1=='y' or 'Y':
chance_taken_1=random.randint(1,2)
if chance_taken_1==1:
print("Congratulations on getting unstuck early!")
print("You got 50 miles added!!!")
first_round=first_round+50
print("Your milage total is now:", first_round)
time.sleep(5)
if chance_taken_1==2:
print("You got stuck again!")
print("Ouch!!! 100 points off!!!")
first_round=first_round-100
print("Your milage total is now:", first_round)
time.sleep(5)
if not lose_choice_1=='y' or 'Y':
print("You have decided to take the hit!")
time.sleep(2)
first_round=first_round-50
print("Your mileage total is now:", first_round)
time.sleep(3)
if first_round<250:
print("Sorry, you lost!")
time.sleep(3)
break
if first_round>=250:
print("Congratulations!!! You have passed the first round!!!")
print("You can try for round 2 or you can select your prize of a rubber duck.")
time.sleep(3)
prize_pick_round_1=input("Press y to get prize and end game or any other key to continue:")
if prize_pick_round_1=='y' or 'Y':
print("You have chosen the rubber ducky!")
print("I hope your happy with it!")
print("Ending game...")
time.sleep(5)
break
if not prize_pick_round_1=='y' or 'Y':
continue
break
</code></pre>
| -4 | 2016-08-15T00:21:37Z | 38,948,101 | <p>You should be able to fix your issue by changing the second nested if statement to elif like so:</p>
<pre><code>import random
import time
import math
print("Welcome to ATV Road Trip!!!")
time.sleep(1)
stuck=0
print("Good luck because your gonna need it...")
time.sleep(1)
first_round=0
second_round=0
third_round=0
while True:
print("You need 250 miles to complete the first round")
time.sleep(1)
first_number_1=random.choice([100,200,300])
second_number_1=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_1=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_1=first_number_1+second_number_1+third_number_1
first_roll_1=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_1,mystery_1,mystery_1])
if first_roll_1==mystery_1:
print("Mystery miles!!!")
time.sleep(1)
print("You got a mile of:",first_roll_1)
first_round=first_round+first_roll_1
time.sleep(1)
print("Your total miles so far in this round is:", first_round)
time.sleep(1)
first_number_2=random.choice([100,200,300])
second_number_2=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_2=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_2=first_number_2+second_number_2+third_number_2
first_roll_2=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_2,mystery_2,mystery_2])
print("Rolling again...")
time.sleep(1)
if first_roll_2==mystery_2:
print("Mystery!!!")
time.sleep(1)
print("You got a mile of:", first_roll_2)
first_round=first_round+first_roll_2
time.sleep(1)
print("Your total miles so far in this round is:", first_round)
time.sleep(1)
first_number_3=random.choice([100,200,300])
second_number_3=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_3=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_3=first_number_3+second_number_3+third_number_3
first_roll_3=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_3,mystery_3,mystery_3])
print("Rolling again...")
time.sleep(1)
if first_roll_3==mystery_3:
print("Mystery!!!")
time.sleep(1)
print("You got a mile of:", first_roll_3)
first_round=first_round+first_roll_3
time.sleep(1)
print("You got a total milage of:", first_round)
time.sleep(1)
print("Congratulations on your total milage, but you might get stuck!")
time.sleep(4)
print("Lets find out! You have a 50/50 shot of getting stuck!")
time.sleep(1)
print("""If you get stuck, you can choose to take the lose of 50 miles or you can take a chance on another 50/50. If you win that, you get 50 miles added to your total milage for this round and no points off. However, if you lose, then you get 100 miles off! If you do not get stuck, nothing happens to your score.""")
time.sleep(10)
chance_1=random.randint(1,2)
if chance_1 == 1:
print("Congratulations on not getting stuck!!!")
time.sleep(1)
if chance_1 == 2:
print("Sorry, you got stuck!!!")
stuck=stuck+1
print("It happens, sorry buddy.")
time.sleep(4)
lose_choice_1=raw_input("Press y to take a chance of getting out and added score or n for taking the hit:")
if lose_choice_1 == 'y' or 'Y':
chance_taken_1=random.randint(1,2)
if chance_taken_1 == 1:
print("Congratulations on getting unstuck early!")
print("You got 50 miles added!!!")
first_round=first_round+50
print("Your milage total is now:", first_round)
time.sleep(5)
else:
print("You got stuck again!")
print("Ouch!!! 100 points off!!!")
first_round=first_round-100
print("Your milage total is now:", first_round)
time.sleep(5)
if lose_choice_1 != 'y' or 'Y':
print("You have decided to take the hit!")
time.sleep(1)
first_round=first_round-50
print("Your mileage total is now:", first_round)
time.sleep(1)
if first_round < 250:
print("Sorry, you lost!")
time.sleep(1)
break
if first_round >= 250:
print("Congratulations!!! You have passed the first round!!!")
print("You can try for round 2 or you can select your prize of a rubber duck.")
time.sleep(1)
prize_pick_round_1=raw_input("Press y to get prize and end game or any other key to continue:")
if prize_pick_round_1 == 'y' or 'Y':
print("You have chosen the rubber ducky!")
print("I hope your happy with it!")
print("Ending game...")
time.sleep(5)
break
if prize_pick_round_1 != 'y' or 'Y':
continue
break
</code></pre>
<p>Look up examples of if, elif, else statements.
When possible you should try to get rid of as many nested if statements as possible.</p>
<p>Example:</p>
<pre><code>if chance_taken1 == 2:
return value
elif chance_taken1 == 1
return other value
else:
print "invalid input"
return
</code></pre>
| 0 | 2016-08-15T01:13:14Z | [
"python"
] |
Code works but does not work the correct way-python | 38,947,809 | <p>I am trying to create this modified version of road trip in python 3.4.3 and it is not working like I want. The problem is that when the player selects anything but a "y" when taking a hit for getting stuck, it assumes the player wants to take a chance when he/she doesn't. I have tried use the else statement and I tried the not in front of it. You will see that in my code. This same thing occurs for choosing a prize or to continue. I know it has to be the same error. This is just the first round so I will be adding more to it but I need to get this solved before I can continue. Thanks in advance.</p>
<pre><code>import random
import time
import math
print("Welcome to ATV Road Trip!!!")
time.sleep(2)
stuck=0
print("Good luck because your gonna need it...")
time.sleep(2)
first_round=0
second_round=0
third_round=0
while True:
print("You need 250 miles to complete the first round")
time.sleep(2)
first_number_1=random.choice([100,200,300])
second_number_1=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_1=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_1=first_number_1+second_number_1+third_number_1
first_roll_1=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_1,mystery_1,mystery_1])
if first_roll_1==mystery_1:
print("Mystery miles!!!")
time.sleep(2)
print("You got a mile of:",first_roll_1)
first_round=first_round+first_roll_1
time.sleep(2)
print("Your total miles so far in this round is:", first_round)
time.sleep(3)
first_number_2=random.choice([100,200,300])
second_number_2=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_2=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_2=first_number_2+second_number_2+third_number_2
first_roll_2=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_2,mystery_2,mystery_2])
print("Rolling again...")
time.sleep(2)
if first_roll_2==mystery_2:
print("Mystery!!!")
time.sleep(2)
print("You got a mile of:", first_roll_2)
first_round=first_round+first_roll_2
time.sleep(2)
print("Your total miles so far in this round is:", first_round)
time.sleep(3)
first_number_3=random.choice([100,200,300])
second_number_3=random.choice([0,10,20,30,40,50,60,70,80,90])
third_number_3=random.choice([0,1,2,3,4,5,6,7,8,9])
mystery_3=first_number_3+second_number_3+third_number_3
first_roll_3=random.choice([25,25,25,35,35,35,50,50,50,75,75,75,100,100,150,150,200,mystery_3,mystery_3,mystery_3])
print("Rolling again...")
time.sleep(2)
if first_roll_3==mystery_3:
print("Mystery!!!")
time.sleep(2)
print("You got a mile of:", first_roll_3)
first_round=first_round+first_roll_3
time.sleep(2)
print("You got a total milage of:", first_round)
time.sleep(3)
print("Congratulations on your total milage, but you might get stuck!")
time.sleep(4)
print("Lets find out! You have a 50/50 shot of getting stuck!")
time.sleep(3)
print("""If you get stuck, you can choose to take the lose of 50 miles or
you can take a chance on another 50/50. If you win that, you get 50 miles added
to your total milage for this round and no points off. However, if you lose, then
you get 100 miles off! If you do not get stuck, nothing happens to your score.""")
time.sleep(10)
chance_1=random.randint(1,2)
if chance_1==1:
print("Congratulations on not getting stuck!!!")
time.sleep(3)
if chance_1==2:
print("Sorry, you got stuck!!!")
stuck=stuck+1
print("It happens, sorry buddy.")
time.sleep(4)
lose_choice_1=input("Press y to take a chance of getting out and added score or n for taking the hit:")
if lose_choice_1=='y' or 'Y':
chance_taken_1=random.randint(1,2)
if chance_taken_1==1:
print("Congratulations on getting unstuck early!")
print("You got 50 miles added!!!")
first_round=first_round+50
print("Your milage total is now:", first_round)
time.sleep(5)
if chance_taken_1==2:
print("You got stuck again!")
print("Ouch!!! 100 points off!!!")
first_round=first_round-100
print("Your milage total is now:", first_round)
time.sleep(5)
if not lose_choice_1=='y' or 'Y':
print("You have decided to take the hit!")
time.sleep(2)
first_round=first_round-50
print("Your mileage total is now:", first_round)
time.sleep(3)
if first_round<250:
print("Sorry, you lost!")
time.sleep(3)
break
if first_round>=250:
print("Congratulations!!! You have passed the first round!!!")
print("You can try for round 2 or you can select your prize of a rubber duck.")
time.sleep(3)
prize_pick_round_1=input("Press y to get prize and end game or any other key to continue:")
if prize_pick_round_1=='y' or 'Y':
print("You have chosen the rubber ducky!")
print("I hope your happy with it!")
print("Ending game...")
time.sleep(5)
break
if not prize_pick_round_1=='y' or 'Y':
continue
break
</code></pre>
| -4 | 2016-08-15T00:21:37Z | 38,949,985 | <p>Tests like this don't work:</p>
<pre><code>if lose_choice_1 == 'y' or 'Y':
</code></pre>
<p>It's always true. You need to do:</p>
<pre><code>if lose_choice_1 == 'y' or lose_choice_1 == 'Y':
</code></pre>
<p>or you can do:</p>
<pre><code>if lose_choice_1.lower() == 'y':
</code></pre>
<p>Other than that, your code is just messy and redundant (get your space bar fixed.) Here's a rework that might give you some ideas about how to go about writing your game so that you can more easily extend it (I've removed the time.sleep() calls to focus on the logic itself.)</p>
<pre><code>import random
print("Welcome to ATV Road Trip!!!")
print("Good luck because your gonna need it...")
stuck = 0
first_round = second_round = third_round = 0
while True:
print("You need 250 miles to complete the first round")
for roll in range(3):
first_number = random.choice(range(100, 400, 100))
second_number = random.choice(range(0, 100, 10))
third_number = random.choice(range(10))
mystery = first_number + second_number + third_number
first_roll = random.choice([25, 35, 50, 75] * 3 + [100, 150] * 2 + [200, mystery, mystery, mystery])
if roll > 0:
print("Rolling again...")
if first_roll == mystery:
print("Mystery miles!!!")
print("You added a mileage of:", first_roll)
first_round += first_roll
print("Your total miles so far in this round is:", first_round)
print("Congratulations on your total mileage, but you might get stuck!")
print("Lets find out! You have a 50/50 shot of getting stuck!")
print("""If you get stuck, you can choose to take the loss of 50 miles or
you can take a chance on another 50/50. If you win that, you get 50 miles added
to your total mileage for this round and no points off. However, if you lose, then
you get 100 miles off! If you do not get stuck, nothing happens to your score.""")
chance_1 = random.randint(1, 2)
if chance_1 == 1:
print("Congratulations on not getting stuck!!!")
else:
print("Sorry, you got stuck!!!")
print("It happens, sorry buddy.")
stuck += 1
lose_choice_1 = input("Press y to take a chance of getting out and added score or n for taking the hit: ")
if lose_choice_1 == 'y' or lose_choice_1 == 'Y':
chance_taken_1 = random.randint(1, 2)
if chance_taken_1 == 1:
print("Congratulations on getting unstuck early!")
print("You got 50 miles added!!!")
first_round += 50
else:
print("You got stuck again!")
print("Ouch!!! 100 points off!!!")
first_round -= 100
else:
print("You have decided to take the hit!")
first_round -= 50
print("Your mileage total is now:", first_round)
if first_round < 250:
print("Sorry, you lost!")
break
else:
print("Congratulations!!! You have passed the first round!!!")
print("You can try for round 2 or you can select your prize of a rubber duck.")
prize_pick_round_1 = input("Press y to get prize and end game or any other key to continue: ")
if prize_pick_round_1 == 'y' or prize_pick_round_1 == 'Y':
print("You have chosen the rubber ducky!")
print("I hope your happy with it!")
print("Ending game...")
break
</code></pre>
| 0 | 2016-08-15T05:57:18Z | [
"python"
] |
Conditional comprehension in Julia | 38,947,840 | <p>In Python, there is the option to provide a condition for whether or not to include a specific item in a comprehension.</p>
<pre><code>[x**2 for x in range(10) if x > 5]
# [36, 49, 64, 81]
</code></pre>
<p>It is possible to conditionally use function, but I have not yet found a way to entirely exclude values, other than <code>filter!</code>ing them outside of the comprehension.</p>
<pre><code>l = collect(0:9)
filter!(x -> x > 5, l)
l = [x^2 for x in l] # alternatively, map!(x -> x^2, l)
# [36, 49, 64, 81]
</code></pre>
<p>Is this possible in Julia? </p>
| 6 | 2016-08-15T00:27:35Z | 38,947,888 | <p>It is possible in the latest Julia.</p>
<pre><code>julia> [x^2 for x in 0:9 if x > 5]
4-element Array{Int64,1}:
36
49
64
81
</code></pre>
<p>Otherwise, yes, if you're using pre 0.5 you're stuck with:</p>
<pre><code>[x^2 for x in filter((x) -> x > 5, 0:9)]
</code></pre>
| 12 | 2016-08-15T00:35:53Z | [
"python",
"if-statement",
"filter",
"list-comprehension",
"julia-lang"
] |
Sort nested dictionaries then sort outer dictionary | 38,947,841 | <p>I have a dictionary of states and counties:</p>
<pre><code>{
'WI': {'CountyZ': 0,
'CountyC': 0,
'CountyD': 0},
'IL': {'CountyM': 0,
'CountyW': 0,
'CountyA': 0}
}
</code></pre>
<p>I would like to sort the inner dictionaries of counties based on keys and then sort the outer dictionary of states based on the keys as well.</p>
<p>I've tried the following but I'm unable to get the desired result:</p>
<pre><code>sorted(sorted(states.items(), key=lambda x: x[0]), key=lambda y: y[1].items())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>[('IL', [('CountyA', 0), ('CountyM', 0), ('CountyW', 0)]),
('WI', [('CountyC', 0), ('CountyD', 0), ('CountyZ', 0)])]
</code></pre>
| 0 | 2016-08-15T00:27:36Z | 38,947,989 | <p>You can get the sorted list of tuples like so:</p>
<pre><code>d = {
'WI': {'CountyZ': 0,
'CountyC': 0,
'CountyD': 0},
'IL': {'CountyM': 0,
'CountyW': 0,
'CountyA': 0}
}
print sorted((key, sorted(inner_dict.items())) for key, inner_dict in d.iteritems())
</code></pre>
| 1 | 2016-08-15T00:53:21Z | [
"python",
"sorting",
"dictionary"
] |
Copy between arrays by indexing | 38,947,916 | <p>I'd like to copy elements of an array (<code>a</code>) to a result array <code>b</code> according to some rules that define which element from <code>a</code> goes where in <code>b</code>. I created an example below.</p>
<p>Is it possible (by some smart indexing?) to perform the last step (<code>b[x,mask] = a[mask]</code>) in one step for all <code>x</code> or can this only be achieved in a loop as shown (in an expanded way) below? <code>x</code> in my real example is rather large (~100), so I think this could benefit from a removal of the loop.</p>
<pre><code>a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
m1 = a > 6
m2 = ~m1 & ((a < 8) & (a > 4))
m3 = ~m1 & ~m2 & (a > 1)
m4 = ~m1 & ~m2 & ~m3 & (a < 10)
b = np.zeros((4, 3, 3))
b[0, m1] = a[m1]
b[1, m2] = a[m2]
b[2, m3] = a[m3]
b[3, m4] = a[m4]
print '0\n', b[0]
print '1\n', b[1]
print '2\n', b[2]
print '3\n', b[3]
</code></pre>
<p>Output:</p>
<pre><code>0
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 7. 8. 9.]]
1
[[ 0. 0. 0.]
[ 0. 5. 6.]
[ 0. 0. 0.]]
2
[[ 0. 2. 3.]
[ 4. 0. 0.]
[ 0. 0. 0.]]
3
[[ 1. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
</code></pre>
| 1 | 2016-08-15T00:41:03Z | 38,948,792 | <p>I don't know if it improves it or not, but it is possible to do the copy in one step if we construct raveled indexes:</p>
<p>Start with a list of the masks:</p>
<pre><code>In [1934]: m=[m1,m2,m3,m4]
</code></pre>
<p>Make an index list by joining the individual list - adjusted to work with a flat or raveled 1d version of <code>a</code>:</p>
<pre><code>In [1935]: ida=np.concatenate([np.ravel_multi_index(np.nonzero(z),a.shape) for z in m])
In [1936]: ida
Out[1936]: array([6, 7, 8, 4, 5, 1, 2, 3, 0], dtype=int32)
In [1937]: a.flat[ida]
Out[1937]: array([7, 8, 9, 5, 6, 2, 3, 4, 1])
</code></pre>
<p>Construct the same for 3d <code>b</code>, taking into account the different 1st dimension values:</p>
<pre><code>In [1938]: idb = [np.ravel_multi_index(((i,)+np.nonzero(z)),bshape) for i,z in enumerate(m)]
In [1939]: idb
Out[1939]:
[array([6, 7, 8], dtype=int32),
array([13, 14], dtype=int32),
array([19, 20, 21], dtype=int32),
array([27], dtype=int32)]
In [1940]: idb=np.concatenate(idb)
</code></pre>
<p>Now do the copy:</p>
<pre><code>In [1941]: b.flat[id1]=a.flat[ida]
In [1942]: b
Out[1942]:
array([[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 7., 8., 9.]],
[[ 0., 0., 0.],
[ 0., 5., 6.],
...
[ 0., 0., 0.]]])
</code></pre>
<p>So the copy is done in one call, but I had to use two list comprehensions to construct the required indices.</p>
| 0 | 2016-08-15T03:08:16Z | [
"python",
"arrays",
"numpy"
] |
Reshaping numpy array from list | 38,947,926 | <p>I have the following problem with shape of ndarray:</p>
<pre><code>out.shape = (20,)
reference.shape = (20,0)
norm = [out[i] / np.sum(out[i]) for i in range(len(out))]
# norm is a list now so I convert it to ndarray:
norm_array = np.array((norm))
norm_array.shape = (20,30)
# error: operands could not be broadcast together with shapes (20,30) (20,)
diff = np.fabs(norm_array - reference)
</code></pre>
<p>How can I change shape of norm_array from (20,30) into (20,) or reference to (20,30), so I can substract them?</p>
<p>EDIT: Can someone explain me, why they have different shape, if I can access both single elements with norm_array[0][0] and reference[0][0] ?</p>
| 0 | 2016-08-15T00:41:33Z | 38,948,220 | <p>I am not sure what you are trying to do exactly, but here is some information on numpy arrays.</p>
<p>A 1-d numpy array is a row vector with a shape that is a single-valued tuple:</p>
<pre><code>>>> np.array([1,2,3]).shape
(3,)
</code></pre>
<p>You can create multidimensional arrays by passing in nested lists. Each sub-list is a 1-d row vector of length 1, and there are 3 of them. </p>
<pre><code>>>> np.array([[1],[2],[3]]).shape
(3,1)
</code></pre>
<p>Here is the weird part. You can create the same array, but leave the lists empty. You end up with 3 row vectors of length 0.</p>
<pre><code>>>> np.array([[],[],[]]).shape
(3,0)
</code></pre>
<p>This is what you have for you <code>reference</code> array, an array with structure but no values. This brings me back to my original point:</p>
<p>You can't subtract an empty array.</p>
| 2 | 2016-08-15T01:39:07Z | [
"python",
"arrays",
"numpy",
"reshape"
] |
Reshaping numpy array from list | 38,947,926 | <p>I have the following problem with shape of ndarray:</p>
<pre><code>out.shape = (20,)
reference.shape = (20,0)
norm = [out[i] / np.sum(out[i]) for i in range(len(out))]
# norm is a list now so I convert it to ndarray:
norm_array = np.array((norm))
norm_array.shape = (20,30)
# error: operands could not be broadcast together with shapes (20,30) (20,)
diff = np.fabs(norm_array - reference)
</code></pre>
<p>How can I change shape of norm_array from (20,30) into (20,) or reference to (20,30), so I can substract them?</p>
<p>EDIT: Can someone explain me, why they have different shape, if I can access both single elements with norm_array[0][0] and reference[0][0] ?</p>
| 0 | 2016-08-15T00:41:33Z | 38,948,579 | <p>If I make 2 arrays with the shapes you describe, I get an error</p>
<pre><code>In [1856]: norm_array=np.ones((20,30))
In [1857]: reference=np.ones((20,0))
In [1858]: norm_array-reference
...
ValueError: operands could not be broadcast together with shapes (20,30) (20,0)
</code></pre>
<p>But it's different from yours. But if I change the shape of <code>reference</code>, the error messages match.</p>
<pre><code>In [1859]: reference=np.ones((20,))
In [1860]: norm_array-reference
...
ValueError: operands could not be broadcast together with shapes (20,30) (20,)
</code></pre>
<p>So your <code>(20,0)</code> is wrong. I don't know if you mistyped something or not.</p>
<p>But if I make <code>reference</code> 2d with 1 in the last dimension, broadcasting works, producing a difference that matches (20,30) in shape:</p>
<pre><code>In [1861]: reference=np.ones((20,1))
In [1862]: norm_array-reference
</code></pre>
<p>If <code>reference = np.zeros((20,))</code>, then I could use <code>reference[:,None]</code> to add that singleton last dimension.</p>
<p>If <code>reference</code> is (20,), you can't do <code>reference[0][0]</code>. <code>reference[0][0]</code> only works with 2d arrays with at least 1 in the last dim. <code>reference[0,0]</code> is the preferred way of indexing a single element of a 2d array.</p>
<p>So far this is normal array dimensions and broadcasting; something you'll learn with use.</p>
<p>===============</p>
<p>I'm puzzled about the shape of <code>out</code>. If it is (20,), how does <code>norm_array</code> end up as (20,30). <code>out</code> must consist of 20 arrays or lists, each of which has 30 elements.</p>
<p>If <code>out</code> was 2d array, we could normalize without iteration</p>
<pre><code>In [1869]: out=np.arange(12).reshape(3,4)
</code></pre>
<p>with the list comprehension:</p>
<pre><code>In [1872]: [out[i]/np.sum(out[i]) for i in range(out.shape[0])]
Out[1872]:
[array([ 0. , 0.16666667, 0.33333333, 0.5 ]),
array([ 0.18181818, 0.22727273, 0.27272727, 0.31818182]),
array([ 0.21052632, 0.23684211, 0.26315789, 0.28947368])]
In [1873]: np.array(_) # and to array
Out[1873]:
array([[ 0. , 0.16666667, 0.33333333, 0.5 ],
[ 0.18181818, 0.22727273, 0.27272727, 0.31818182],
[ 0.21052632, 0.23684211, 0.26315789, 0.28947368]])
</code></pre>
<p>Instead take row sums, and tell it to keep it 2d for ease of further use</p>
<pre><code>In [1876]: out.sum(axis=1,keepdims=True)
Out[1876]:
array([[ 6],
[22],
[38]])
</code></pre>
<p>now divide</p>
<pre><code>In [1877]: out/out.sum(axis=1,keepdims=True)
Out[1877]:
array([[ 0. , 0.16666667, 0.33333333, 0.5 ],
[ 0.18181818, 0.22727273, 0.27272727, 0.31818182],
[ 0.21052632, 0.23684211, 0.26315789, 0.28947368]])
</code></pre>
| 0 | 2016-08-15T02:34:26Z | [
"python",
"arrays",
"numpy",
"reshape"
] |
Manipulating data frame in R | 38,947,967 | <p>I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A.</p>
<p>Below is a reproducible example.</p>
<pre><code>set.seed(10)
fooDF <- data.frame(A = sample(1:4, 10, replace=TRUE), B = sample(letters[1:4], 10, replace=TRUE), C= sample(letters[1:4], 10, replace=TRUE), D = sample(1:4, 10, replace=TRUE))
fooDF[!duplicated(fooDF),]
A B C D
1 4 c b 2
2 4 d a 2
3 2 a b 4
4 3 c a 1
5 4 a b 3
6 4 b a 2
7 1 b d 2
8 1 a d 4
9 2 b a 3
10 2 d c 2
newdata <- data.frame(A = 1:4)
for(i in 1:nrow(fooDF)){
col_name <- paste(fooDF$B[i], fooDF$C[i], sep="")
newdata[newdata$A == fooDF$A[i], col_name ] <- fooDF$D[i]
}
</code></pre>
<p>The format I am trying to get it in.</p>
<pre><code>> newdata
A cb da ab ca ba bd ad dc
1 1 NA NA NA NA NA 2 4 NA
2 2 NA NA 4 NA 3 NA NA 2
3 3 NA NA NA 1 NA NA NA NA
4 4 2 2 3 NA 2 NA NA NA
</code></pre>
<p>Right now I am doing it line by line but that is unfeasible for a large csv containing 5 million + lines. Is there a way to do it faster in R or python?</p>
| 1 | 2016-08-15T00:49:27Z | 38,948,115 | <p>First paste columns B and C together (into column "z"):</p>
<pre><code>fooDF$z = paste0(fooDF$B,fooDF$C)
A B C D z
1 3 d c 3 dc
2 1 b d 3 bd
3 1 a a 2 aa
4 2 d a 1 da
5 4 d c 1 dc
6 2 d b 2 db
7 4 b d 3 bd
8 2 c d 3 cd
9 1 a b 2 ab
10 4 a b 2 ab
</code></pre>
<p>Then I'll remove columns B and C</p>
<pre><code>fooDF$B = NULL
fooDF$c = NULL
</code></pre>
<p>And last do a reshape from long to wide:</p>
<pre><code>finalFooDF = reshape(fooDF, timevar = "z", direction = "wide",idvar = "A")
A D.dc D.bd D.aa D.da D.db D.cd D.ab
1 3 3 NA NA NA NA NA NA
2 1 NA 3 2 NA NA NA 2
4 2 NA NA NA 1 2 3 NA
5 4 1 3 NA NA NA NA 2
</code></pre>
| 3 | 2016-08-15T01:16:14Z | [
"python"
] |
Manipulating data frame in R | 38,947,967 | <p>I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A.</p>
<p>Below is a reproducible example.</p>
<pre><code>set.seed(10)
fooDF <- data.frame(A = sample(1:4, 10, replace=TRUE), B = sample(letters[1:4], 10, replace=TRUE), C= sample(letters[1:4], 10, replace=TRUE), D = sample(1:4, 10, replace=TRUE))
fooDF[!duplicated(fooDF),]
A B C D
1 4 c b 2
2 4 d a 2
3 2 a b 4
4 3 c a 1
5 4 a b 3
6 4 b a 2
7 1 b d 2
8 1 a d 4
9 2 b a 3
10 2 d c 2
newdata <- data.frame(A = 1:4)
for(i in 1:nrow(fooDF)){
col_name <- paste(fooDF$B[i], fooDF$C[i], sep="")
newdata[newdata$A == fooDF$A[i], col_name ] <- fooDF$D[i]
}
</code></pre>
<p>The format I am trying to get it in.</p>
<pre><code>> newdata
A cb da ab ca ba bd ad dc
1 1 NA NA NA NA NA 2 4 NA
2 2 NA NA 4 NA 3 NA NA 2
3 3 NA NA NA 1 NA NA NA NA
4 4 2 2 3 NA 2 NA NA NA
</code></pre>
<p>Right now I am doing it line by line but that is unfeasible for a large csv containing 5 million + lines. Is there a way to do it faster in R or python?</p>
| 1 | 2016-08-15T00:49:27Z | 38,948,508 | <p>In <code>R</code>, this can be done with <code>tidyr</code></p>
<pre><code>library(tidyr)
fooDF %>%
unite(BC, B, C, sep="") %>%
spread(BC, D)
# A ab ad ba bd ca cb da dc
#1 1 NA 4 NA 2 NA NA NA NA
#2 2 4 NA 3 NA NA NA NA 2
#3 3 NA NA NA NA 1 NA NA NA
#4 4 3 NA 2 NA NA 2 2 NA
</code></pre>
<hr>
<p>Or we can do this with <code>dcast</code></p>
<pre><code>library(data.table)
dcast(setDT(fooDF), A~paste0(B,C), value.var = "D")
# A ab ad ba bd ca cb da dc
#1: 1 NA 4 NA 2 NA NA NA NA
#2: 2 4 NA 3 NA NA NA NA 2
#3: 3 NA NA NA NA 1 NA NA NA
#4: 4 3 NA 2 NA NA 2 2 NA
</code></pre>
<h3>data</h3>
<pre><code>fooDF <- structure(list(A = c(4L, 4L, 2L, 3L, 4L, 4L, 1L, 1L, 2L, 2L),
B = c("c", "d", "a", "c", "a", "b", "b", "a", "b", "d"),
C = c("b", "a", "b", "a", "b", "a", "d", "d", "a", "c"),
D = c(2L, 2L, 4L, 1L, 3L, 2L, 2L, 4L, 3L, 2L)), .Names = c("A",
"B", "C", "D"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10"))
</code></pre>
| 3 | 2016-08-15T02:23:27Z | [
"python"
] |
bash on Ubuntu on windows Linux, folder recognition, and running Python scripts | 38,948,021 | <p>I'm new to Linux. I recently downloaded Bash on Ubuntu on Windows 10 (after the Anniversary edition update to Windows 10). Since this update is relatively new, there is not much online regarding troubleshooting. There are two things I need help on:</p>
<p>(1) When I go to the home folder, which seems to be "C:\Users\user\AppData\Local\lxss\home\user" and I add a new folder through Windows, this folder does not show up in Linux with the "ls" command. But when I add a directory using "mkdir" in Linux, the "ls" command shows this folder. Why is it behaving like this? Am I limited to creating folders through "mkdir" when working in this folder?</p>
<p>(2) I have a Python script sitting in that same folder that I'm trying to run and again it is not being found by Linux or the Python interpreter started in Bash on Ubuntu on Windows. I have Python 3 installed (Anaconda) and I'm able to type commands directly in the Python interpreter and it's working. However, I would like to run scripts in files.</p>
<p>Please let me know if more information is needed. Thanks. </p>
| 0 | 2016-08-15T00:57:58Z | 39,723,038 | <p>Looks like you are having permissions issues.
To see everything on your home folder try
<strong>ls -al</strong>
to change permissions check out the <strong>chmod</strong> command </p>
| 0 | 2016-09-27T11:05:15Z | [
"python",
"linux",
"bash",
"ubuntu",
"wsl"
] |
Using searchsorted for 2D array | 38,948,042 | <p>I would like to have the index like function :<code>np.searchsorted([1,2,3,4,5], 3)</code> returns 2 but in case 2-D dimension: <code>np.searchsorted([[1,2],[3,4],[5,6]], [5,6])</code> should return 2. How can I do that?</p>
| 2 | 2016-08-15T01:01:44Z | 38,948,098 | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow">documentation for <code>searchsorted</code></a> indicates that it only works on 1-D arrays.</p>
<p>You can find the index location in a list using built-in methds:</p>
<pre><code>>>> a = [[1,2],[3,4],[5,6]]
>>> a.index([5,6])
2
>>> a = [[1,2],[5,6],[3,4]]
>>> print(a.index([5,6]))
>>> a.sort()
>>> print(a.index([5,6]))
1
2
</code></pre>
| 1 | 2016-08-15T01:12:46Z | [
"python",
"numpy"
] |
Using searchsorted for 2D array | 38,948,042 | <p>I would like to have the index like function :<code>np.searchsorted([1,2,3,4,5], 3)</code> returns 2 but in case 2-D dimension: <code>np.searchsorted([[1,2],[3,4],[5,6]], [5,6])</code> should return 2. How can I do that?</p>
| 2 | 2016-08-15T01:01:44Z | 38,948,106 | <pre><code>a = np.array([[1,2],[3,4],[5,6]])
b = np.array([5,6])
np.where(np.all(a==b,axis=1))
</code></pre>
| 3 | 2016-08-15T01:14:09Z | [
"python",
"numpy"
] |
Why doesn't Pycharm show dictionary methods in this case? | 38,948,132 | <p>I am trying to do a very simple service to collect and print data from a RESTfull API, in Python.
This is the code I have:</p>
<pre><code>import requests
import json
response = requests.get("url")
data2 = response.json()
print type(data2)
</code></pre>
<p>Here is my issue: when I print data2 type, it tells me it's a dictionary, so when I do <code>data2.</code> (notice the dot) my IDE should give me a series of methods like len(), cmp(),str() for me to choose from. But nothing shows up.
The same thing happens to me using Atom.
To be clear, if I write <code>data2.len()</code>, it does not say it is an error, so it recognizes the methods. But it doesn't show them as a suggestion.</p>
<p>How should I solve this? Thank you so much.</p>
| 1 | 2016-08-15T01:19:45Z | 39,334,190 | <p>As it was mentioned in comments PyCharm doesn't know type because <code>requests</code> doesn't declare return type. But it's possible to use type comments here (see <a href="https://www.python.org/dev/peps/pep-0484/#type-comments" rel="nofollow">PEP-484</a>):</p>
<pre><code>response = requests.get("url")
data2 = response.json() # type: dict
print(type(data2))
</code></pre>
| 2 | 2016-09-05T16:02:49Z | [
"python",
"dictionary",
"pycharm"
] |
Why doesn't Pycharm show dictionary methods in this case? | 38,948,132 | <p>I am trying to do a very simple service to collect and print data from a RESTfull API, in Python.
This is the code I have:</p>
<pre><code>import requests
import json
response = requests.get("url")
data2 = response.json()
print type(data2)
</code></pre>
<p>Here is my issue: when I print data2 type, it tells me it's a dictionary, so when I do <code>data2.</code> (notice the dot) my IDE should give me a series of methods like len(), cmp(),str() for me to choose from. But nothing shows up.
The same thing happens to me using Atom.
To be clear, if I write <code>data2.len()</code>, it does not say it is an error, so it recognizes the methods. But it doesn't show them as a suggestion.</p>
<p>How should I solve this? Thank you so much.</p>
| 1 | 2016-08-15T01:19:45Z | 39,334,842 | <p>PyCharm's inability to display the methods you mention indicate inability to infer the variable's type from the code alone. Which often indicates that the code might not be prepared to handle that variable's data properly in all cases (in many cases that means buggy code).</p>
<p>The fact that your code prints the type as <code>dict</code> in <em>that particular execution</em> doesn't mean it'll <em>always</em> be a <code>dict</code> (otherwise PyCharm would have been able to infer the type).</p>
<p>Making the code better prepared to deal with the variable's data in any situation - will make the type inferable, which will also allow PyCharm to fill in the data correctly.</p>
<p>For example, you could write your code like this:</p>
<pre><code>response = requests.get("url")
data2 = response.json()
assert isinstance(data2, dict)
print type(data2) # here data2's methods would be listed
</code></pre>
<p>or,</p>
<pre><code>response = requests.get("url")
data2 = response.json()
if isinstance(data2, dict):
print type(data2) # here data2's methods would be listed
</code></pre>
| 0 | 2016-09-05T16:51:05Z | [
"python",
"dictionary",
"pycharm"
] |
Fill django-tables2 with "special" queryset | 38,948,143 | <p>I'm trying django-tables2 to display some data, it looks like a nice tool, but I can't figure out how to use a queryset that uses fields from more than one model, at least not in an easy way. I built a queryset that shows data of five models, is the next:</p>
<pre><code>resultado=Producto.objects.filter(codigobarras_producto=txt_codigo_producto).values('pk',
'nombre_producto',
'inventarioproducto__bodega_idbodega__nombre_bodega',
'codigobarras_producto',
'inventarioproducto__existencia_actual',
'codigoestilo_producto',
'precio__valor_precio',
'marca_id_marca__nombre_marca')
</code></pre>
<p>How can I define the columns headers and show this result on a django-table? I'm using django 1.8, python 3.4 and the latest version of djagno-tables2 available on GitHub.</p>
| 0 | 2016-08-15T01:21:53Z | 38,948,618 | <p>I figured out, the same elements that I wrote inside "values", I used them in "field" definitions of the meta class of the table.</p>
| 0 | 2016-08-15T02:40:15Z | [
"python",
"django"
] |
Python MySQL queries time out where MySQL workbench works fine | 38,948,144 | <p>I recently had my website moved to a new server. I have some basic python scripts with access data in a MySQL database. On the old server we had no problems. On the new server :</p>
<ul>
<li>MySQLWorkbench can connect no trouble and perform all queries</li>
<li>The same (SELECT) queries with python work 5% of the time and the other 95% of the time they timeout or the connection is lost during the query</li>
<li>for example the table has 100000 rows, selecting the entire thing in MySQLWorkbench works fine. Returned in 3 seconds. </li>
<li>in python the same query never works, when LIMIT 2999 the query works but just LIMIT 3010 causes it to timeout. </li>
<li>same effect observed when the script is run locally or remotely</li>
</ul>
<p>Been digging around for a few days now to figure out if there are some settings in either the database, the database server, the server itself that prevent python (but not MySQLWorkbench) doing its job correctly. </p>
<p>The Query and code in case they are interesting:</p>
<pre><code>query = "SELECT * FROM wordpress.table;"
conn = MySQLConnection(**mysqlconfig)
cursor = conn.cursor()
cursor.execute(query)
rows = cursor.fetchall()
</code></pre>
<p>I don't have the details on the server but it has enough power for MySQLWorkbench to work fine, just python can't seem to be able to made to work</p>
<p>**** <strong><em>EDIT</em></strong> ****</p>
<p>To see if this problem was caused by queries returning too much data for python to handle I thought of using OFFSET and LIMIT to loop through a bigger query in pieces with say 10 rows per query.</p>
<pre><code>total_rows = 100000
interval = 10
data = []
for n in range(0, total_rows / interval):
q = "SELECT * FROM wordpress.table LIMIT %s OFFSET %s" % (interval, n * interval)
cursor.execute(q)
returned = cursor.fetchall()
rows = [[i for i in j] for j in list(returned)]
for row in rows:
data.append(row)
print n, len(data)
</code></pre>
<p>Expected: this would quickly work through the bigger query in smaller pieces
Happens: It gets further than the 3000 rows it got stuck on before but ends up hitting a wall after some iterations. Also not consistently, running the script 10 times results in n reaching a different point each time.</p>
| 3 | 2016-08-15T01:21:53Z | 39,007,790 | <p>You might get better performance using a server side cursor:</p>
<pre><code>import MySQLdb.cursor
con = MySQLdb.connect(host=host,
user=user,
passwd=pwd,
charset=charset,
port=port,
cursorclass=MySQLdb.cursors.SSDictCursor);
cur = con.cursor()
cur.execute("SELECT * FROM wordpress.table")
for row in cur:
print row
</code></pre>
<p>You might to check also the replies to those questions:</p>
<p><a href="http://stackoverflow.com/questions/337479/how-to-get-a-row-by-row-mysql-resultset-in-python">How to get a row-by-row MySQL ResultSet in python</a></p>
<p><a href="http://stackoverflow.com/questions/1808150/how-to-efficiently-use-mysqldb-sscursor">How to efficiently use MySQLDB SScursor?</a></p>
| 2 | 2016-08-17T23:33:02Z | [
"python",
"mysql",
"mysql-workbench",
"mysql-connector-python"
] |
Position of widgets in GridLayout | 38,948,174 | <p>I'm trying to create a grid of widgets with each "cell" widget having a rectangle I can change the color of later. When I run the code below with the line <code>grid.add_widget(Button(text=str(i)))</code> the buttons fill the window (as in the docs). However, when I use my <code>Cell</code> widget as in <code>grid.add_widget(Cell())</code> all the widgets are bunched in the lower left corner (<code>position=[0,0]</code>, <code>size=[100,100]</code>). I found this question <a href="http://stackoverflow.com/questions/30679110/kivy-add-raw-widget-to-gridlayout-as-opposed-to-image-button-etc">Kivy: Add raw Widget to GridLayout (as opposed to Image, Button, etc)</a> and changed my <code>Cell</code> class to inherit from <code>Layout</code> instead of <code>Widget</code> but that didn't help things. Any ideas on what I'm doing wrong? What I'd like is a grid of colored rectangles. </p>
<p>Versions </p>
<pre><code>[INFO ] [Kivy ] v1.9.1
[INFO ] [Python ] v2.7.6 (default, Jun 22 2015, 17:58:13)
</code></pre>
<p>Code</p>
<pre><code>from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.layout import Layout
from kivy.graphics import Rectangle, Color
XSIZE=2
YSIZE=2
class Cell(Layout):
def __init__(self, *args, **kwargs):
super(Cell, self).__init__(*args, **kwargs)
with self.canvas:
Rectangle(size=self.size, pos=self.pos)
Color((0.2, 0.2, 0.2, 1.0))
class GameApp(App):
def build(self):
grid = GridLayout(rows=YSIZE, cols=XSIZE, size=Window.size)
for i in xrange(4):
print 'i={}'.format(i)
# grid.add_widget(Cell())
grid.add_widget(Button(text=str(i)))
return grid
if __name__ == '__main__':
GameApp().run()
</code></pre>
| 4 | 2016-08-15T01:30:16Z | 38,959,832 | <p>I will show an example on how you can achieve this.
I will create a grid class, and add the cell widgets to it.
But I will only use one canvas (the gridlayouts canvas).
So the cell class will contain an <a href="https://kivy.org/docs/api-kivy.graphics.instructions.html" rel="nofollow">InstructionGroup</a>, rather than make multiple canvases.<br>
To be able to set size, position and color of each cell later, those attributes must be attributes of the cell class.<br>
The attributes will be set in <code>MyGrid</code>'s <code>set_attributes</code> method.<br>
First when the app is running, you can get the positions of the cells, hence I use the <code>Clock.schedule_once</code> method. That will execute the next frame.<br>
And to demonstrate how to change the colors, I create a <code>Clock.schedule_interval</code>, to animate the colors of the cells with random colors. </p>
<p>So here is the example:</p>
<pre><code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import Rectangle, Color, InstructionGroup
from kivy.clock import Clock
from random import uniform
XSIZE=2
YSIZE=2
class Cell(Widget):
def __init__(self, i, **kwargs):
super(Cell, self).__init__(**kwargs)
self.ig = InstructionGroup()
self.rect = Rectangle()
self.color = Color(0.2, 0.2, 0.2*i)
self.ig.add(self.color)
self.ig.add(self.rect)
class MyGrid(GridLayout):
def __init__(self,**kwargs):
super(MyGrid,self).__init__(**kwargs)
self.rows=YSIZE
self.cols=XSIZE
for i in xrange(4):
self.add_widget(Cell(i))
self.canvas.add(self.children[0].ig)
Clock.schedule_once(self.set_attributes)
Clock.schedule_interval(self.change_color,1)
def set_attributes(self,dt):
for i in self.children:
i.rect.pos = i.pos
i.rect.size = i.size
def change_color(self,dt):
for i in self.children:
i.color.rgb = (uniform(0.0,1.0),uniform(0.0,1.0),uniform(0.0,1.0))
class GameApp(App):
def build(self):
return MyGrid()
if __name__ == '__main__':
GameApp().run()
</code></pre>
| 1 | 2016-08-15T17:23:37Z | [
"python",
"kivy"
] |
Python Selenium with Chrome. How to switch between different tabs | 38,948,190 | <p>I click a button which opens a new tab. How to I then navigate around the new tab?</p>
<p>This sounds like a simple task but after several hours trying to find a solution I'm not any closer. Is there a simple way of doing this?</p>
<p>Tried using keys for CONTROL + 'T' and read other suggestions but nothing seems to work.</p>
<p>Many thanks</p>
| 0 | 2016-08-15T01:32:43Z | 39,149,217 | <p>I just implemented my solution and it worked for my case, which looks very similar to yours.</p>
<p>First you need to check the <code>window_handles</code>:</p>
<pre><code>len(driver.window_handles) > 1
</code></pre>
<p>If you have more than one, you can try to switch to your second handler:</p>
<pre><code>driver.switch_to_window(driver.window_handles[1])
</code></pre>
| 0 | 2016-08-25T15:28:36Z | [
"python",
"selenium",
"selenium-chromedriver"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start
print sum_nums(5)
</code></pre>
| 0 | 2016-08-15T01:45:25Z | 38,948,305 | <p>Use the python built in 'reduce' like below. Also what you want can be achieved when you start from 1 and iterate till 6.</p>
<pre><code>reduce(lambda x, y: x+y, range(1, 6))
</code></pre>
| 1 | 2016-08-15T01:51:30Z | [
"python"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start
print sum_nums(5)
</code></pre>
| 0 | 2016-08-15T01:45:25Z | 38,948,308 | <p>This could be done with a 1 liner but i'll help you out with a solution in the format that you're attempting.</p>
<pre><code>def sum_nums(number):
total = 0
for i in range(number + 1):
total += i
print total
</code></pre>
<p>Input <code>5</code></p>
<p>Output <code>15</code></p>
<p>Also, some clarification as per your error message. <code>len</code> is to be used for strings. An integer does not have a length. By simply passing it to the <code>range</code> function it will try all of the numbers (if you don't specify a starting number) from 1 up to that number, but not including it. That's why we do <code>range(number + 1)</code> to include the target number.</p>
<p>Hope this helps :)</p>
| 0 | 2016-08-15T01:52:16Z | [
"python"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start
print sum_nums(5)
</code></pre>
| 0 | 2016-08-15T01:45:25Z | 38,948,349 | <p>You can do this in a one liner with:</p>
<pre><code>def sum_range_inclusive(number):
return sum(range(number + 1))
</code></pre>
<p>To break this down:</p>
<pre><code># assume number is 5 for now
number = 5
# exclusive, doesn't include the number
range(number)
# returns [0, 1, 2, 3, 4]
# inclusive, includes the number
range(number + 1)
# returns [0, 1, 2, 3, 4, 5]
# sum of inclusive range
sum([0, 1, 2, 3, 4, 5])
# returns 15
</code></pre>
| 1 | 2016-08-15T01:59:23Z | [
"python"
] |
Adding all the numbers in a Range, including the number | 38,948,264 | <p>I was trying to create a function that added up the range of a number, including the number. </p>
<p>So when I input 5, I should receive 15. </p>
<p>Why is this function not working?</p>
<pre><code>def sum_nums(number):
start = 0
for index in range(0,len(number)):
start += index
return start
print sum_nums(5)
</code></pre>
| 0 | 2016-08-15T01:45:25Z | 38,948,391 | <p>This question would be amiss if someone didn't mention that <code>sum(range(n))</code> is always <code>n*(n-1)/2</code>. If you wish to do this inclusive of the value <code>n</code>, the expressions are <code>sum(range(n+1))</code> and <code>n*(n+1)/2</code>.</p>
| 2 | 2016-08-15T02:06:21Z | [
"python"
] |
how to work around yahoo data issue? Not enough volume to fill | 38,948,348 | <p>I am working on a MACD strategy backtest, and sometimes I came across this warning:</p>
<pre><code>2015-02-19 00:00:00 broker.backtesting [DEBUG] Not enough volume to fill 1988.HK market order [1] for 55258 share/s
Then I checked the csv data source and found:
Date Open High Low Close Volume Adj Close
19/02/2015 9.06 9.06 9.06 9.06 0 8.59591
</code></pre>
<p>as you can see, the <code>volume</code> on that particular day was 0, so the order cannot be filled.</p>
<p>I am not going to hack the <code>pyalgotrade</code> framework, so is there anyway to work around this? e.g. pre-process the data from <code>yahoo</code> feed and set the volume to what I want. Thanks.</p>
| 0 | 2016-08-15T01:59:20Z | 38,964,948 | <p>Try this in the strategy constructor:</p>
<pre><code>self.getBroker().getFillStrategy().setVolumeLimit(None)
</code></pre>
| 0 | 2016-08-16T00:33:10Z | [
"python",
"pyalgotrade"
] |
Using shift operator for LFSR in python | 38,948,430 | <p>Let's say I want to write a 16bit linear feedback shift register LFSR in Python using its native shift operator.</p>
<ol>
<li>Does the operator itself have a feature to specify the bit to shifted into the new MSB position? </li>
<li>Does the operator have a carry flag or the like to catch the LSB falling out of the register?</li>
<li>Has to setup the register to 16bit size? Not sure how to do this in Python where variables are not clearly typed.</li>
<li>What's the smartest way to compute the multi-bit XOR function for the feedback. Actual bit extraction or lookup table?</li>
</ol>
<p>Thanks,
Gert</p>
| 0 | 2016-08-15T02:12:34Z | 38,948,543 | <p>Python does not have registers and you cannot declare the type of anything. </p>
<p>The shift operators operate on unlimited-precision integers. If you shift left, the number will continue to get larger indefinitely (or until out of memory). If you shift right, the least-significant bit is dropped as you would expect. There is no "carry flag", that's the kind of thing you see in assembly language and Python is not assembly. Since the integers have unlimited precision, logical and arithmetic shifts are equivalent, in a sense (if you imagine that the sign bit repeats indefinitely).</p>
<p>Any time you want fixed width operations you will just have to mask the results of the unlimited-precision operations. </p>
<p>As for the "smartest" way to do something, that's not really an appropriate question for Stack Overflow. </p>
| 0 | 2016-08-15T02:29:13Z | [
"python",
"bit-shift"
] |
Parsing string as boolean? | 38,948,483 | <p>Is it possible to parse a string in a <code>if</code> statement as a string? Something like</p>
<pre><code>if "1 > 2":
print "1 is greater than 2"
</code></pre>
<p>But is parsed as</p>
<pre><code>if 1 > 2:
print "1 is greater than 2"
</code></pre>
<p>Is this possible? Is the a program out there that does this?</p>
| 1 | 2016-08-15T02:19:20Z | 38,948,537 | <p>That's what <code>eval</code> is for.</p>
<pre><code>if eval("1 > 2"):
print "1 is greater than 2"
</code></pre>
<p>Be careful with <code>eval</code>, though. It will call <em>any</em> function supplied to it. Like <code>os.system('rm -rf /')</code> :/</p>
| 3 | 2016-08-15T02:28:17Z | [
"python",
"string",
"boolean"
] |
Parsing string as boolean? | 38,948,483 | <p>Is it possible to parse a string in a <code>if</code> statement as a string? Something like</p>
<pre><code>if "1 > 2":
print "1 is greater than 2"
</code></pre>
<p>But is parsed as</p>
<pre><code>if 1 > 2:
print "1 is greater than 2"
</code></pre>
<p>Is this possible? Is the a program out there that does this?</p>
| 1 | 2016-08-15T02:19:20Z | 38,949,050 | <p>If you are only comparing numerical values this approach would be safer in general.</p>
<p>This could also be made to work for non-numerical values.</p>
<pre><code>from operator import gt, ge, lt, le, eq, ne
def compare(expression):
parts = expression.split()
if len(parts) != 3:
raise Exception("Can only call this with 'A comparator B', like 1 > 2")
a, comp, b = parts
try:
a, b = float(a), float(b)
except:
raise Exception("Comparison only works for numerical values")
ops = {">": gt, '<': lt, '>=': ge, '<=': le, '==': eq, '!=': ne}
if comp not in ops:
raise Exception("Can only compare with %s" % (", ".join(ops)))
return ops.get(comp)(a, b)
def run_comp(expression):
try:
print("{} -> {}".format(expression, compare(expression)))
except Exception as e:
print str(e)
if __name__ == "__main__":
run_comp("1.0 > 2")
run_comp("2.0 > 2")
run_comp("2 >= 2")
run_comp("2 <= 1")
run_comp("5 == 5.0")
run_comp("5 <= 5.0")
run_comp("5 != 5.0")
run_comp("7 != 5.0")
run_comp("pig > orange")
run_comp("1 ! 2")
run_comp("1 >")
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code>1.0 > 2 -> False
2.0 > 2 -> False
2 >= 2 -> True
2 <= 1 -> False
5 == 5.0 -> True
5 <= 5.0 -> True
5 != 5.0 -> False
7 != 5.0 -> True
Comparison only works for numerical values
Can only compare with >=, ==, <=, !=, <, >
Can only call this with 'A comparator B', like 1 > 2
</code></pre>
| 0 | 2016-08-15T03:47:05Z | [
"python",
"string",
"boolean"
] |
pip and and installing mysql-python. | 38,948,496 | <p>I'm trying to install MySQL-Python through pip with pip <code>install MySQL-Python</code>. But I'm getting a couple of error messages. Here's the console log:</p>
<pre><code>C:\WINDOWS\system32>pip install mysql-python
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: mysql-python
Running setup.py bdist_wheel for mysql-python ... error
Complete output from command c:\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Rasmus\\AppData\\Local\\Temp\\pip-build-cfm09c14\\mysql-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\Rasmus\AppData\Local\Temp\tmps09l9dk_pip-wheel- --python-tag cp35:
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-3.5
copying _mysql_exceptions.py -> build\lib.win-amd64-3.5
creating build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-3.5\MySQLdb
creating build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.5\MySQLdb\constants
running build_ext
building '_mysql' extension
creating build\temp.win-amd64-3.5
creating build\temp.win-amd64-3.5\Release
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\anaconda3\include -Ic:\anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /Tc_mysql.c /Fobuild\temp.win-amd64-3.5\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Failed building wheel for mysql-python
Running setup.py clean for mysql-python
Failed to build mysql-python
Installing collected packages: mysql-python
Running setup.py install for mysql-python ... error
Complete output from command c:\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Rasmus\\AppData\\Local\\Temp\\pip-build-cfm09c14\\mysql-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\Rasmus\AppData\Local\Temp\pip-u6i7y7az-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.5
copying _mysql_exceptions.py -> build\lib.win-amd64-3.5
creating build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-3.5\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-3.5\MySQLdb
creating build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.5\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.5\MySQLdb\constants
running build_ext
building '_mysql' extension
creating build\temp.win-amd64-3.5
creating build\temp.win-amd64-3.5\Release
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\anaconda3\include -Ic:\anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\\winrt" /Tc_mysql.c /Fobuild\temp.win-amd64-3.5\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Command "c:\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Rasmus\\AppData\\Local\\Temp\\pip-build-cfm09c14\\mysql-python\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\Rasmus\AppData\Local\Temp\pip-u6i7y7az-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Rasmus\AppData\Local\Temp\pip-build-cfm09c14\mysql-python\
</code></pre>
<p>I tried downloading the two whl files and install them 'manually' from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python</a> but they give the error:</p>
<pre><code>C:\WINDOWS\system32>pip install C:\Users\Rasmus\Downloads\MySQL_python-1.2.5-cp27-none-win_amd64.whl
MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform.
</code></pre>
<p>I used python 3.5, and windows 10. </p>
| 0 | 2016-08-15T02:21:10Z | 38,948,830 | <p>It seems your pip version is outdated. </p>
<ol>
<li><p>So first do <code>python -m pip install --upgrade pip</code></p></li>
<li><p>Then use your downloaded wheel, but do <code>python3 -m pip install [.whl_location]</code> if python3 is in your path, else navigate to python3 folder and do the same.</p></li>
</ol>
<p>Hope this helps.</p>
| 1 | 2016-08-15T03:13:21Z | [
"python"
] |
How to change locals() result from other function? | 38,948,541 | <p>I have some code like this:</p>
<pre><code>def f():
i = 5
g(locals())
print 'in f:', i, j
def g(env):
env['j'] = env['i'] + 1
print 'in g:', env['i'], env['j']
f()
</code></pre>
<p>I get:</p>
<pre><code>in g: 5 6
in f: 5---------------------------------------------------------------------------
NameError Traceback (most recent call last)
NameError: global name 'j' is not defined
</code></pre>
<p>It seems that g cannot change the local variables got by locals() in f. Is there anyway to change the local variables in other function?</p>
| -2 | 2016-08-15T02:28:48Z | 38,948,604 | <p>According to the <a href="https://docs.python.org/2/library/functions.html#locals" rel="nofollow">docs</a> regarding <code>locals</code>:</p>
<blockquote>
<p>Note The contents of this dictionary should not be modified; changes
may not affect the values of local and free variables used by the
interpreter.</p>
</blockquote>
<p>An alternative solution is to just return <code>j</code>.</p>
<pre><code>def f():
i = 5
j = g(locals())
print 'in f:', i, j
def g(env):
j = env['i'] + 1
print 'in g:', env['i'], j
return j
f()
</code></pre>
| 3 | 2016-08-15T02:37:59Z | [
"python",
"python-2.7",
"function",
"scope",
"local-variables"
] |
PySpark LogisticRegressionWithLBFGS Import error | 38,948,617 | <p>I am trying to use the pysoark LogisticRegression library.Below is part of my code:</p>
<pre><code> from pyspark.mllib.linalg import Vectors
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel, LogisticRegressionWithSGD
from pyspark import SparkContext
</code></pre>
<p>I am getting the error:</p>
<pre><code> Traceback (most recent call last):
File "LogisticRegression.py", line 3, in <module>
from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel, LogisticRegressionWithSGD
ImportError: cannot import name LogisticRegressionWithLBFGS
</code></pre>
<p>Is there a circular import dependency here?I am using Python 2.7.9</p>
| 1 | 2016-08-15T02:40:08Z | 38,952,426 | <p>I'd say your version of pyspark is outdated.</p>
<p>Try :</p>
<pre><code>pip freeze | grep pyspark
</code></pre>
<p><code>LogisticRegressionWithLBFGS</code> class was introduced in pyspark 1.2.0.</p>
<p>To upgrade your version of pyspark you can use <code>pip</code> as well :</p>
<pre><code>pip install pyspark --upgrade
</code></pre>
<p><strong>Edit :</strong></p>
<p>@ShuaiYuan comment's seems right and you can't use pip for pyspark.</p>
| 0 | 2016-08-15T09:19:21Z | [
"python",
"machine-learning",
"pyspark",
"logistic-regression"
] |
Call variable into a sqlite row | 38,948,729 | <p>I have a python script that reads a conf file and prints out matches. <br>These matches are all stored in a varialbe. <br>
I want to be able to insert the values into a sqlite table.. <br>
<br>
File reads: <br>
Hello Asia <br>
World Mumbai <br>
Hello America <br>
World Chicargo <br>
Hello Australia <br>
World Sydney <br>
<br></p>
<h1>Here is my scipt.</h1>
<pre><code>#!/usr/bin/python
import re
import sqlite3
File = open("/home/abc/def.conf", "r")
for line in File:
if re.match("(hello)", line, re.IGNORECASE):
Continent = line.lstrip("hello")
print Continent
if re.match("(world)", line, re.IGNORECASE):
City = line.lstrip("world")
print a
#Creating SQL TABLE
sqlite_file = '/home/abc/dbase.sqlite3'
table_name1 = 'table1'
new_column1 = 'Continent'
new_column2 = 'City'
conn = sqlite3.connect(sqlite_file)
cur.execute('CREATE TABLE {tn} ({nf})'\
.format(tn=table_name1, nf=new_column1))
cur.execute("ALTER TABLE {tn} ADD COLUMN '{cn}'"\
.format(tn=table_name1, cn=new_column2))
cur.execute("INSERT INTO table1
(`Continent`,`City`) VALUES ($Continent, $City)");
conn.commit()
conn.close()
</code></pre>
<p>-------------- VALUES ($Continent, $City)") ??? THIS IS WHERE I AM STUCK</p>
| 1 | 2016-08-15T02:58:14Z | 38,949,546 | <p>The syntax to insert values from Python variables is as follows:</p>
<pre><code>cur.execute("INSERT INTO table1 (`Continent`,`City`) VALUES (?,?)",(Continent,City));
</code></pre>
<p><code>?</code> represents a parameter and the second argument of the <code>execute</code> function is an iterable (tuple, list) of your corresponding variables.</p>
| 0 | 2016-08-15T05:02:14Z | [
"python",
"sql",
"sqlite"
] |
python append folder name to filenames in all sub folders | 38,948,774 | <p>I am trying to append the name of a folder to all filenames within that folder. I have to loop through a parent folder that contain sub folders. I have to do this in Python and not a bat file.</p>
<p>Example is, take these folders:</p>
<pre><code>Parent Folder
Sub1
example01.txt
example01.jpg
example01.tif
Sub2
example01.txt
example01.jpg
example01.tif
</code></pre>
<p>To this</p>
<pre><code>Parent Folder
Sub1
Sub1_example01.txt
Sub1_example01.jpg
Sub1_example01.tif
Sub2
Sub2_example01.txt
Sub2_example01.jpg
Sub2_example01.tif
</code></pre>
<p>I believe its os.rename, but i cant work out how to call the folder name.</p>
<p>Thanks for the advice.</p>
| 0 | 2016-08-15T03:05:51Z | 38,948,934 | <p>You can use <a href="https://docs.python.org/3.5/library/os.html#os.walk" rel="nofollow"><code>os.walk</code></a> to iterate over the directories and then <a href="https://docs.python.org/3.5/library/os.html#os.rename" rel="nofollow"><code>os.rename</code></a> to rename all the files:</p>
<pre><code>from os import walk, path, rename
for dirpath, _, files in walk('parent'):
for f in files:
rename(path.join(dirpath, f), path.join(dirpath, path.split(dirpath)[-1] + '_' + f))
</code></pre>
| 0 | 2016-08-15T03:29:53Z | [
"python",
"file-processing"
] |
python append folder name to filenames in all sub folders | 38,948,774 | <p>I am trying to append the name of a folder to all filenames within that folder. I have to loop through a parent folder that contain sub folders. I have to do this in Python and not a bat file.</p>
<p>Example is, take these folders:</p>
<pre><code>Parent Folder
Sub1
example01.txt
example01.jpg
example01.tif
Sub2
example01.txt
example01.jpg
example01.tif
</code></pre>
<p>To this</p>
<pre><code>Parent Folder
Sub1
Sub1_example01.txt
Sub1_example01.jpg
Sub1_example01.tif
Sub2
Sub2_example01.txt
Sub2_example01.jpg
Sub2_example01.tif
</code></pre>
<p>I believe its os.rename, but i cant work out how to call the folder name.</p>
<p>Thanks for the advice.</p>
| 0 | 2016-08-15T03:05:51Z | 38,948,949 | <p>I would use <code>os.path.basename</code> on the root to find your prefix.</p>
<pre><code>import os
for root, dirs, files in os.walk("Parent"):
if not files:
continue
prefix = os.path.basename(root)
for f in files:
os.rename(os.path.join(root, f), os.path.join(root, "{}_{}".format(prefix, f)))
</code></pre>
<p>Before</p>
<pre><code>> tree Parent
Parent
âââ Sub1
â  âââ example01.jpg
â  âââ example02.jpg
â  âââ example03.jpg
âââ Sub2
âââ example01.jpg
âââ example02.jpg
âââ example03.jpg
2 directories, 6 files
</code></pre>
<p>After</p>
<pre><code>> tree Parent
Parent
âââ Sub1
â  âââ Sub1_example01.jpg
â  âââ Sub1_example02.jpg
â  âââ Sub1_example03.jpg
âââ Sub2
âââ Sub2_example01.jpg
âââ Sub2_example02.jpg
âââ Sub2_example03.jpg
2 directories, 6 files
</code></pre>
| 1 | 2016-08-15T03:32:31Z | [
"python",
"file-processing"
] |
Python BeautifulSoup Referencing Tag with space in XML tag | 38,948,813 | <p>Apologies for my poorly formatted post and written code, first post! I'm sure this is a simple fix but cannot seem to figure it out.</p>
<p>Question 1: I'm Writing an XML scraper for an Eve Online API. I have a need to iterate on an HTML tag that has a space in it (<code>type id="X"</code>) with <code>*BeautifulSoup*</code>. I would like to iterate over the <em>item ID tags</em> in the XML (2 in this example). I'm not sure if <code>*Data.iter*</code> is the right approach or not. I know print Data.buy will find the first buy tag in the XML and print the children, but cannot find the same method to have it print the first Data.<code>'type id="x"'</code>.</p>
<p>Question 2: Any direction on how one would continue the scrape process would be welcome. I was thinking about exporting the buy / sell / all to some sort of storage (was thinking CSV files but not positive) with different storages for the different item IDs and the buy / sell orders.</p>
<pre><code>import requests #Used to service API connection
from lxml import html #Used to parse XML
from bs4 import BeautifulSoup #Used to read XML table on webpage
ItemTypeID1 = 34
ItemTypeID2 = 35
RegionID = 10000002
Webpage = requests.get('http://api.eve-central.com/api/marketstat?typeid=%i&typeid=%i&regionlimit=%i' % (ItemTypeID1, ItemTypeID2, RegionID))
#Check if page is up
if Webpage.status_code == 200:
#Convert webpage to %Data
Data = BeautifulSoup(Webpage.text, 'lxml')
#Problem line
for item in Data.iter('type id='):
print 'something'
</code></pre>
<p><a href="http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&regionlimit=10000002" rel="nofollow">http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&regionlimit=10000002</a></p>
<pre><code><?xml version='1.0' encoding='utf-8'?>
<evec_api version="2.0" method="marketstat_xml">
<marketstat><type id="34">
<buy><volume>21648183554</volume><avg>5.34</avg><max>5.78</max><min>2.00</min><stddev>0.83</stddev><median>5.52</median><percentile>5.58</percentile></buy>
<sell><volume>15987043271</volume><avg>6.20</avg><max>15.00</max><min>5.58</min><stddev>1.38</stddev><median>6.00</median><percentile>5.85</percentile></sell>
<all><volume>37635226825</volume><avg>5.71</avg><max>15.00</max><min>2.00</min><stddev>1.40</stddev><median>5.54</median><percentile>4.16</percentile></all>
</type><type id="35">
<buy><volume>4163954948</volume><avg>7.26</avg><max>9.39</max><min>4.02</min><stddev>1.60</stddev><median>6.48</median><percentile>9.24</percentile></buy>
<sell><volume>10154431073</volume><avg>11.84</avg><max>17.41</max><min>9.00</min><stddev>1.80</stddev><median>10.59</median><percentile>9.46</percentile></sell>
<all><volume>14318386021</volume><avg>10.51</avg><max>17.41</max><min>4.02</min><stddev>2.21</stddev><median>10.00</median><percentile>5.87</percentile></all>
</type></marketstat>
</evec_api>
</code></pre>
| -1 | 2016-08-15T03:10:55Z | 38,948,983 | <p><code>type id=</code> is not a tag. The tag name of the element is <code>type</code> and <code>id</code> is an <em>attribute</em> of that element.</p>
<pre><code>for item in Data.find_all('type'):
print item.get('id')
</code></pre>
<p>For the URL that you reference this code will output:</p>
<pre>
34
35
</pre>
<p>The code simply finds all elements with tag name "type" and displays the <code>id</code> attribute of each tag found.</p>
<p>You can access the data contained in the nested <code>buy</code> and <code>sell</code> tags:</p>
<pre><code>for item in Data.find_all('type'):
print item.get('id')
volume = item.buy.volume.text
avg = item.buy.volume.text
# etc.
</code></pre>
<p>which shows how to get at the data contained in the volume and avg tags for each item.</p>
<hr>
<p>There is also a JSON API available which might be easier to use, especially when using the <code>requests</code> module:</p>
<pre><code>import requests
url = 'http://api.eve-central.com/api/marketstat/json' # the JSON endpoint
params = {'typeid': (34, 35), 'RegionID': 10000002}
r = requests.get(url, params=params)
data = r.json()
</code></pre>
<p>This gives you a list of Python dictionaries to work with:</p>
<pre><code>for type_ in data:
print '{}: volume = {}, avg = {}'.format(type_['buy']['forQuery']['types'][0], type_['buy']['volume'], type_['buy']['avg'])
</code></pre>
<pre>
34: volume = 110242267166, avg = 4.29419161677
35: volume = 40908217125, avg = 6.71507628294
</pre>
<p>although getting the type id back out of the JSON response is a bit awkward compared to XML.</p>
| 1 | 2016-08-15T03:36:58Z | [
"python",
"xml",
"beautifulsoup",
"lxml"
] |
Python BeautifulSoup Referencing Tag with space in XML tag | 38,948,813 | <p>Apologies for my poorly formatted post and written code, first post! I'm sure this is a simple fix but cannot seem to figure it out.</p>
<p>Question 1: I'm Writing an XML scraper for an Eve Online API. I have a need to iterate on an HTML tag that has a space in it (<code>type id="X"</code>) with <code>*BeautifulSoup*</code>. I would like to iterate over the <em>item ID tags</em> in the XML (2 in this example). I'm not sure if <code>*Data.iter*</code> is the right approach or not. I know print Data.buy will find the first buy tag in the XML and print the children, but cannot find the same method to have it print the first Data.<code>'type id="x"'</code>.</p>
<p>Question 2: Any direction on how one would continue the scrape process would be welcome. I was thinking about exporting the buy / sell / all to some sort of storage (was thinking CSV files but not positive) with different storages for the different item IDs and the buy / sell orders.</p>
<pre><code>import requests #Used to service API connection
from lxml import html #Used to parse XML
from bs4 import BeautifulSoup #Used to read XML table on webpage
ItemTypeID1 = 34
ItemTypeID2 = 35
RegionID = 10000002
Webpage = requests.get('http://api.eve-central.com/api/marketstat?typeid=%i&typeid=%i&regionlimit=%i' % (ItemTypeID1, ItemTypeID2, RegionID))
#Check if page is up
if Webpage.status_code == 200:
#Convert webpage to %Data
Data = BeautifulSoup(Webpage.text, 'lxml')
#Problem line
for item in Data.iter('type id='):
print 'something'
</code></pre>
<p><a href="http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&regionlimit=10000002" rel="nofollow">http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&regionlimit=10000002</a></p>
<pre><code><?xml version='1.0' encoding='utf-8'?>
<evec_api version="2.0" method="marketstat_xml">
<marketstat><type id="34">
<buy><volume>21648183554</volume><avg>5.34</avg><max>5.78</max><min>2.00</min><stddev>0.83</stddev><median>5.52</median><percentile>5.58</percentile></buy>
<sell><volume>15987043271</volume><avg>6.20</avg><max>15.00</max><min>5.58</min><stddev>1.38</stddev><median>6.00</median><percentile>5.85</percentile></sell>
<all><volume>37635226825</volume><avg>5.71</avg><max>15.00</max><min>2.00</min><stddev>1.40</stddev><median>5.54</median><percentile>4.16</percentile></all>
</type><type id="35">
<buy><volume>4163954948</volume><avg>7.26</avg><max>9.39</max><min>4.02</min><stddev>1.60</stddev><median>6.48</median><percentile>9.24</percentile></buy>
<sell><volume>10154431073</volume><avg>11.84</avg><max>17.41</max><min>9.00</min><stddev>1.80</stddev><median>10.59</median><percentile>9.46</percentile></sell>
<all><volume>14318386021</volume><avg>10.51</avg><max>17.41</max><min>4.02</min><stddev>2.21</stddev><median>10.00</median><percentile>5.87</percentile></all>
</type></marketstat>
</evec_api>
</code></pre>
| -1 | 2016-08-15T03:10:55Z | 38,953,311 | <p>You have a couple of issues, you seem to be mixing up <em>bs4</em> and <em>lxml</em> syntax, <em>iter</em> is an lxml method, <em>type</em> is the node and <em>id</em> is an attribute of the node.</p>
<p>Since you are using lxml just forget about bs4 and getting the data is quite simple:</p>
<pre><code>from lxml import html # Used to parse XML
ItemTypeID1 = 34
ItemTypeID2 = 35
RegionID = 10000002
webpage = requests.get('http://api.eve-central.com/api/marketstat?typeid=%i&typeid=%i&regionlimit=%i' % (
ItemTypeID1, ItemTypeID2, RegionID))
if webpage.status_code == 200:
data = html.fromstring(webpage.content)
for item in data.iter('type'):
print(item.get("id")) # print node attribute id value.
buy_dict = {node.tag: node.text for node in item.xpath("buy/*")}
sell_dict = {node.tag: node.text for node in item.xpath("sell/*")}
print(buy_dict)
print(sell_dict)
</code></pre>
<p>That will give you:</p>
<pre><code>34
{'min': '2.00', 'max': '5.81', 'median': '5.54', 'volume': '22518685011', 'percentile': '5.72', 'stddev': '0.80', 'avg': '5.37'}
{'min': '5.57', 'max': '15.00', 'median': '6.00', 'volume': '14953114542', 'percentile': '5.78', 'stddev': '1.38', 'avg': '6.21'}
35
{'min': '4.02', 'max': '9.20', 'median': '6.65', 'volume': '4170891614', 'percentile': '9.20', 'stddev': '1.59', 'avg': '7.25'}
{'min': '8.90', 'max': '17.41', 'median': '10.59', 'volume': '10089810619', 'percentile': '9.44', 'stddev': '1.84', 'avg': '11.83'}
</code></pre>
<p>Then to write to a csv:</p>
<pre><code>import requests # Used to service API connection
from lxml import html # Used to parse XML
from csv import DictWriter
ItemTypeID1 = 34
ItemTypeID2 = 35
RegionID = 10000002
webpage = requests.get('http://api.eve-central.com/api/marketstat?typeid=%i&typeid=%i&regionlimit=%i' % (
ItemTypeID1, ItemTypeID2, RegionID))
if webpage.status_code == 200:
with open("data.csv", "w") as f:
wr = DictWriter(f, fieldnames=["buy/sell", 'volume', 'min', 'max', 'median', 'percentile', 'stddev', 'avg'])
wr.writeheader()
data = html.fromstring(webpage.content)
for item in data.iter('type'):
buy_dict = {node.tag: node.text for node in item.xpath("buy/*")}
buy_dict["buy/sell"] = "buy"
sell_dict = {node.tag: node.text for node in item.xpath("sell/*")}
sell_dict["buy/sell"] = "sell"
wr.writerows([buy_dict, sell_dict])
</code></pre>
<p>Which will give you:</p>
<pre><code>buy/sell,volume,min,max,median,percentile,stddev,avg
buy,22518685011,2.00,5.81,5.54,5.72,0.80,5.37
sell,14953114542,5.57,15.00,6.00,5.78,1.38,6.21
buy,4170891614,4.02,9.20,6.65,9.20,1.59,7.25
sell,10089810619,8.90,17.41,10.59,9.44,1.84,11.83
</code></pre>
| 0 | 2016-08-15T10:21:49Z | [
"python",
"xml",
"beautifulsoup",
"lxml"
] |
Shifting the location of tensor3 elements based on an offset vector | 38,948,862 | <p>I have a Theano <code>tensor3</code> (i.e., a 3-dimensional array) <code>x</code>:</p>
<pre><code>[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
</code></pre>
<p>as well as a Theano vector (i.e., a 1-dimensional array) <code>y</code>, which we will refer as an "offset" vector, since it specifies the desired offset:</p>
<pre><code>[2, 1]
</code></pre>
<p>I want to shift the location of elements of <code>x</code> based on vector <code>y</code>, so that the output be as follows (the shift is performed on the second dimension):</p>
<pre><code>[[[ a b c d]
[ e f g h]
[ 0 1 2 3]]
[[ i j k l]
[12 13 14 15]
[16 17 18 19]]]
</code></pre>
<p>where the <code>a</code>, <code>b</code>, â¦, <code>l</code> could be any number.</p>
<p>For example, a valid output could be:</p>
<pre><code>[[[ 0 0 0 0]
[ 0 0 0 0]
[ 0 1 2 3]]
[[ 0 0 0 0]
[12 13 14 15]
[16 17 18 19]]]
</code></pre>
<p>Another valid output could be:</p>
<pre><code>[[[ 4 5 6 7]
[ 8 9 10 11]
[ 0 1 2 3]]
[[20 21 22 23]
[12 13 14 15]
[16 17 18 19]]]
</code></pre>
<hr>
<p>I am aware of the function <a href="http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor.roll" rel="nofollow"><code>theano.tensor.roll(x, shift, axis=None)</code></a>, however the <code>shift</code> can only take a scalar as input, i.e. it shifts all elements with the same offset.</p>
<p>E.g., the code:</p>
<pre><code>import theano.tensor
from theano import shared
import numpy as np
x = shared(np.arange(24).reshape((2,3,4)))
print('theano.tensor.roll(x, 2, axis=1).eval(): \n{0}'.
format(theano.tensor.roll(x, 2, axis=1).eval()))
</code></pre>
<p>outputs:</p>
<pre><code>theano.tensor.roll(x, 2, axis=1).eval():
[[[ 4 5 6 7]
[ 8 9 10 11]
[ 0 1 2 3]]
[[16 17 18 19]
[20 21 22 23]
[12 13 14 15]]]
</code></pre>
<p>which is not what I want.</p>
<p>How can I shift the location of <code>tensor3</code> elements based on an offset vector? (note that in the code provided in this example, the <code>tensor3</code> is a shared variable for convenience, but in my actual code it will be a symbolic variable)</p>
| 0 | 2016-08-15T03:19:34Z | 38,980,184 | <p>I couldn't find any dedicated function for that purpose, so I simply ended up using <a href="http://deeplearning.net/software/theano/tutorial/loop.html" rel="nofollow"><code>theano.scan</code></a>:</p>
<pre><code>import theano
import theano.tensor
from theano import shared
import numpy as np
y = shared(np.array([2,1]))
x = shared(np.arange(24).reshape((2,3,4)))
print('x.eval():\n{0}\n'.format(x.eval()))
def shift_and_reverse_row(matrix, y):
'''
Shift and reverse the matrix in the direction of the first dimension (i.e., rows)
matrix: matrix
y: scalar
'''
new_matrix = theano.tensor.zeros_like(matrix)
new_matrix = theano.tensor.set_subtensor(new_matrix[:y,:], matrix[y-1::-1,:])
return new_matrix
new_x, updates = theano.scan(shift_and_reverse_row, outputs_info=None,
sequences=[x, y[::-1]] )
new_x = new_x[:, ::-1, :]
print('new_x.eval(): \n{0}'.format(new_x.eval()))
</code></pre>
<p>output:</p>
<pre><code>x.eval():
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
new_x.eval():
[[[ 0 0 0 0]
[ 0 0 0 0]
[ 0 1 2 3]]
[[ 0 0 0 0]
[12 13 14 15]
[16 17 18 19]]]
</code></pre>
| 0 | 2016-08-16T16:37:32Z | [
"python",
"multidimensional-array",
"theano"
] |
Import csv to django model using csvImporter | 38,948,917 | <p>I am trying to import data from a csv file to a django model. I found <a href="http://stackoverflow.com/questions/2459979/how-to-import-csv-data-into-django-models">this</a> thread, which lead me to the documentation for <a href="http://django-csv-importer.readthedocs.io/en/latest/" rel="nofollow">CSVImporter</a>. Since I have already declared a model in my django app, the documentation suggests I use the following code:</p>
<pre><code>>>> from my_projects.models import Person
>>> from csvImporter.model import CsvDbModel
>>>
>>> class MyCsvModel(CsvDbModel):
>>>
>>> class Meta:
>>> dbModel = Person
>>> delimiter = ";"
</code></pre>
<p>So I did this:</p>
<pre><code>from polls.models import Question
from csvImporter.model import CsvDbModel
File "/Users/ytk/anaconda3/lib/python3.5/site-packages/csvImporter/model.py", line 134
except ValueError,e :
^
SyntaxError: invalid syntax
</code></pre>
<p>What am I doing wrong?</p>
| 1 | 2016-08-15T03:27:25Z | 38,949,109 | <p>This syntax is incompatible with python 3. The correct syntax in Python3 is </p>
<pre><code>except ValueError as e:
...
</code></pre>
<p>This library doesn't support python 3, but exists pull request to make support <a href="https://github.com/anthony-tresontani/csv_importer/pulls" rel="nofollow">https://github.com/anthony-tresontani/csv_importer/pulls</a></p>
| 1 | 2016-08-15T03:56:32Z | [
"python",
"django",
"csv-import"
] |
Get the selected text content from other programs | 38,948,947 | <p>When I am using other programs (e.g. opening a pdf or word), I will select some text contents (like a word or paragraph) by using the mouse. I want my python program to get this text content. How to do this using PyQt, or some other Python library?</p>
| -1 | 2016-08-15T03:32:05Z | 38,963,809 | <p>This is an easy task, you haven't specified the pyqt version, so I'll post the solution for PyQt4, here you go:</p>
<pre><code>from PyQt4.QtCore import QObject, pyqtSlot, SIGNAL, SLOT
from PyQt4.QtGui import QApplication, QMessageBox
import sys
class MyClipboard(QObject):
@pyqtSlot()
def changedSlot(self):
if(QApplication.clipboard().mimeData().hasText()):
QMessageBox.information(None, "Text has been copied somewhere!",
QApplication.clipboard().text())
def main():
app = QApplication(sys.argv)
listener = MyClipboard()
app.setQuitOnLastWindowClosed(False)
QObject.connect(QApplication.clipboard(), SIGNAL(
"dataChanged()"), listener, SLOT("changedSlot()"))
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-08-15T22:09:41Z | [
"python",
"linux",
"pyqt",
"clipboard"
] |
How do I make part of the script asynchronous with dask? | 38,948,956 | <p>Suppose I am given a collection of documents. I am required to tokenize them, and then turn them into vectors for further work. As I find elasticsearch's tokenizer works much better than my own solution, I am switching to that. However, it is considerably slower. Then the end result is expected to be fed into the vectorizer in a stream.</p>
<p>The whole process can be done with a chained list of generators</p>
<pre><code>def fetch_documents(_cursor):
with _cursor:
# a lot of documents expected, may not fit in memory
_cursor.execute('select ... from ...')
for doc in _cursor:
yield doc
def tokenize(documents):
for doc in documents:
yield elasticsearch_tokenize_me(doc)
def build_model(documents):
some_model = SomeModel()
for doc in documents:
some_model.add_document(doc)
return some_model
build_model(tokenize(fetch_documents))
</code></pre>
<p>So this basically works fine, but doesn't utilize all the available processing capability. As dask is used in other related projects, I try to adapt and get this (I am using psycopg2 for database access).</p>
<pre><code>from dask import delayed
import psycopg2
import psycopg2.extras
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
def loader():
conn = psycopg2.connect()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute('''
SELECT document, ... FROM ...
''')
return cur
@delayed
def tokenize(partition):
result = []
client = IndicesClient(Elasticsearch())
for row in partition:
_result = client.analyze(analyzer='standard', text=row['document'])
result.append(dict(row,
tokens=tuple(item['token'] for item in _result['tokens'])))
return result
@delayed
def build_model(sequence_of_data):
some_model = SomeModel()
for item in chain.from_iterable(sequence_of_data):
some_model.add_document(item)
return some_model
with loader() as cur:
partitions = []
for idx_start in range(0, cur.rowcount, 200):
partitions.append(delayed(cur.fetchmany)(200))
tokenized = []
for partition in partitions:
tokenized.append(tokenize(partition))
result = do_something(tokenized)
result.compute()
</code></pre>
<p>Code more or less work, except at the end all documents are tokenized, before being fed into the model. While this works for smaller collection of data, however not for a huge collection of data (due to huge memory consumption). Should I just use plain <code>concurrent.futures</code> for this work or am I using dask wrongly?</p>
| 1 | 2016-08-15T03:33:23Z | 38,949,233 | <p>Using just <code>concurrent.futures</code> for the work</p>
<pre><code>from concurrent.futures import ProcessPoolExecutor
def loader():
conn = psycopg2.connect()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute('''
SELECT document, ... FROM ...
''')
return cur
def tokenize(partition):
result = []
client = IndicesClient(Elasticsearch())
for row in partition:
_result = client.analyze(analyzer='standard', text=row['document'])
result.append(dict(row,
tokens=tuple(item['token'] for item in _result['tokens'])))
return result
def do_something(partitions, total):
some_model = 0
for partition in partitions:
result = partition.result()
for item in result:
some_model.add_document(item)
return some_model
with loader() as cur, \
ProcessPoolExecutor(max_workers=8) as executor:
print(cur.rowcount)
partitions = []
for idx_start in range(0, cur.rowcount, 200):
partitions.append(executor.submit(tokenize,
cur.fetchmany(200)))
build_model(partitions)
</code></pre>
| 1 | 2016-08-15T04:12:10Z | [
"python",
"python-3.x",
"dask"
] |
How do I make part of the script asynchronous with dask? | 38,948,956 | <p>Suppose I am given a collection of documents. I am required to tokenize them, and then turn them into vectors for further work. As I find elasticsearch's tokenizer works much better than my own solution, I am switching to that. However, it is considerably slower. Then the end result is expected to be fed into the vectorizer in a stream.</p>
<p>The whole process can be done with a chained list of generators</p>
<pre><code>def fetch_documents(_cursor):
with _cursor:
# a lot of documents expected, may not fit in memory
_cursor.execute('select ... from ...')
for doc in _cursor:
yield doc
def tokenize(documents):
for doc in documents:
yield elasticsearch_tokenize_me(doc)
def build_model(documents):
some_model = SomeModel()
for doc in documents:
some_model.add_document(doc)
return some_model
build_model(tokenize(fetch_documents))
</code></pre>
<p>So this basically works fine, but doesn't utilize all the available processing capability. As dask is used in other related projects, I try to adapt and get this (I am using psycopg2 for database access).</p>
<pre><code>from dask import delayed
import psycopg2
import psycopg2.extras
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
def loader():
conn = psycopg2.connect()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute('''
SELECT document, ... FROM ...
''')
return cur
@delayed
def tokenize(partition):
result = []
client = IndicesClient(Elasticsearch())
for row in partition:
_result = client.analyze(analyzer='standard', text=row['document'])
result.append(dict(row,
tokens=tuple(item['token'] for item in _result['tokens'])))
return result
@delayed
def build_model(sequence_of_data):
some_model = SomeModel()
for item in chain.from_iterable(sequence_of_data):
some_model.add_document(item)
return some_model
with loader() as cur:
partitions = []
for idx_start in range(0, cur.rowcount, 200):
partitions.append(delayed(cur.fetchmany)(200))
tokenized = []
for partition in partitions:
tokenized.append(tokenize(partition))
result = do_something(tokenized)
result.compute()
</code></pre>
<p>Code more or less work, except at the end all documents are tokenized, before being fed into the model. While this works for smaller collection of data, however not for a huge collection of data (due to huge memory consumption). Should I just use plain <code>concurrent.futures</code> for this work or am I using dask wrongly?</p>
| 1 | 2016-08-15T03:33:23Z | 38,975,189 | <p>A simple solution would be to load data locally on your machine (it's hard to partition a single SQL query) and then send the data to the dask-cluster for the expensive tokenization step. Perhaps something as follows:</p>
<pre><code>rows = cur.execute(''' SELECT document, ... FROM ... ''')
from toolz import partition_all, concat
partitions = partition_all(10000, rows)
from dask.distributed import Executor
e = Executor('scheduler-address:8786')
futures = []
for part in partitions:
x = e.submit(tokenize, part)
y = e.submit(process, x)
futures.append(y)
results = e.gather(futures)
result = list(concat(results))
</code></pre>
<p>In this example the functions tokenize and process expect to consume and return a list of elements.</p>
| 1 | 2016-08-16T12:39:28Z | [
"python",
"python-3.x",
"dask"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></pre>
| 0 | 2016-08-15T03:37:23Z | 38,949,122 | <p>you can modify this a bit for accepting input from a text file</p>
<pre><code>var letterArray = "asdf\njkasdf\nthe\nsadf".split('\n');
function count(letterArray) {
let mapping = {};
for (let i=0; i < letterArray.length; i++){
if (mapping[letterArray[i]] !== undefined){ // if the letter already exists in the mapping increment it
mapping[letterArray[i]] += 1;
}else { //if the letter does not exist add it and initialize it
mapping[letterArray[i]] = 1;
}
}
return mapping;
}
console.log("count: ", count(letterArray));
</code></pre>
| 0 | 2016-08-15T03:58:15Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></pre>
| 0 | 2016-08-15T03:37:23Z | 38,949,141 | <p>I used python approach to get what you expected</p>
<pre><code>import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
def wordcount(data):
cv = CountVectorizer(min_df=0, strip_accents="ascii", decode_error ="ignore")
counts = cv.fit_transform([data]).toarray().ravel()
words = np.array(cv.get_feature_names())
counts = map(int, counts)
words = [i.tolist() for i in words]
words = [x.encode('UTF8') for x in words]
unsorted_result = zip(words, counts)
print sorted(unsorted_result,key=lambda x: x[1], reverse=True)
</code></pre>
<p>Send you data as a string to this function</p>
| 0 | 2016-08-15T04:00:32Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></pre>
| 0 | 2016-08-15T03:37:23Z | 38,949,164 | <p>I'd recommend doing this is java. It has better tools than javascript, but this can also be done in javascript. Load the whole list into an array. Then use a sort method to sort the entire list. In js its just .sort(). This will put words that are the same next to each other in the list. Then use a loop to walk this list from top to bottom. You will need two variables, lastWord and currentWord. Everytime the word changes put the last word into an new array along with how many times you saw it. You'll obviously also need a counter variable. So you'll be walking your sorted array and dumping results into another one. You'll also need logic that detects when you hit the end of the list so you can write the last world. This is the kind of problem that you'll often see in programming classes in school. Have fun.</p>
| -2 | 2016-08-15T04:03:39Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></pre>
| 0 | 2016-08-15T03:37:23Z | 38,949,183 | <p>In Node.js and after doing <code>npm i split2 through2 -S</code></p>
<pre><code>const fs = require('fs')
const split = require('split2')
const through = require('through2')
const words = {}
fs.createReadStream('words.txt')
.pipe(split())
.pipe(through(write, end))
function write (buf, enc, next) {
const word = buf.toString()
words[word] = ++words[word] || 1
next()
}
function end () {
Object.keys(words)
.sort((a, b) => words[b] - words[a])
.forEach(word => {
console.log(`${word}: ${words[word]} times`)
})
}
</code></pre>
| 5 | 2016-08-15T04:05:53Z | [
"javascript",
"python"
] |
How do I make a word list into an order by most used to least? | 38,948,988 | <p>So I have a file of 100000 words. I'm wondering how I can make it so it creates a file saying "the: 10282 times" "and: 322 times" "sadfas222: 1 times"</p>
<p>This is what the text file look likes:</p>
<pre><code>asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf
</code></pre>
| 0 | 2016-08-15T03:37:23Z | 38,957,792 | <p>You can use <code>Counter</code> from <code>collections</code> module for that:</p>
<pre><code>content = open("textfile.txt").read()
from collections import Counter
c = Counter(content.splitlines())
for x in c.most_common():
print("{}: {} times".format(x[0], x[1]))
</code></pre>
<p>Usage:</p>
<pre><code>In [7]: contet = """asdf
...: jkasdf
...: the
...: sadf
...: asdn
...: 23kl
...: asdf
...: qer
...: f
...: asdf
...: r
...: 2
...: r
...: fsd
...: fa
...: sdf
...: asd
...: far2
...: sdv
...: as
...: df
...: asdf
...: asdf"""
In [8]: from collections import Counter
In [9]: c = Counter(content.splitlines())
In [10]: c.most_common()
Out[10]:
[('asdf', 5),
('r', 2),
('f', 1),
('23kl', 1),
('as', 1),
('df', 1),
('sadf', 1),
('qer', 1),
('sdf', 1),
('jkasdf', 1),
('sdv', 1),
('the', 1),
('2', 1),
('fsd', 1),
('asdn', 1),
('fa', 1),
('asd', 1),
('far2', 1)]
</code></pre>
<p>And loop over the results in c:</p>
<pre><code>In [11]: for x in c.most_common():
....: print("{}: {} times".format(x[0], x[1]))
....:
asdf: 5 times
r: 2 times
f: 1 times
23kl: 1 times
as: 1 times
df: 1 times
sadf: 1 times
qer: 1 times
sdf: 1 times
jkasdf: 1 times
sdv: 1 times
the: 1 times
2: 1 times
fsd: 1 times
asdn: 1 times
fa: 1 times
asd: 1 times
far2: 1 times
</code></pre>
| 0 | 2016-08-15T15:09:11Z | [
"javascript",
"python"
] |
creating a dictionary of words in string whose values are words following that word | 38,948,999 | <p>I would like to create a dictionary from a text file using each unique word as a key and a a dictionary of the words that follow the key with the count of that word as the value. For example something that looks like this:</p>
<pre><code>>>>string = 'This is a string'
>>>word_counts(string)
{'this': {'is': 1}, 'is': {'a': 1}, 'a': {'string': 1}}
</code></pre>
<p>Creating a dictionary of the unique words is no issue, it's creating the dictionary for the following word values I'm stuck on. I can't use an list.index() operation in case there are word repeats. Outside of that I am kind of at a loss. </p>
| 0 | 2016-08-15T03:38:14Z | 38,949,059 | <p>You can make use of <a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow"><code>Counter</code></a> to achieve what you want:</p>
<pre><code>from collections import Counter, defaultdict
def get_tokens(string):
return string.split() # put whatever token-parsing algorithm you want here
def word_counts(string):
tokens = get_tokens(string)
following_words = defaultdict(list)
for i, token in enumerate(tokens):
if i:
following_words[tokens[i - 1]].append(token)
return {token: Counter(words) for token, words in following_words.iteritems()}
string = 'this is a string'
print word_counts(string) # {'this': Counter({'is': 1}), 'a': Counter({'string': 1}), 'is': Counter({'a': 1})}
</code></pre>
| 1 | 2016-08-15T03:48:51Z | [
"python",
"dictionary",
"word-count"
] |
creating a dictionary of words in string whose values are words following that word | 38,948,999 | <p>I would like to create a dictionary from a text file using each unique word as a key and a a dictionary of the words that follow the key with the count of that word as the value. For example something that looks like this:</p>
<pre><code>>>>string = 'This is a string'
>>>word_counts(string)
{'this': {'is': 1}, 'is': {'a': 1}, 'a': {'string': 1}}
</code></pre>
<p>Creating a dictionary of the unique words is no issue, it's creating the dictionary for the following word values I'm stuck on. I can't use an list.index() operation in case there are word repeats. Outside of that I am kind of at a loss. </p>
| 0 | 2016-08-15T03:38:14Z | 38,949,102 | <p>Actually, the <a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow"><code>collections.Counter</code></a> class isn't always the best choice to count something. You can use <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a>:</p>
<pre><code>from collections import defaultdict
def bigrams(text):
words = text.strip().lower().split()
counter = defaultdict(lambda: defaultdict(int))
for prev, current in zip(words[:-1], words[1:]):
counter[prev][current] += 1
return counter
</code></pre>
<p>Note that if your text contains punctuation marks as well, the line <code>words = text.strip().lower().split()</code> should be substituted with <code>words = re.findall(r'\w+', text.lower())</code>.</p>
<p>And if your text is so huge that the performance matters, you may consider the <code>pairwise</code> recipe from <a href="https://docs.python.org/2.7/library/itertools.html" rel="nofollow"><code>itertools</code> docs</a> or, if you're using python2, <code>itertools.izip</code> instead of <code>zip</code>.</p>
| 2 | 2016-08-15T03:55:09Z | [
"python",
"dictionary",
"word-count"
] |
creating a dictionary of words in string whose values are words following that word | 38,948,999 | <p>I would like to create a dictionary from a text file using each unique word as a key and a a dictionary of the words that follow the key with the count of that word as the value. For example something that looks like this:</p>
<pre><code>>>>string = 'This is a string'
>>>word_counts(string)
{'this': {'is': 1}, 'is': {'a': 1}, 'a': {'string': 1}}
</code></pre>
<p>Creating a dictionary of the unique words is no issue, it's creating the dictionary for the following word values I'm stuck on. I can't use an list.index() operation in case there are word repeats. Outside of that I am kind of at a loss. </p>
| 0 | 2016-08-15T03:38:14Z | 38,949,156 | <p>Just to give an alternative option (I imagine the other answers are more suitable for your needs) you could use the <code>pairwise</code> recipe from <code>itertools</code>:</p>
<pre><code>from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
</code></pre>
<p>Then the function can be coded as:</p>
<pre><code>def word_counts(string):
words = string.split()
result = defaultdict(lambda: defaultdict(int))
for word1, word2 in pairwise(words):
result[word1][word2] += 1
return result
</code></pre>
<p>Test:</p>
<pre><code>string = 'This is a string is not an int is a string'
print word_counts(string)
</code></pre>
<p>Produces:</p>
<pre><code>{'a': {'string': 2}, 'string': {'is': 1}, 'This': {'is': 1}, 'is': {'a': 2, 'not': 1}, 'an': {'int': 1}, 'int': {'is': 1}, 'not': {'an': 1}}
</code></pre>
| 0 | 2016-08-15T04:02:04Z | [
"python",
"dictionary",
"word-count"
] |
Linear and Quadratic terms in CPLEX Objective Function | 38,949,055 | <p>I would like to minimize an objective function which is rather simple, but I am somehow having problems making the correct calls to from the Python API to CPLEX</p>
<p>I looked at how to use <code>set_quadratic</code> and <code>set_quadratic_coefficients</code> <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.4.0/ilog.odms.cplex.help/refpythoncplex/html/cplex._internal._subinterfaces.ObjectiveInterface-class.html" rel="nofollow">here</a> but that didn't result in a solution to my problem.</p>
<p>My objective function has a set of linear variables and a set of quadratic variables</p>
<pre><code>varCoefs = [1]*(numB + numQ)
varLower = [0]*(numB + numQ)
varNames = [(x,"b%s"%x) for x in range( numB )]
varNames += [(len(varNames) + x,"q%s"%x) for x in range( numQ )]
varCoefs += [10]*len(deltas)
varLower += [1]*len(deltas)
varNames += [(len(varNames) + x,"delta%s"%x) for x in range( len(deltas) )]
varCoefs += [0]*len(target.v)
varLower += [0]*len(target.v)
sContent = [(len(varNames) + x,"s%s"%x) for x in range( len(target.v) )]
varNames += sContent
varCoefs += [-1]
varLower += [0]
varNames += [(len(varNames),'mu')]
problem.variables.add(obj = varCoefs, lb = varLower)
problem.variables.set_names(varNames)
# problem.objective.set_quadratic_coefficients([[['s%s' % x], [1]] for x in range( len(target.v) )])
problem.objective.set_quadratic(
[cplex.SparsePair(ind=[sContent[x][0]], val=[1]) for x in range( len(target.v) )]
)
</code></pre>
<p>Everything works up to the last call add the quadratic terms. At which point CPLEX throws the following error <code>CPLEX Error 1226: Array entry 13919 not ascending.</code> twice, ignoring the command, and the Python code continues.</p>
<p>I looked up the <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.4.0/ilog.odms.cplex.help/refcallablelibrary/html/macros/CPXERR_ARRAY_NOT_ASCENDING.html" rel="nofollow" title="error">error</a>, but that didn't seem to help me either. </p>
<p>I did try re-writing the above to add the variables by name and lower bound first... and then call <code>set_linear</code> and <code>set_quadratic</code> afterward, but that doesn't help either.</p>
<p>What am I missing here?</p>
| 0 | 2016-08-15T03:48:12Z | 38,959,192 | <p>If you're calling <code>set_quadratic</code> with a quadratic objective function that is separable, it corresponds to <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refcallablelibrary/qpapi/copyqpsep.html?pos=3" rel="nofollow">CPXXcopyqpsep</a>. If you're calling <code>set_quadratic</code> with a quadratic objective function that is inseparable, it corresponds to <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refcallablelibrary/qpapi/copyquad.html?pos=3" rel="nofollow">CPXXcopyquad</a>. I agree that the error you're getting is not particularly useful, but it makes a bit more sense if you know where it's coming from in the Callable C Library.</p>
<p>With that said, here's a complete example, using your snippet, with some dummy inputs:</p>
<pre><code>import cplex
class MockTarget(object):
pass
# Dummy data for testing
numB = 3
numQ = 3
deltas = [0.1, 0.1, 0.1]
problem = cplex.Cplex()
target = MockTarget()
target.v = [1, 2, 3]
# Build the problem
varCoefs = [1]*(numB + numQ)
varLower = [0]*(numB + numQ)
varNames = [(x,"b%s"%x) for x in range( numB )]
varNames += [(len(varNames) + x,"q%s"%x) for x in range( numQ )]
varCoefs += [10]*len(deltas)
varLower += [1]*len(deltas)
varNames += [(len(varNames) + x,"delta%s"%x) for x in range( len(deltas) )]
varCoefs += [0]*len(target.v)
varLower += [0]*len(target.v)
sContent = [(len(varNames) + x,"s%s"%x) for x in range( len(target.v) )]
varNames += sContent
varCoefs += [-1]
varLower += [0]
varNames += [(len(varNames),'mu')]
problem.variables.add(obj = varCoefs, lb = varLower)
problem.variables.set_names(varNames)
# Print without quadratic terms so you can see the progression.
problem.write('test1.lp')
# Separable Q
qsepvec = []
for tpl in varNames:
if tpl in sContent:
qsepvec.append(1.0)
else:
qsepvec.append(0.0)
print qsepvec
problem.objective.set_quadratic(qsepvec)
problem.write('test2.lp')
# Inseparable Q (overwrites previous Q)
qmat = []
for tpl in varNames:
if tpl in sContent:
sp = cplex.SparsePair(ind=[tpl[0]], val=[1.0])
qmat.append(sp)
else:
sp = cplex.SparsePair(ind=[], val=[])
qmat.append(sp)
print qmat
problem.objective.set_quadratic(qmat)
problem.write('test3.lp')
</code></pre>
<p>I've written that out in long form rather than using list comprehensions to make it a bit more clear. The contents of the the LP files are below:</p>
<p>test1.lp:</p>
<pre><code>\ENCODING=ISO-8859-1
\Problem name:
Minimize
obj: b0 + b1 + b2 + q0 + q1 + q2 + 10 delta0 + 10 delta1 + 10 delta2 + 0 s0
+ 0 s1 + 0 s2 - mu
Bounds
delta0 >= 1
delta1 >= 1
delta2 >= 1
End
</code></pre>
<p>test2.lp</p>
<pre><code>\ENCODING=ISO-8859-1
\Problem name:
Minimize
obj: b0 + b1 + b2 + q0 + q1 + q2 + 10 delta0 + 10 delta1 + 10 delta2 + 0 s0
+ 0 s1 + 0 s2 - mu + [ s0 ^2 + s1 ^2 + s2 ^2 ] / 2
Bounds
delta0 >= 1
delta1 >= 1
delta2 >= 1
End
</code></pre>
<p>test3.lp</p>
<pre><code>\ENCODING=ISO-8859-1
\Problem name:
Minimize
obj: b0 + b1 + b2 + q0 + q1 + q2 + 10 delta0 + 10 delta1 + 10 delta2 + 0 s0
+ 0 s1 + 0 s2 - mu + [ s0 ^2 + s1 ^2 + s2 ^2 ] / 2
Bounds
delta0 >= 1
delta1 >= 1
delta2 >= 1
End
</code></pre>
<p>You can see that test2.lp and test3.lp are the same (the later overwrites the former, but does the same thing). Hopefully that makes it a bit easier to understand. In general, using this technique of printing out LP's for very simple problems, is one of the more useful debugging techniques.</p>
<p>You should also check out the python examples that are shipped with CPLEX. For example, qpex1.py, miqpex1.py, indefqpex1.py.</p>
| 1 | 2016-08-15T16:39:23Z | [
"python",
"linear-programming",
"cplex",
"quadratic-programming"
] |
Linear and Quadratic terms in CPLEX Objective Function | 38,949,055 | <p>I would like to minimize an objective function which is rather simple, but I am somehow having problems making the correct calls to from the Python API to CPLEX</p>
<p>I looked at how to use <code>set_quadratic</code> and <code>set_quadratic_coefficients</code> <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.4.0/ilog.odms.cplex.help/refpythoncplex/html/cplex._internal._subinterfaces.ObjectiveInterface-class.html" rel="nofollow">here</a> but that didn't result in a solution to my problem.</p>
<p>My objective function has a set of linear variables and a set of quadratic variables</p>
<pre><code>varCoefs = [1]*(numB + numQ)
varLower = [0]*(numB + numQ)
varNames = [(x,"b%s"%x) for x in range( numB )]
varNames += [(len(varNames) + x,"q%s"%x) for x in range( numQ )]
varCoefs += [10]*len(deltas)
varLower += [1]*len(deltas)
varNames += [(len(varNames) + x,"delta%s"%x) for x in range( len(deltas) )]
varCoefs += [0]*len(target.v)
varLower += [0]*len(target.v)
sContent = [(len(varNames) + x,"s%s"%x) for x in range( len(target.v) )]
varNames += sContent
varCoefs += [-1]
varLower += [0]
varNames += [(len(varNames),'mu')]
problem.variables.add(obj = varCoefs, lb = varLower)
problem.variables.set_names(varNames)
# problem.objective.set_quadratic_coefficients([[['s%s' % x], [1]] for x in range( len(target.v) )])
problem.objective.set_quadratic(
[cplex.SparsePair(ind=[sContent[x][0]], val=[1]) for x in range( len(target.v) )]
)
</code></pre>
<p>Everything works up to the last call add the quadratic terms. At which point CPLEX throws the following error <code>CPLEX Error 1226: Array entry 13919 not ascending.</code> twice, ignoring the command, and the Python code continues.</p>
<p>I looked up the <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.4.0/ilog.odms.cplex.help/refcallablelibrary/html/macros/CPXERR_ARRAY_NOT_ASCENDING.html" rel="nofollow" title="error">error</a>, but that didn't seem to help me either. </p>
<p>I did try re-writing the above to add the variables by name and lower bound first... and then call <code>set_linear</code> and <code>set_quadratic</code> afterward, but that doesn't help either.</p>
<p>What am I missing here?</p>
| 0 | 2016-08-15T03:48:12Z | 38,960,501 | <p>I solved the problem by adding the quadratic terms first, setting their coefficients, and then adding the linear terms in a separate call see below.</p>
<pre><code>problem.objective.set_sense(problem.objective.sense.minimize)
varLower = [0]*len(target.v)
varNames = ["s%s"%x for x in range( len(target.v) )]
problem.variables.add(names=varNames, lb=varLower)
problem.objective.set_quadratic(
[[[x],[1]] for x in range( len(target.v) )]
)
varCoefs = [-1]
varLower = [0]
varNames = ['mu']
varCoefs += [1]*(numB + numQ)
varLower += [0]*(numB + numQ)
varNames += ["b%s"%x for x in range( numB )]
varNames += ["q%s"%x for x in range( numQ )]
varCoefs += [10]*len(deltas)
varLower += [1]*len(deltas)
varNames += ["delta%s"%x for x in range( len(deltas) )]
problem.variables.add(names=varNames, lb=varLower, obj=varCoefs)
</code></pre>
<p>However, I would still like to know why it works this way, and not the other way.</p>
| 0 | 2016-08-15T18:07:33Z | [
"python",
"linear-programming",
"cplex",
"quadratic-programming"
] |
How to submit a POST request to the Calls resource? (making outgoing calls in Twilio) | 38,949,066 | <p>I'm having trouble with making outgoing calls using Twilio and I believe I skipped this step where I should submit a POST request to the Calls resource. I don't really understand what to do with this and I need someone to explain it for me since I'm just a beginner. And by the way, my Twilio account is just free trial. Does this have something to do as to why I can't make local calls?</p>
<p>Thanks.</p>
| 0 | 2016-08-15T03:50:07Z | 38,952,309 | <p>Twilio developer evangelist here.</p>
<p>Best place for you to start would be the <a href="https://www.twilio.com/docs/quickstart/python/rest" rel="nofollow">Python making calls quick start</a>. Follow that tutorial through and you should understand how to make a call with Python.</p>
<p>Though, as you say, the key is the <a href="https://www.twilio.com/docs/api/rest/making-calls" rel="nofollow">POST request to the calls resource</a>. It's easiest to perform this using our <a href="https://www.twilio.com/docs/libraries/python" rel="nofollow">Python helper library</a> and looks a bit like this:</p>
<pre><code>from twilio.rest import TwilioRestClient
# Get these credentials from http://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
client = TwilioRestClient(account_sid, auth_token)
# Make the call
call = client.calls.create(to="+14085551234", # Any phone number
from_="+12125551234", # Must be a valid Twilio number
url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient") # Just plays hold music
</code></pre>
<p>Let me know if that helps at all.</p>
| 0 | 2016-08-15T09:11:39Z | [
"python",
"twilio",
"twilio-click-to-call"
] |
Overriding get_queryset leads to caching headache in ListView, where data remains stale | 38,949,071 | <p>Could someone explain why overriding <code>get_queryset</code> and referencing the queryset via <code>self</code> completely caches the page? I need to wait 5 minutes or more before updates made to the database display.</p>
<p>I'm trying to save a temporary value to the each object and pass it to the template.</p>
<p>I've got everything working fine and dandy in example 3 but don't really understand what I did to make it work, so any insight would be great!</p>
<h1>Example 1: Caches for several minutes, but r.css='abc' work ok</h1>
<pre><code>class AppointmentListView(ListView):
qs = Appointment.objects.prefetch_related('client', 'patients')
def get_queryset(self):
for r in self.qs:
r.css = 'abc' #<-passes temp value to template ok
return self.qs
</code></pre>
<h1>Example 2: No caching problem but r.css='abc' now does not work</h1>
<p>If I don't include a method and just have the queryset called automatically, there is no caching and database updates display immediately, but my temp data does not reach template.
class AppointmentListView(ListView):</p>
<pre><code> queryset = Appointment.objects.prefetch_related('client','patients')
for r in queryset:
r.css = 'abc' #<- NOT passed to template
</code></pre>
<h1>Example 3: No caching problem AND r.css='abc' works fine</h1>
<p>Finally if I put everything in the method, it all works fine - temp data reaches the template and there's no caching.</p>
<pre><code>class AppointmentListView(ListView):
def get_queryset(self):
qs = Appointment.objects.prefetch_related('client','patients')
for r in qs:
r.css = 'abc' #<-passes to template ok
return qs
</code></pre>
| 1 | 2016-08-15T03:50:44Z | 38,950,201 | <p>The behavior you're seeing is how Python evaluates your code. Below is a simplified example that explains what you're seeing.</p>
<pre><code>import random
class Example1(object):
roll = random.randint(1, 6) # this is evaluated immediately!
def get_roll(self):
return self.roll
ex1 = Example1()
# the call below always returns the same number!
# (until Python re-interprets the class)
ex1.get_roll()
</code></pre>
<p>If you type the code above into a python interpreter, you'll notice that <code>ex1.get_roll()</code> always returns the same number!</p>
<p><code>Example1.roll</code> is known as a class or static variable. These are evaluated only once when the class is defined. </p>
<pre><code>class Example2(object):
def get_number(self):
roll = random.randint(1,6)
return roll
</code></pre>
<p>In <code>Example2</code>, a new random number is generated everytime <code>get_roll</code> method is called.</p>
<p>For the examples listed in your question:</p>
<p><strong>Example 1</strong> </p>
<p><code>qs</code> is a class variable, and thus only gets evaluated once (which is why you see the "caching" behavior). Subsequent calls to <code>get_queryset</code> returns the same <code>qs</code> variable that was initially evaluated.</p>
<p><strong>Example 2</strong></p>
<p>You didn't override <code>get_queryset</code>, which means <code>ListView.get_queryset</code> implementation is used. </p>
<p>Django's <code>ListView.get_queryset</code> copies the <code>queryset</code> before evaluating it - which is why you don't see "caching". However, because the queryset is copied, the effects from your for loop is thrown away.</p>
<p><strong>Example 3</strong></p>
<p>This is generally the correct way to write your code. You should write your methods like this if you don't want to see "caching" behavior.</p>
| 1 | 2016-08-15T06:22:20Z | [
"python",
"django",
"django-templates",
"django-queryset"
] |
python lxml.html.soupparser.fromstring raising annoying warning | 38,949,091 | <p>My code...</p>
<pre><code>foo = fromstring(my_html)
</code></pre>
<p>it raises this warning...</p>
<pre><code>UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
To get rid of this warning, change this:
BeautifulSoup([your markup])
to this:
BeautifulSoup([your markup], "html.parser")
markup_type=markup_type))
</code></pre>
<p>I have tried passing it the string <code>'html.parser'</code> but that does not work as it gives me an error saying that the string is not a callable so I tried <code>html.parser</code> and then I looked through the lxml module to see if I could find another parser, and couldn't. I looked through the python stdlib and saw that in 2.7 there is one called <code>HTMLParser</code> so I imported that and input the <code>beautifulsoup=HTMLParser</code> and that did not work either.</p>
<p>Where is the callable that I should be passing to <code>fromstring</code>?</p>
<p>EDIT added attempted solutions:</p>
<pre><code>from lxml.html.soupparser import fromstring
wiktionary_page = fromstring(wiktionary_page.read(), features="html.parser" )
</code></pre>
<p>and this</p>
<pre><code>from lxml.html.soupparser import BeautifulSoup
wiktionary_page = fromstring(wiktionary_page.read(), beautifulsoup=lambda s: BeautifulSoup(s, "html.parser"))
</code></pre>
| 3 | 2016-08-15T03:52:35Z | 38,950,833 | <p>You can pass the <em>features</em> keyword which will set the parser.</p>
<pre><code>tree = lxml.html.soupparser.fromstring("<p>foo</p>", features="html.parser" )
</code></pre>
<p>What happens in <em>fromstring</em> is <em>_parser</em> gets called but I think there is a bug in the line <em>bsargs['features'] = ['html.parser']</em>, it should be <code>bsargs['features'] = 'html.parser'</code>:</p>
<pre><code>def _parse(source, beautifulsoup, makeelement, **bsargs):
if beautifulsoup is None:
beautifulsoup = BeautifulSoup
if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3
if 'convertEntities' not in bsargs:
bsargs['convertEntities'] = 'html'
if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"): # bs4
if 'features' not in bsargs:
bsargs['features'] = ['html.parser'] # use Python html parser
tree = beautifulsoup(source, **bsargs)
root = _convert_tree(tree, makeelement)
# from ET: wrap the document in a html root element, if necessary
if len(root) == 1 and root[0].tag == "html":
return root[0]
root.tag = "html"
return root
</code></pre>
<p>You could also use a lambda:</p>
<pre><code>from lxml.html.soupparser import BeautifulSoup
import lxml.html.soupparser
tree = lxml.html.soupparser.fromstring("<p>foo</p>", beautifulsoup=lambda s: BeautifulSoup(s, "html.parser"))
</code></pre>
<p>Both suppress any warnings:</p>
<pre><code>In [13]: from lxml.html import soupparser
In [14]: tree = soupparser.fromstring("<p>foo</p>", features="html.parser" )
In [15]: from lxml.html.soupparser import BeautifulSoup
In [16]: import lxml.html.soupparser
In [17]: tree = lxml.html.soupparser.fromstring("<p>foo</p>", beautifulsoup=lambda s: BeautifulSoup(s, "html.parser"))
</code></pre>
| 3 | 2016-08-15T07:20:00Z | [
"python",
"beautifulsoup",
"lxml"
] |
Why does running `airflow clear` using the -t option raise a thread error? | 38,949,147 | <p>I've constructed an Airflow DAG with default settings as the tutorial. When I run the DAG, some tasks failed. When I attempt to clear the failed tasks using <code>airflow clear my_dag -s 2016-08-03 -t my_task_name -fd</code>, I get the following exception:</p>
<pre><code>TypeError: object.__new__(thread.lock) is not safe, use thread.lock.__new__()
</code></pre>
<p>Is this an issue with Airflow itself, or is it something on my side?</p>
<p>The full backtrace is:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/bin/airflow", line 15, in <module>
args.func(args)
File "/usr/local/lib/python2.7/dist-packages/airflow/bin/cli.py", line 379, in clear
include_upstream=args.upstream,
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 2870, in sub_dag
dag = copy.deepcopy(self)
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 2856, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1974, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 2856, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1974, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 329, in _reconstruct
y = callable(*args)
File "/usr/lib/python2.7/copy_reg.py", line 93, in __newobj__
return cls.__new__(cls, *args)
TypeError: object.__new__(thread.lock) is not safe, use thread.lock.__new__()
</code></pre>
| -1 | 2016-08-15T04:01:26Z | 38,963,444 | <p>Don't use deepcopy (it is almost always certainly wrong). deepcopy will copy all referred to objects; in this case your object graph has some locks; they are not copiable by deepcopy and thus you get the error.</p>
<p><a href="http://stackoverflow.com/questions/29267261/object-new-thread-lock-is-not-safe-use-thread-lock-new">Same question</a></p>
| 0 | 2016-08-15T21:36:35Z | [
"python",
"airflow"
] |
Why does running `airflow clear` using the -t option raise a thread error? | 38,949,147 | <p>I've constructed an Airflow DAG with default settings as the tutorial. When I run the DAG, some tasks failed. When I attempt to clear the failed tasks using <code>airflow clear my_dag -s 2016-08-03 -t my_task_name -fd</code>, I get the following exception:</p>
<pre><code>TypeError: object.__new__(thread.lock) is not safe, use thread.lock.__new__()
</code></pre>
<p>Is this an issue with Airflow itself, or is it something on my side?</p>
<p>The full backtrace is:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/bin/airflow", line 15, in <module>
args.func(args)
File "/usr/local/lib/python2.7/dist-packages/airflow/bin/cli.py", line 379, in clear
include_upstream=args.upstream,
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 2870, in sub_dag
dag = copy.deepcopy(self)
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 2856, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1974, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 2856, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1974, in __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 329, in _reconstruct
y = callable(*args)
File "/usr/lib/python2.7/copy_reg.py", line 93, in __newobj__
return cls.__new__(cls, *args)
TypeError: object.__new__(thread.lock) is not safe, use thread.lock.__new__()
</code></pre>
| -1 | 2016-08-15T04:01:26Z | 38,964,621 | <p>Looks like this is an open issue for Airflow: <a href="https://issues.apache.org/jira/browse/AIRFLOW-351" rel="nofollow">https://issues.apache.org/jira/browse/AIRFLOW-351</a></p>
| 0 | 2016-08-15T23:45:36Z | [
"python",
"airflow"
] |
How to create a code that will append items to a list in python | 38,949,161 | <p>Hi I am trying to create a code that will append items to a list in python through the program itself inside of terminal. </p>
<p>Whenever I use this code it works but when I stop running the code and rerun the new item in the list is gone.</p>
<p>This is currently my code. 'Calc' is a list that has multiple strings so I want to add another item to that list whenever they type that into terminal.</p>
<pre><code>elif userInput in command:
print("Okay, Initializing new command.\n\n")
command1 = raw_input("Which command would you like to add?\nKeyword\nLater Versions\n ").lower()
if command1 == 'keyword':
print('You selected keyword, to exit press enter')
command2 = raw_input("Which Keyword would you like to edit? ")
if command2 == 'calc':
command3 = raw_input("Which Keyword would you like to add? ")
calc.append(command3)
print(calc)
</code></pre>
| -2 | 2016-08-15T04:03:24Z | 38,949,201 | <p>When you re-run, the list is re-initiazing and clearing itself. </p>
<p>One way to save the contents of the list for multiple runs of the code would be to write the contents of the list to a text file and save that. </p>
<p>You can read <a href="http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python/%22Reading%20and%20Writing%20Files%20in%20Python%20for%20Beginners%22" rel="nofollow">www.pythonforbeginners.com/files/reading-and-writing-files-in-python</a> for a basic rundown on how to do that.</p>
| 1 | 2016-08-15T04:08:30Z | [
"python"
] |
pandas DataFrame sort rows by duplicate | 38,949,190 | <p>How can I sort a DataFrame so that rows in the duplicate column are "recycled". </p>
<p>For example, my original DataFrame looks like this:</p>
<pre><code>In [3]: df
Out[3]:
A B
0 r1 0
1 r1 1
2 r2 2
3 r2 3
4 r3 4
5 r3 5
</code></pre>
<p>I would like it to turn to:</p>
<pre><code>In [3]: df_sorted
Out[3]:
A B
0 r1 0
2 r2 2
4 r3 4
1 r1 1
3 r2 3
5 r3 5
</code></pre>
<p>rows are sorted such that rows in columns <code>A</code> are in a "recycled" fashion.</p>
<p>I have searched APIs in Pandas, but seems there isn't any proper method to do so. I can write a complicated function to accomplish this, but just wondering is there any smart way or existing pandas method can do this? Thanks a lot in advance.</p>
<p>Update:
Apologies for a wrong statement. In my real problem, column <code>B</code> contains string values.</p>
| 3 | 2016-08-15T04:06:35Z | 38,949,542 | <p>You can formulate your need as taking the first row of each group, then the second line, then the thrid, etc. So this is equivalent to group your results by row per group and then per <code>'A'</code> .</p>
<p>You can number your rows per key in <code>'A'</code> with the function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rank.html" rel="nofollow"><code>rank</code></a>. Apply this function on each group and you are done:</p>
<pre><code>df['C'] = df.groupby('A')['B'].rank()
df
Out[8]:
A B C
0 r1 0 1.0
1 r1 1 2.0
2 r2 2 1.0
3 r2 3 2.0
4 r3 4 1.0
5 r3 5 2.0
df.sort_values(['C', 'A'])
Out[9]:
A B C
0 r1 0 1.0
2 r2 2 1.0
4 r3 4 1.0
1 r1 1 2.0
3 r2 3 2.0
5 r3 5 2.0
</code></pre>
<p>You drop <code>'C'</code> if you don't need it.</p>
<hr>
<p><strong>Edit to follow up on a comment</strong></p>
<p>I take for granted in your sample <code>'B'</code> is your index column. If it's not then you need to work on the index itself:</p>
<pre><code>df['C'] = df.reset_index().groupby('A')['index'].rank()
</code></pre>
| 4 | 2016-08-15T05:01:48Z | [
"python",
"sorting",
"pandas",
"dataframe",
"duplicates"
] |
pandas DataFrame sort rows by duplicate | 38,949,190 | <p>How can I sort a DataFrame so that rows in the duplicate column are "recycled". </p>
<p>For example, my original DataFrame looks like this:</p>
<pre><code>In [3]: df
Out[3]:
A B
0 r1 0
1 r1 1
2 r2 2
3 r2 3
4 r3 4
5 r3 5
</code></pre>
<p>I would like it to turn to:</p>
<pre><code>In [3]: df_sorted
Out[3]:
A B
0 r1 0
2 r2 2
4 r3 4
1 r1 1
3 r2 3
5 r3 5
</code></pre>
<p>rows are sorted such that rows in columns <code>A</code> are in a "recycled" fashion.</p>
<p>I have searched APIs in Pandas, but seems there isn't any proper method to do so. I can write a complicated function to accomplish this, but just wondering is there any smart way or existing pandas method can do this? Thanks a lot in advance.</p>
<p>Update:
Apologies for a wrong statement. In my real problem, column <code>B</code> contains string values.</p>
| 3 | 2016-08-15T04:06:35Z | 38,949,547 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> for counting duplicates in column <code>A</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> first by <code>A</code> (in sample not necessary, in real data maybe important) and then by <code>C</code>. Last remove column <code>C</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a>:</p>
<pre><code>df['C'] = df.groupby('A')['A'].cumcount()
df.sort_values(by=['C', 'A'], inplace=True)
print (df)
A B C
0 r1 0 0
2 r2 2 0
4 r3 4 0
1 r1 1 1
3 r2 3 1
5 r3 5 1
df.drop('C', axis=1, inplace=True)
print (df)
A B
0 r1 0
2 r2 2
4 r3 4
1 r1 1
3 r2 3
5 r3 5
</code></pre>
<p><strong>Timings</strong>:</p>
<p>Small df (<code>len(df)=6</code>)</p>
<pre><code>In [26]: %timeit (jez(df))
1000 loops, best of 3: 2 ms per loop
In [27]: %timeit (boud(df1))
100 loops, best of 3: 2.52 ms per loop
</code></pre>
<p>Large df (<code>len(df)=6000</code>)</p>
<pre><code>In [23]: %timeit (jez(df))
100 loops, best of 3: 3.44 ms per loop
In [28]: %timeit (boud(df1))
100 loops, best of 3: 2.52 ms per loop
</code></pre>
<p>Code for timing:</p>
<pre><code>df = pd.concat([df]*1000).reset_index(drop=True)
df1 = df.copy()
def jez(df):
df['C'] = df.groupby('A')['A'].cumcount()
df.sort_values(by=['C', 'A'], inplace=True)
df.drop('C', axis=1, inplace=True)
return (df)
def boud(df):
df['C'] = df.groupby('A')['B'].rank()
df = df.sort_values(['C', 'A'])
df.drop('C', axis=1, inplace=True)
return (df)
100 loops, best of 3: 4.29 ms per loop
</code></pre>
| 2 | 2016-08-15T05:02:29Z | [
"python",
"sorting",
"pandas",
"dataframe",
"duplicates"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r") #opens file with name of "exiting.txt"
line1 = (f.readline())
line2 = (f.readline())
line3 = (f.readline())
line4 = (f.readline())
line5 = (f.readline())
line6 = (f.readline())
line7 = (f.readline())
ext = input("Enter a name to exit: ")
lst = [line1,line2,line3,line4,line5,line6,line7]
for line in lst:
line = line.replace("username",ext)
print(line1)
line1 = line1.replace("username",ext)
print(line1)
</code></pre>
<p>When I run this, I get the first print out exactly the same as it was before (and all the other lines are the same as well) and the second line is more like what I want</p>
<p>I want the for loop to loop over and over the lines replacing the word <code>username</code> with the actual username.</p>
<blockquote>
<p>Enter a name to exit: millingtonc</p>
<p>mkdir "\qnapnas01\archive\Data\Users\username"</p>
<p>mkdir "\qnapnas01\archive\Data\Users\millingtonc"</p>
</blockquote>
| -1 | 2016-08-15T04:10:19Z | 38,949,300 | <p>I think the problem is that you are changing the value of variable <code>l</code> instead of the <code>line1</code> in <code>lst</code> or variable <code>l1</code> itself. Following codes should help you do the trick:</p>
<pre><code>lst = [line1,line2,line3,line4,line5,line6,line7]
for i in range(len(lst)):
lst[i] = lst[i].replace("username",ext)
</code></pre>
<p>I am not sure the final results but the basic idea is you can change the value in list and actually replace the string that you ask for.</p>
| 0 | 2016-08-15T04:24:46Z | [
"python"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r") #opens file with name of "exiting.txt"
line1 = (f.readline())
line2 = (f.readline())
line3 = (f.readline())
line4 = (f.readline())
line5 = (f.readline())
line6 = (f.readline())
line7 = (f.readline())
ext = input("Enter a name to exit: ")
lst = [line1,line2,line3,line4,line5,line6,line7]
for line in lst:
line = line.replace("username",ext)
print(line1)
line1 = line1.replace("username",ext)
print(line1)
</code></pre>
<p>When I run this, I get the first print out exactly the same as it was before (and all the other lines are the same as well) and the second line is more like what I want</p>
<p>I want the for loop to loop over and over the lines replacing the word <code>username</code> with the actual username.</p>
<blockquote>
<p>Enter a name to exit: millingtonc</p>
<p>mkdir "\qnapnas01\archive\Data\Users\username"</p>
<p>mkdir "\qnapnas01\archive\Data\Users\millingtonc"</p>
</blockquote>
| -1 | 2016-08-15T04:10:19Z | 38,949,361 | <p>Changing the string in the for-loop won't change the <code>line1</code> variable. Also, you should probably find a better way to read from the file in the first place which could help you to avoid this problem. I suggested one way below but there are numerous other ways you can accomplish essentially the same thing.</p>
<pre><code>ext = input("Enter a name to exit: ")
with open("Exiting.txt", "r") as f:
lst = [f.readline() for _ in range(7)]
lst = [line.replace("username", ext) for line in lst]
print(lst)
</code></pre>
| 0 | 2016-08-15T04:33:12Z | [
"python"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r") #opens file with name of "exiting.txt"
line1 = (f.readline())
line2 = (f.readline())
line3 = (f.readline())
line4 = (f.readline())
line5 = (f.readline())
line6 = (f.readline())
line7 = (f.readline())
ext = input("Enter a name to exit: ")
lst = [line1,line2,line3,line4,line5,line6,line7]
for line in lst:
line = line.replace("username",ext)
print(line1)
line1 = line1.replace("username",ext)
print(line1)
</code></pre>
<p>When I run this, I get the first print out exactly the same as it was before (and all the other lines are the same as well) and the second line is more like what I want</p>
<p>I want the for loop to loop over and over the lines replacing the word <code>username</code> with the actual username.</p>
<blockquote>
<p>Enter a name to exit: millingtonc</p>
<p>mkdir "\qnapnas01\archive\Data\Users\username"</p>
<p>mkdir "\qnapnas01\archive\Data\Users\millingtonc"</p>
</blockquote>
| -1 | 2016-08-15T04:10:19Z | 38,949,373 | <p>Basically, you're overwriting a temporary variable (line) which only exists in the scope of the loop, so you're not seeing any changes to your other variables (line1, line2, etc.). So you need to store the replaced values in a separate list outside the loop, like so:</p>
<pre><code>replacedLines = []
for line in lst:
replacedLines.append(line.replace("username",ext))
</code></pre>
<p>Or, using a list comprehension:</p>
<pre><code>replacedList = [line.replace("username",ext) for line in lst]
</code></pre>
| 0 | 2016-08-15T04:35:00Z | [
"python"
] |
replace word in list of strings using python | 38,949,217 | <p>I have a script that I am trying to optimize for work and I basically need to replace the "username" in the script with the username of the person. I eventually want to do this over and over for a list of people but I am having trouble with what seems like a very basic part.</p>
<pre><code>f = open("Exiting.txt","r") #opens file with name of "exiting.txt"
line1 = (f.readline())
line2 = (f.readline())
line3 = (f.readline())
line4 = (f.readline())
line5 = (f.readline())
line6 = (f.readline())
line7 = (f.readline())
ext = input("Enter a name to exit: ")
lst = [line1,line2,line3,line4,line5,line6,line7]
for line in lst:
line = line.replace("username",ext)
print(line1)
line1 = line1.replace("username",ext)
print(line1)
</code></pre>
<p>When I run this, I get the first print out exactly the same as it was before (and all the other lines are the same as well) and the second line is more like what I want</p>
<p>I want the for loop to loop over and over the lines replacing the word <code>username</code> with the actual username.</p>
<blockquote>
<p>Enter a name to exit: millingtonc</p>
<p>mkdir "\qnapnas01\archive\Data\Users\username"</p>
<p>mkdir "\qnapnas01\archive\Data\Users\millingtonc"</p>
</blockquote>
| -1 | 2016-08-15T04:10:19Z | 38,949,375 | <p>I ended up fixing it thanks to Evert and cuongnv</p>
<pre><code>f = open("Exiting.txt","r") #opens the exitng.txt which has 7 lines
line1 = (f.readline())
line2 = (f.readline())
line3 = (f.readline())
line4 = (f.readline())
line5 = (f.readline())
line6 = (f.readline())
line7 = (f.readline())
f.close()
ext = input("Enter a name to exit: ")
lst = [line1,line2,line3,line4,line5,line6,line7]
lst2 = []
for i in lst:
i = i.replace("username",ext)
lst2.append(i)
for d in lst2:
print(d)
</code></pre>
| 0 | 2016-08-15T04:35:20Z | [
"python"
] |
Selenium. Upload a file on a new chrome open file pop up (or how to simulate ctrl+v on python) | 38,949,261 | <p>Im doing a python selenium script for chrome webdriver, and I need to upload a file. When I hit the upload buttom, a open file dialog pops up, and I haven't been able to actually upload the file. Aproaches I have tried: </p>
<p>Using selenium ide, and recording me uploading the file. It yeilds this result:</p>
<pre><code>driver.find_element_by_id("html5_1aq7art6u98a1i1eokfk581u443").clear()
driver.find_element_by_id("html5_1aq7art6u98a1i1eokfk581u443").send_keys("")
</code></pre>
<p>However, the id changes everytime the page is reloaded, and so this aproach doesnt work. I also haven't been able to find a way to locate the form to type the file name. </p>
<p>I also tried using alerts and changing window with selenium</p>
<pre><code>driver.switch_to_window("Open")
driver.send_keyssend_keys(os.getcwd()+"/file.png")
alert = driver.switch_to.alert
alert.send_keyssend_keys(os.getcwd()+"/file.png")
</code></pre>
<p>But both of this aproaches have failed. (the first one doesnt finds the window, and the second one tells me that no alert is open)</p>
<p>As a last resort Im searching how to copy to clipboard the name of the file, and after clicking the upload buttom, wating something like a second, and then simulating with python a "crtl+v" followed by "enter" key press, but I dont know how to do it, and the internet searchs take me to the dark path of some c based third party libraries that overwhelmed me a bit. </p>
<p>Here is the full code for the posting script, the rest of the code (before this part) its just scrapping and deleting my own post:</p>
<pre><code>driver.get('https://www.kijiji.ca/p-post-ad.html?categoryId=87')
time.sleep(2)
driver.find_element_by_css_selector("button.button--jss-0-514").click()
driver.find_element_by_id("postad-title").clear()
driver.find_element_by_id("postad-title").send_keys(postTitle)
driver.find_element_by_id("pstad-descrptn").clear()
driver.find_element_by_id("pstad-descrptn").send_keys(postContent)
driver.find_element_by_id("pstad-map-address").clear()
driver.find_element_by_id("pstad-map-address").send_keys(postAdress)
#driver.find_element_by_id("ImageUploadButton").click()
#time.sleep(2)
driver.find_element_by_xpath("//input[@type='file'][contains(@id,'html5_')]").clear()
driver.find_element_by_xpath("//input[@type='file'][contains(@id,'html5_')]").send_keys("file.png")
driver.find_element_by_id("PhoneNumber").clear()
driver.find_element_by_id("PhoneNumber").send_keys(phoneNumber)
driver.find_element_by_id("pstad-email").send_keys(profile)
driver.find_element_by_name("saveAndCheckout").click()
</code></pre>
<p>Full Error:
[10360:7760:0815/140356:ERROR:latency_info.cc(164)] RenderWidgetHostImpl::OnSwapCompositorFrame, LatencyInfo vector size 187 is too big.
[10360:7760:0815/140357:ERROR:latency_info.cc(164)] RenderWidgetHostImpl::OnSwapCompositorFrame, LatencyInfo vector size 452 is too big.
Traceback (most recent call last):
File "KijijiAutoPosting.py", line 95, in
driver.find_element_by_xpath("//input[@type='file'][contains(@id,'html5_')]").clear()
File "C:\Users\Silve\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 87, in clear
self._execute(Command.CLEAR_ELEMENT)
File "C:\Users\Silve\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 461, in _execute
return self._parent.execute(command, params)
File "C:\Users\Silve\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "C:\Users\Silve\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidElementStateException: Message: invalid element state: Element is not currently interactable and may not be manipulated
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64)</p>
| 1 | 2016-08-15T04:17:58Z | 38,949,325 | <p>Try following code:</p>
<pre><code>driver.find_element_by_xpath("//input[@type='file']").clear()
driver.find_element_by_xpath("//input[@type='file']").send_keys("/path/to/file")
</code></pre>
<p>This should work if there is only one button for file uploading. </p>
<p>Also you can try this <code>XPath</code>:</p>
<pre><code>"//input[@type='file'][contains(@id,'html5_')]"
</code></pre>
| 1 | 2016-08-15T04:28:31Z | [
"python",
"selenium",
"keyboard"
] |
TypeError: a float is required PYTHON | 38,949,294 | <p>My current python script:</p>
<pre><code>import ftplib
import hashlib
import httplib
import pytz
from datetime import datetime
import urllib
from pytz import timezone
import os.path, time
import glob
def ftphttp():
dataset_path='Desktop'
files = glob.glob(dataset_path+"/images/*.png")
ts = files.sort(key=os.path.getmtime)
dt = datetime.fromtimestamp(ts, pytz.utc)
timeZone= timezone('Asia/Singapore')
localtime = dt.astimezone(timeZone).isoformat()
cam = "002"
lscam = localtime + cam
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
m.update(lscam)
dd=m.hexdigest()
for image in glob.glob(os.path.join('Desktop/images/*.png')):
with open(image, 'rb') as file:
ftp.storbinary('STOR '+dd+ '.png', file)
x = httplib.HTTPConnection('localhost', 8086)
x.connect()
f = {'ts' : localtime}
x.request('GET','/camera/store?cam='+cam+'&'+urllib.urlencode(f)+'&fn='+dd)
y = x.getresponse()
z=y.read()
x.close()
ftp.quit()
</code></pre>
<p>The trackback:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
ftphttp()
File "/home/kevin403/Testtimeloop.py", line 17, in ftphttp
dt = datetime.fromtimestamp(ts, pytz.utc)
TypeError: a float is required
</code></pre>
<p>I trying to get a list of files in a folder to get their modified timestamp and store it in a database. But i can't seem to do it. Anybody got an idea on how to do it? Been trying it for quite long and i'm new to python.</p>
| 0 | 2016-08-15T04:24:02Z | 38,949,493 | <p>This occurs because the function glob.glob, returns an array of strings, and you are trying to pass this result to "datetime.fromtimestamp" function, that expects a number. </p>
<p>Any moment you "store" the modified date, to use after.</p>
<p>You needs to manipulate the files one by one. Example (I didn't test):</p>
<pre><code>files = glob.glob(dataset_path+"/images/*.png")
ts = files.sort(key=os.path.getmtime)
for file in ts:
ms = os.path.getmtime(file)
dt = datetime.fromtimestamp(ms)
...
</code></pre>
<p>or if you only needs the modification dates (without the path of file):</p>
<pre><code>files = glob.glob(dataset_path+"/images/*.png")
ts = map(os.path.getmtime, files)
dts = map(datetime.fromtimestamp, ts)
...
</code></pre>
<p>References:</p>
<p><a href="https://docs.python.org/2/library/datetime.html#datetime.date.fromtimestamp" rel="nofollow">https://docs.python.org/2/library/datetime.html#datetime.date.fromtimestamp</a>
<a href="https://docs.python.org/2/library/glob.html#glob.glob" rel="nofollow">https://docs.python.org/2/library/glob.html#glob.glob</a> </p>
| 1 | 2016-08-15T04:55:03Z | [
"python",
"python-2.7"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in</code>)</em></p>
| 0 | 2016-08-15T04:25:15Z | 38,949,414 | <p>You can do this by performing a <code>sum</code> on a list comprehension that collects all the "scores":</p>
<pre><code>sum( [x['score'] for x in MyListOfDictionaries] )
</code></pre>
<p>(PS. Numpy is not necessary here)
<br></p>
<p><br>
<strong><em>Edit:</em></strong> as pointed out by @sebastian in the comments, the brackets around the list comprehension aren't necessary since we're plugging this directly into a function, i.e.:</p>
<pre><code>sum(x['score'] for x in MyListOfDictionaries)
</code></pre>
<p>this is known as "generator" syntax; from a performance point of view it can be more efficient as it avoids the extra step of allocating memory for the list before processing it.</p>
| 2 | 2016-08-15T04:42:06Z | [
"python",
"numpy",
"dictionary"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in</code>)</em></p>
| 0 | 2016-08-15T04:25:15Z | 38,949,689 | <p><code>NumPy</code> is a library for numerical arrays processing. You use numbers as columns names, convert your collection to matrix and use <code>NumPy</code> to make your calculations if you want to use exactly <code>NumPy</code> and its performance.</p>
<p>I suggest you to try <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> library: it has a type <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">DataFrame</a> which was created to contain and process collections like yours (like dataframes in <code>R</code> language or tables in <code>MatLab</code>) — tables with columns and rows. It has <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow">sum</a> method which solves your problem.</p>
<p>I guess, it's not the only thing that you want to do with your data and speed is important — I'd recommend to use this library.</p>
<p>Here are related StackOverflow questions, which will show you some abilities of the library:</p>
<ul>
<li><a href="http://stackoverflow.com/q/20181456/1305036">Sum up column values in Pandas DataFrame</a></li>
<li><a href="http://stackoverflow.com/questions/28236305">How do I sum values in a column that matches a given condition using pandas?</a></li>
</ul>
| 0 | 2016-08-15T05:22:16Z | [
"python",
"numpy",
"dictionary"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in</code>)</em></p>
| 0 | 2016-08-15T04:25:15Z | 38,949,821 | <pre><code>In [1963]: ll=[{
...: 'name': 'John',
...: 'score': 30
...: }, {
...
...: }]
</code></pre>
<p>First the obvious iterative solution</p>
<pre><code>In [1965]: sum([d['score'] for d in ll])
Out[1965]: 87
</code></pre>
<p>I can turn it into an object array with:</p>
<pre><code>In [1966]: np.array(ll)
Out[1966]:
array([{'score': 30, 'name': 'John'}, {'score': 23, 'name': 'Jan'},
{'score': 34, 'name': 'Mike'}], dtype=object)
</code></pre>
<p>but applying <code>sum</code> directly to that won't help. But:</p>
<pre><code>In [1967]: from operator import itemgetter
In [1970]: np.frompyfunc(itemgetter('score'),1,1)(ll).sum()
Out[1970]: 87
</code></pre>
<p>See my recent answer
<a href="http://stackoverflow.com/a/38936480/901925">http://stackoverflow.com/a/38936480/901925</a> for more on how to access attributes of objects in an array.</p>
<p><code>frompyfunc</code> doesn't really get rid of iteration - it just wraps it in a user friendly manner. And the <code>itemgetter</code> is still doing <code>item['score']</code> for each dictionary in the list.</p>
<p>This use of <code>itemgetter</code> is basically the same as:</p>
<pre><code>In [1974]: list(map(itemgetter('score'), ll))
Out[1974]: [30, 23, 34]
</code></pre>
<p>List comprehension, map, <code>frompyfunc</code> are all ways of iterating through the list and getting the <code>score</code> value from each dictionary.</p>
<p><code>pandas</code> may be able to turn this whole list into a dataframe, but don't be fooled by its ease of use - it's doing all of this, and more, under the covers.</p>
| 2 | 2016-08-15T05:38:21Z | [
"python",
"numpy",
"dictionary"
] |
How to sum dictionary value in python? | 38,949,302 | <p>I have a list get from database.</p>
<pre><code>[{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
</code></pre>
<p>Can <a href="http://www.numpy.org/" rel="nofollow">numpy</a> get the sum of the score? <em>(without loop through 1 by 1 using <code>for in</code>)</em></p>
| 0 | 2016-08-15T04:25:15Z | 38,954,749 | <pre><code>lst = [{
'name': 'John',
'score': 30
}, {
'name': 'Jan',
'score': 23
}, {
'name': 'Mike',
'score': 34
}]
sum(map(lambda x: x['score'], lst))
</code></pre>
| 1 | 2016-08-15T12:04:47Z | [
"python",
"numpy",
"dictionary"
] |
Find the nth time a specific value is exceeded in numpy array | 38,949,308 | <p>This is an extension of the question asked here:
<a href="http://stackoverflow.com/questions/16243955/numpy-first-occurence-of-value-greater-than-existing-value">Numpy first occurence of value greater than existing value</a></p>
<pre><code>N = 10000
aa = np.arange(-N,N)
</code></pre>
<p>In this numpy array, I want to find the index where the array exceeds 0 for the 10th time. To find where it exceeds 0 for the first time, I can simply do:</p>
<pre><code>np.argmax(aa>0.0)
</code></pre>
| 1 | 2016-08-15T04:25:52Z | 38,949,335 | <p>You can work from the same principles as the "first time" case, just with a slightly more complicated middle step.</p>
<p>Start with the boolean array representing your condition:</p>
<pre><code>cond = aa > 0
</code></pre>
<p>Convert the True/False values in the array to counts:</p>
<pre><code>counts = np.cumsum(cond)
</code></pre>
<p>Search for the first occurrence of the count you're looking for:</p>
<pre><code>idx = np.searchsorted(counts, 10)
</code></pre>
<p>Remember that the <code>10</code> in this last line refers to the tenth value that satisfies the condition, and the first value has count <code>1</code>.</p>
<hr>
<p>Alternately, you could convert the condition array to indices:</p>
<pre><code>indices, = np.nonzero(cond)
idx = indices[9]
</code></pre>
<p>Note that in this setup, the tenth value will be at index <code>9</code>.</p>
| 2 | 2016-08-15T04:29:49Z | [
"python",
"arrays",
"numpy"
] |
(Python code not working in loop) pandas.DataFrame.apply() not working in loop | 38,949,320 | <p>I have a piece of code which works fine alone, but when I put it in loop (or use <code>df.apply()</code> method), it does not work.
The code is:</p>
<pre><code>import pandas as pd
from functools import partial
datadf=pd.DataFrame(data,columns=['X1','X2'])
for i in datadf.index.values.tolist():
row=datadf.loc[i]
x1=row['X1']
x2=row['X2']
set1=set([x1,x2])
links=data2[data2['Xset']==set1]
df1=pd.DataFrame(range(1,11),columns=['year'])
def idlist1(row,var1):
year=row['year']
id1a=links[(links['xx1']==var1) & (links['year']==year)]
id1a=id1a['id1'].values.tolist()
id1b=links[(links['xx2']==var1) & (links['year']==year)]
id1b=id1b['id2'].values.tolist()
id1=list(set(id1a+id1b))
return id1
df1['id1a']=df1.apply(partial(idlist1,var1=x1),axis=1)
#...(do other stuffs to return a value using "df1")
del df1
</code></pre>
<p>Here <code>data2</code> is another dataframe. Here I'm trying to match the values of <code>(x1,x2)</code> to <code>data2</code>.
The code works fine outside the loop by which I mean, I specify <code>(x1,x2)</code> directly. But when I put the code in the loop or use <code>df.apply</code>, I always get the error message </p>
<pre><code>ValueError: could not broadcast input array from shape (0) into shape (1)
</code></pre>
<p>I don't understand why. Could someone help? Thanks!
(BTW, the version of <code>pandas</code> is <code>0.18.0</code>.)
The full error message is:</p>
<pre><code>File "<ipython-input-229-541c0f3a4d2f>", line 19, in <module>
df1['id1a']=df1.apply(partial(idlist1,var1=x1),axis=1)
File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 4042, in apply
return self._apply_standard(f, axis, reduce=reduce)
File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 4155, in _apply_standard
result = self._constructor(data=results, index=index)
File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 223, in __init__
mgr = self._init_dict(data, index, columns, dtype=dtype)
File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 359, in _init_dict
return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
File "/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 5250, in _arrays_to_mgr
return create_block_manager_from_arrays(arrays, arr_names, axes)
File "/anaconda2/lib/python2.7/site-packages/pandas/core/internals.py", line 3933, in create_block_manager_from_arrays
construction_error(len(arrays), arrays[0].shape, axes, e)
File "/anaconda2/lib/python2.7/site-packages/pandas/core/internals.py", line 3895, in construction_error
raise e
ValueError: could not broadcast input array from shape (0) into shape (1)
</code></pre>
<p><strong>Update</strong>: I found out the <code>df.apply</code> method somehow is not compatible with the loop, so I converted all the <code>apply</code>'s in the loop to loops, and the code works fine now. Although I "sort of" solved the issue, but I'm still very confused about why this would happen. If anyone knows why, I'd really appreciate the answer. Thanks!</p>
| 2 | 2016-08-15T04:27:27Z | 38,951,306 | <p>Probably because there're multiple definitions of <code>row</code>, one as an argument of the function <code>def idlist1(row,var1):</code> and one defined as <code>row=datadf.loc[i]</code>, you can try to rename one and see if it helps.</p>
| 1 | 2016-08-15T07:55:40Z | [
"python",
"loops",
"pandas"
] |
Code doesnt print anything | 38,949,350 | <pre><code># -*- coding: utf-8 -*-
"""
fill-in-the-blanks1.py
"""
# -*- coding: utf-8 -*-
"""
p1
"""
level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be
called out at any place in the document. A __3__ is a group of strings, variables or numbers. __3__ can also be
printed by the __1__ command. __4__ is the statement of true or false.'''
level2 = '''A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by
adding ___2___ separated by commas between the parentheses. ___1___ by default return ___3___ if you
don't specify the value to return. ___2___ can be standard data types such as string, number, dictionary,
tuple, and ___4___ or can be more complicated such as objects and lambda functions.'''
level3 = '''__1__ , __2__ , __3__ , all belongs to the if statement. __1__ will be used at the beginning of the
if statement, __2__ will be used in the middle between the __4__ and the __5__ statement. '''
variables1 = ["print", "def", "list", "boolean"]
variables2 = ["function", "parameter", "false", "list"]
variables3 = ["if", "elif", "else", "first"]
d = "__1__"
e = "__2__"
f = "__3__"
g = "__4__"
h = "__5__"
def replacevar(string, variable, inputa, finish):
string.split()
while True:
if inputa == variable[0]:
string = string.replace(d, inputa)
finish = ""
finish = finish.join(string)
return finish
break;
else:
print ("Your Answer is incorrect, pls try again")
return True
level = input("Which level do you want to play? (1, 2 or 3)")
if level == "1":
print (level1)
useranswer = input("Please enter the value for variable NO.1: ")
replacevar(level1, variables1, useranswer, finish1)
print (finish1)
</code></pre>
<p>Python code as above, this is just the first part of the program that asks you to fill in the blank and replace the <strong>1</strong>..... with the word you entered if your answer is correct. But when I run the program, after I typed 1, the question showed as expected, but after I typed "print"(without the "") for the answer for the first variable "<strong>1</strong>", it doesn't print the string with replaced words. </p>
| 0 | 2016-08-15T04:31:46Z | 38,949,506 | <p>The only issue was you were using if level == "1": , replace it with if level == 1: and it worked.</p>
<pre><code> """
fill-in-the-blanks1.py
"""
# -*- coding: utf-8 -*-
"""
p1
"""
level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be
called out at any place in the document. A __3__ is a group of strings, variables or numbers. __3__ can also be
printed by the __1__ command. __4__ is the statement of true or false.'''
level2 = '''A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by
adding ___2___ separated by commas between the parentheses. ___1___ by default return ___3___ if you
don't specify the value to return. ___2___ can be standard data types such as string, number, dictionary,
tuple, and ___4___ or can be more complicated such as objects and lambda functions.'''
level3 = '''__1__ , __2__ , __3__ , all belongs to the if statement. __1__ will be used at the beginning of the
if statement, __2__ will be used in the middle between the __4__ and the __5__ statement. '''
variables1 = ["print", "def", "list", "boolean"]
variables2 = ["function", "parameter", "false", "list"]
variables3 = ["if", "elif", "else", "first"]
d = "__1__"
e = "__2__"
f = "__3__"
g = "__4__"
h = "__5__"
def replacevar(string, variable, inputa, finish):
string.split()
while True:
if inputa == variable[0]:
string = string.replace(d, inputa)
finish = ""
finish = finish.join(string)
return finish
break;
else:
print ("Your Answer is incorrect, pls try again")
return True
level = input("Which level do you want to play? (1, 2 or 3)")
if level == 1:
print (level1)
useranswer = input("Please enter the value for variable NO.1: ")
replacevar(level1, variables1, useranswer, finish1)
print (finish1)
</code></pre>
| 0 | 2016-08-15T04:57:11Z | [
"python",
"printing"
] |
Code doesnt print anything | 38,949,350 | <pre><code># -*- coding: utf-8 -*-
"""
fill-in-the-blanks1.py
"""
# -*- coding: utf-8 -*-
"""
p1
"""
level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be
called out at any place in the document. A __3__ is a group of strings, variables or numbers. __3__ can also be
printed by the __1__ command. __4__ is the statement of true or false.'''
level2 = '''A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by
adding ___2___ separated by commas between the parentheses. ___1___ by default return ___3___ if you
don't specify the value to return. ___2___ can be standard data types such as string, number, dictionary,
tuple, and ___4___ or can be more complicated such as objects and lambda functions.'''
level3 = '''__1__ , __2__ , __3__ , all belongs to the if statement. __1__ will be used at the beginning of the
if statement, __2__ will be used in the middle between the __4__ and the __5__ statement. '''
variables1 = ["print", "def", "list", "boolean"]
variables2 = ["function", "parameter", "false", "list"]
variables3 = ["if", "elif", "else", "first"]
d = "__1__"
e = "__2__"
f = "__3__"
g = "__4__"
h = "__5__"
def replacevar(string, variable, inputa, finish):
string.split()
while True:
if inputa == variable[0]:
string = string.replace(d, inputa)
finish = ""
finish = finish.join(string)
return finish
break;
else:
print ("Your Answer is incorrect, pls try again")
return True
level = input("Which level do you want to play? (1, 2 or 3)")
if level == "1":
print (level1)
useranswer = input("Please enter the value for variable NO.1: ")
replacevar(level1, variables1, useranswer, finish1)
print (finish1)
</code></pre>
<p>Python code as above, this is just the first part of the program that asks you to fill in the blank and replace the <strong>1</strong>..... with the word you entered if your answer is correct. But when I run the program, after I typed 1, the question showed as expected, but after I typed "print"(without the "") for the answer for the first variable "<strong>1</strong>", it doesn't print the string with replaced words. </p>
| 0 | 2016-08-15T04:31:46Z | 38,949,620 | <p>When you get over the hurdle of making level 1 work, I believe the structure of your program makes it difficult to get the other levels to work as well without a lot of redundant code. I've reworked it a bit below to enable the other levels -- see if this gives you any ideas with respect to moving forward with your program:</p>
<pre><code>statements = {
"1": '''The __1__ command can print out any type of a variable. __2__ defines a function that
could be called out at any place in the document. A __3__ is a group of strings, variables or numbers.
__3__ can also be printed by the __1__ command. __4__ is a statement of true or false.''',
"2": '''A __1__ is created with the def keyword. You specify the inputs a __1__ takes by
adding __2__ separated by commas between the parentheses. __1__ by default return __3__ if you
don't specify the value to return. __2__ can be standard data types such as string, number,
dictionary, tuple, and __4__ or can be more complicated such as objects and lambda functions.''',
"3": '''__1__ , __2__ , __3__ , all belong to the if statement. __1__ will be used at the beginning
of the if statement, __2__ will be used in the middle between the __4__ and the __5__ statement.''',
}
answers = {
"1": [("__1__", "print"), ("__2__", "def"), ("__3__", "list"), ("__4__", "boolean")],
"2": [("__1__", "function"), ("__2__", "parameters"), ("__3__", "false"), ("__4__", "list")],
"3": [("__1__", "if"), ("__2__", "elif"), ("__3__", "else"), ("__4__", "first")],
}
def replacevar(string, answer, response, blank):
if response == answer:
return string.replace(blank, response)
return None
level = input("Which level do you want to play? (1, 2 or 3) ")
statement = statements[level]
blanks = answers[level]
print(statement)
for (blank, answer) in blanks:
while True:
user_answer = input("Please enter the value for blank " + blank + " ")
finish = replacevar(statement, answer, user_answer, blank)
if finish is None:
print("Your Answer is incorrect, please try again")
else:
statement = finish
print(statement)
break
print("Level completed!")
</code></pre>
<p>Some specific issues with your code: <code>replacevar()</code> has a <code>break</code> which will never be reached after a <code>return</code>; <code>replacevar()</code> sometimes returns a boolean and sometimes a string -- it should return a string or <code>None</code>, or it should return <code>True</code> or <code>False</code>, but don't mix types on return; your main program ignores the result of <code>replacevar()</code> which it shouldn't as it sets you up for the next blank; you <code>split()</code> the string but fail to save the results of the call so it's a no-op; you call <code>join()</code> on a string when it's meant to be called on an array.</p>
| 1 | 2016-08-15T05:13:14Z | [
"python",
"printing"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.