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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Quick way to Upper every value in xml? | 38,926,000 | <p>I have the following xml:</p>
<pre><code><Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info>
<Type>TVSeries</Type>
</Item>
</code></pre>
<p>What would be the quickest way to <code>UPPER</code> all the values? For example:</p>
<pre><code><Item>
<Platform>ITUNES</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>COMMANDER IN CHIEF</Name>
<Studio>ABC</Studio>
</Info>
<Type>TVSERIES</Type>
</Item>
</code></pre>
| -1 | 2016-08-12T20:28:58Z | 38,926,021 | <p>Here is a way to upper everything, though note that this will include the tags as well:</p>
<pre><code>node = etree.fromstring(etree.tostring(item).upper())
print etree.tostring(node, pretty_print=True)
<ITEM>
<PLATFORM>ITUNES</PLATFORM>
<PLATFORMID>102224185</PLATFORMID>
<INFO>
<LANGUAGEOFMETADATA>EN</LANGUAGEOFMETADATA>
<NAME>COMMANDER IN CHIEF</NAME>
<STUDIO>ABC</STUDIO>
</INFO>
<TYPE>TVSERIES</TYPE>
</ITEM>
</code></pre>
| -1 | 2016-08-12T20:30:28Z | [
"python",
"xml",
"lxml"
] |
Quick way to Upper every value in xml? | 38,926,000 | <p>I have the following xml:</p>
<pre><code><Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info>
<Type>TVSeries</Type>
</Item>
</code></pre>
<p>What would be the quickest way to <code>UPPER</code> all the values? For example:</p>
<pre><code><Item>
<Platform>ITUNES</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>COMMANDER IN CHIEF</Name>
<Studio>ABC</Studio>
</Info>
<Type>TVSERIES</Type>
</Item>
</code></pre>
| -1 | 2016-08-12T20:28:58Z | 38,926,040 | <p>You can find all elements and call <code>upper()</code> on each element's text:</p>
<pre><code>import lxml.etree as ET
data = """<Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info>
<Type>TVSeries</Type>
</Item>
"""
root = ET.fromstring(data)
for elm in root.xpath("//*"): # //* would find all elements recursively
elm.text = elm.text.upper()
print(ET.tostring(root))
</code></pre>
<p>Prints:</p>
<pre><code><Item>
<Platform>ITUNES</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>COMMANDER IN CHIEF</Name>
<Studio>ABC</Studio>
</Info>
<Type>TVSERIES</Type>
</Item>
</code></pre>
<p>This though does not cover cases when you, for example, have a tail of an element - e.g. have <code><Studio>ABC</Studio>test</code> instead of just <code><Studio>ABC</Studio></code>. To support that as well, put the following under the for loop as well:</p>
<pre><code>elm.tail = elm.tail.upper() if elm.tail else None
</code></pre>
| 4 | 2016-08-12T20:31:34Z | [
"python",
"xml",
"lxml"
] |
Quick way to Upper every value in xml? | 38,926,000 | <p>I have the following xml:</p>
<pre><code><Item>
<Platform>itunes</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>Commander In Chief</Name>
<Studio>abc</Studio>
</Info>
<Type>TVSeries</Type>
</Item>
</code></pre>
<p>What would be the quickest way to <code>UPPER</code> all the values? For example:</p>
<pre><code><Item>
<Platform>ITUNES</Platform>
<PlatformID>102224185</PlatformID>
<Info>
<LanguageOfMetadata>EN</LanguageOfMetadata>
<Name>COMMANDER IN CHIEF</Name>
<Studio>ABC</Studio>
</Info>
<Type>TVSERIES</Type>
</Item>
</code></pre>
| -1 | 2016-08-12T20:28:58Z | 38,926,050 | <p>Assuming you can parse the XML file you can just rewrite the contents using the <code>.upper()</code> function that is built into python for strings. You can call it like that:
<code>"mystring".upper()</code>. </p>
| -1 | 2016-08-12T20:32:16Z | [
"python",
"xml",
"lxml"
] |
Manipulate specific columns (sample features) conditional on another column's entries (feature value) using pandas/numpy dataframe | 38,926,031 | <p>my <strong>input</strong> dataframe (shortened) looks like this:</p>
<pre><code>>>> import numpy as np
>>> import pandas as pd
>>> df_in = pd.DataFrame([[1, 2, 'a', 3, 4], [6, 7, 'b', 8, 9]],
... columns=(['c1', 'c2', 'col', 'c3', 'c4']))
>>> df_in
c1 c2 col c3 c4
0 1 2 a 3 4
1 6 7 b 8 9
</code></pre>
<hr>
<p>It is supposed to be manipulated, i.e.</p>
<p><em>if row (sample) in column 'col' (feature) has a specific value (e.g., 'b' here),
then convert the entries in columns 'c1' and 'c2' in the same row to NumPy.NaNs.</em></p>
<p><strong>Result wanted:</strong></p>
<pre><code>>>> df_out = pd.DataFrame([[1, 2, 'a', 3, 4], [np.nan, np.nan, np.nan, 8, 9]],
columns=(['c1', 'c2', 'col', 'c3', 'c4']))
>>> df_out
c1 c2 col c3 c4
0 1 2 a 3 4
1 NaN NaN b 8 9
</code></pre>
<hr>
<p>So far, I managed to get obtain <strong>desired result via the code</strong></p>
<pre><code>>>> dic = {'col' : ['c1', 'c2']} # auxiliary
>>> b_w = df_in[df_in['col'] == 'b'] # Subset with 'b' in 'col'
>>> b_w = b_w.drop(dic['col'], axis=1) # ...inject np.nan in 'c1', 'c2'
>>> b_wo = df_in[df_in['col'] != 'b'] # Subset without 'b' in 'col'
>>> df_out = pd.concat([b_w, b_wo]) # Both Subsets together again
>>> df_out
c1 c2 c3 c4 col
1 NaN NaN 8 9 b
0 1.0 2.0 3 4 a
</code></pre>
<hr>
<p>Although I get what I want (the original data consists entirely of floats, don't
bother the mutation from int to float her), it is a rather inelegant
snippet of code. And my educated guess is that this could be done faster
by using the build-in functions from pandas and numpy, but I am unable to manage this.</p>
<p>Any suggestions how to code this in a <strong>fast and efficient</strong> way for daily use? Any help is highly appreciated. :)</p>
| 4 | 2016-08-12T20:30:56Z | 38,926,091 | <p>You can condition on both the row and col positions to assign values using <code>loc</code> which supports both logic indexing and dimension name indexing:</p>
<pre><code>df_in.loc[df_in.col == 'b', ['c1', 'c2']] = np.nan
df_in
# c1 c2 col c3 c4
# 0 1.0 2.0 a 3 4
# 1 NaN NaN b 8 9
</code></pre>
| 4 | 2016-08-12T20:35:36Z | [
"python",
"performance",
"python-3.x",
"pandas",
"numpy"
] |
Manipulate specific columns (sample features) conditional on another column's entries (feature value) using pandas/numpy dataframe | 38,926,031 | <p>my <strong>input</strong> dataframe (shortened) looks like this:</p>
<pre><code>>>> import numpy as np
>>> import pandas as pd
>>> df_in = pd.DataFrame([[1, 2, 'a', 3, 4], [6, 7, 'b', 8, 9]],
... columns=(['c1', 'c2', 'col', 'c3', 'c4']))
>>> df_in
c1 c2 col c3 c4
0 1 2 a 3 4
1 6 7 b 8 9
</code></pre>
<hr>
<p>It is supposed to be manipulated, i.e.</p>
<p><em>if row (sample) in column 'col' (feature) has a specific value (e.g., 'b' here),
then convert the entries in columns 'c1' and 'c2' in the same row to NumPy.NaNs.</em></p>
<p><strong>Result wanted:</strong></p>
<pre><code>>>> df_out = pd.DataFrame([[1, 2, 'a', 3, 4], [np.nan, np.nan, np.nan, 8, 9]],
columns=(['c1', 'c2', 'col', 'c3', 'c4']))
>>> df_out
c1 c2 col c3 c4
0 1 2 a 3 4
1 NaN NaN b 8 9
</code></pre>
<hr>
<p>So far, I managed to get obtain <strong>desired result via the code</strong></p>
<pre><code>>>> dic = {'col' : ['c1', 'c2']} # auxiliary
>>> b_w = df_in[df_in['col'] == 'b'] # Subset with 'b' in 'col'
>>> b_w = b_w.drop(dic['col'], axis=1) # ...inject np.nan in 'c1', 'c2'
>>> b_wo = df_in[df_in['col'] != 'b'] # Subset without 'b' in 'col'
>>> df_out = pd.concat([b_w, b_wo]) # Both Subsets together again
>>> df_out
c1 c2 c3 c4 col
1 NaN NaN 8 9 b
0 1.0 2.0 3 4 a
</code></pre>
<hr>
<p>Although I get what I want (the original data consists entirely of floats, don't
bother the mutation from int to float her), it is a rather inelegant
snippet of code. And my educated guess is that this could be done faster
by using the build-in functions from pandas and numpy, but I am unable to manage this.</p>
<p>Any suggestions how to code this in a <strong>fast and efficient</strong> way for daily use? Any help is highly appreciated. :)</p>
| 4 | 2016-08-12T20:30:56Z | 39,026,466 | <p>When using <strong>pandas</strong> I would go for the solution provided by @Psidom.</p>
<p>However, for larger datasets it is faster when doing the whole <em>pandas -> numpy -> pandas</em> procedure, i.e. <em>dataframe -> numpy.array -> dataframe</em> (minus 10% process time for my setup). Without converting back to a dataframe, <strong>numpy</strong> is almost twice as fast for my dataset.</p>
<p>Solution for the question asked:</p>
<pre><code>cols, df_out = df_in.columns, df_in.values
for i in [0, 1]:
df_out[df_out[:, 2] == 'b', i] = np.nan
df_out = pd.DataFrame(df_out, columns=cols)
</code></pre>
| 0 | 2016-08-18T19:51:42Z | [
"python",
"performance",
"python-3.x",
"pandas",
"numpy"
] |
Join on date in SQLalchemy considering only date and not time of the day | 38,926,043 | <p>I need to join two tables in SQLalchemy on datetime columns but I do not want to consider full datetimes but only date parts of them (join two rows with similar dates even if the time of the days are not equal).</p>
<p>Here is something I have right now</p>
<pre><code>import sqlalchemy as sq
...
first = meta.tables["schema.first"]
second = meta.tables["schema.second"]
select = sq.select([
first.c.id,
first.c.date,
first.c.value,
second.c.value])
.select_from(first.join(second, sq.and_(
first.c.id == second.c.id,
first.c.date == second.c.date
# exact match between datetimes is currently needed
)))
</code></pre>
| 0 | 2016-08-12T20:31:45Z | 38,936,276 | <p>To truncate the timestamps to day precision use the function <a href="https://www.postgresql.org/docs/current/static/functions-datetime.html" rel="nofollow"><code>date_trunc(text, timestamp)</code></a> in PostgreSQL:</p>
<pre><code>select = sq.select([first.c.id,
first.c.date,
first.c.value,
second.c.value])\
.select_from(first.join(second, sq.and_(
first.c.id == second.c.id,
sq.func.date_trunc('day', first.c.date) ==
sq.func.date_trunc('day', second.c.date)
)))
</code></pre>
<p>In this case you could also alternatively cast the timestamps as dates:</p>
<pre><code>sq.cast(first.c.date, sq.Date) == sq.cast(second.c.date, sq.Date)
</code></pre>
| 1 | 2016-08-13T19:30:54Z | [
"python",
"datetime",
"sqlalchemy"
] |
Join on date in SQLalchemy considering only date and not time of the day | 38,926,043 | <p>I need to join two tables in SQLalchemy on datetime columns but I do not want to consider full datetimes but only date parts of them (join two rows with similar dates even if the time of the days are not equal).</p>
<p>Here is something I have right now</p>
<pre><code>import sqlalchemy as sq
...
first = meta.tables["schema.first"]
second = meta.tables["schema.second"]
select = sq.select([
first.c.id,
first.c.date,
first.c.value,
second.c.value])
.select_from(first.join(second, sq.and_(
first.c.id == second.c.id,
first.c.date == second.c.date
# exact match between datetimes is currently needed
)))
</code></pre>
| 0 | 2016-08-12T20:31:45Z | 38,936,373 | <pre><code>from sqlalchemy.sql.functions import func
first = meta.tables("schema.first")
second = meta.tables("schema.second")
select = sq.select([
first.c.id,
first.c.date,
first.c.value,
second.c.value])
.select_from(first.join(second, sq.and_(
first.c.id == second.c.id,
func.DATE(first.c.date) == func.DATE(second.c.date)
)))
</code></pre>
| 0 | 2016-08-13T19:44:20Z | [
"python",
"datetime",
"sqlalchemy"
] |
Making flexible XPath for Selenium (Python) | 38,926,094 | <p>I am trying to use selenium and python to set the text contents of a web element to a string.</p>
<p>The code:
<code>monthname = browser.find_element_by_xpath("//*[@id='monthRow-7']/td[1]").text</code> works but I want to be able to change <code>monthRow-7</code> to include a different number.</p>
<p>My idea is to ask the user for a month (1-12) and what they enter is stored into a string called monthnum. Then I can concatenate the string monthnum into the xpath to change the number of monthRow. Ex. user enters 9 when prompted for the month number so monthRow-7 is changed to monthRow-9.</p>
<p>I have tried:
<code>monthname = browser.find_element_by_xpath(("\"//*[@id='monthRow-") + monthnum + ("']/td[1]\"")).text</code> where <code>monthnum</code> is a string set by user input.</p>
<p>but that gives me an error that says:</p>
<p><strong>"Message: invalid selector: Unable to locate an element with the xpath expression "//*[@id='monthRow-7']/td[1]" because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type."</strong></p>
<p>The xpath expression listed in the error is the same xpath expression I had in my code that actually works though. Is there any way where I can change the xpath by assigning bits of it to variables?</p>
| 0 | 2016-08-12T20:35:50Z | 38,926,262 | <p>I'd use <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">string formatting</a> for this.</p>
<pre><code>monthnum = 7
monthname = browser.find_element_by_xpath("//*[@id='monthRow-{}']/td[1]".format(monthnum)).text
</code></pre>
<p>Here <code>{}</code> will be replaced by the value of <code>monthnum</code>.</p>
<p>I'm not quite sure what you were trying, but I think your solution should work like this:</p>
<pre><code>monthname = browser.find_element_by_xpath("//*[@id='monthRow-" + monthnum + "']/td[1]").text
</code></pre>
<p>All those round brackets and extra quotes should be unnecessary.</p>
| 0 | 2016-08-12T20:49:41Z | [
"python",
"xml",
"selenium",
"xpath",
"concatenation"
] |
How to convert date entries in OHLC data frame in Python to strings in order to use date time module to inspect dates | 38,926,193 | <pre><code>In[118]: Date.iloc[0].to_string()
Out[118]: 'Date 1997-09-09'
</code></pre>
<p>How do I eliminate "Date" from string in order to use date time module</p>
| 1 | 2016-08-12T20:43:54Z | 38,926,226 | <p>Try:</p>
<pre><code>Date.iloc[0, 0].strftime('%Y-%m-%d')
</code></pre>
<p>consider <code>tidx</code></p>
<pre><code>tidx = pd.date_range('2000-01-01', periods=2)
</code></pre>
<p>both print the same thing.</p>
<pre><code>print(tidx.strftime('%Y-%m-%d'))
print(tidx.to_series().dt.strftime('%Y-%m-%d').values)
['2000-01-01' '2000-01-02']
['2000-01-01' '2000-01-02']
</code></pre>
| 2 | 2016-08-12T20:46:56Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
How to convert date entries in OHLC data frame in Python to strings in order to use date time module to inspect dates | 38,926,193 | <pre><code>In[118]: Date.iloc[0].to_string()
Out[118]: 'Date 1997-09-09'
</code></pre>
<p>How do I eliminate "Date" from string in order to use date time module</p>
| 1 | 2016-08-12T20:43:54Z | 38,926,231 | <p>Pass <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_string.html" rel="nofollow"><code>index=False</code></a>:</p>
<pre><code>Date.iloc[0].to_string(index=False)
</code></pre>
| 2 | 2016-08-12T20:47:09Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
How to convert date entries in OHLC data frame in Python to strings in order to use date time module to inspect dates | 38,926,193 | <pre><code>In[118]: Date.iloc[0].to_string()
Out[118]: 'Date 1997-09-09'
</code></pre>
<p>How do I eliminate "Date" from string in order to use date time module</p>
| 1 | 2016-08-12T20:43:54Z | 38,926,254 | <pre><code>Date.iloc[0].to_string()[-10:]
Out[129]: '1997-09-09'
</code></pre>
| 1 | 2016-08-12T20:49:06Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
how to concatenate two csv files and keep the original order of columns in python? | 38,926,206 | <p>Actually there are many parts in this question. I have solved some parts by viewing the answer of other stack overflow questions. However, there is still one tiny problem not solved. The output csv file tends to order alphabetically or in other order, which is not what I want.</p>
<p>As an example, I'm going to concatenate two csv files vertically. The two csv look like the following.</p>
<pre><code> a.csv
B, A, C, E
1, 1, 1, 1
b.csv
B, A, D, C
2, 2, 2, 2
</code></pre>
<p>The result I'd like to get is </p>
<pre><code> c.csv
B, A, D, C, E
1, 1, , 1, 1
2, 2, 2, 2,
</code></pre>
<p>First, I read them into pandas data frames.</p>
<pre><code> a = pd.read_csv("a.csv")
b = pd.read_csv("b.csv")
</code></pre>
<p>Then concatenate them and write to csv by </p>
<pre><code> c = pd.concat([a, b], join='outer')
c.to_csv("c.csv", index=False)
</code></pre>
<p>The output csv looks like</p>
<pre><code> c.csv
A, C, D, B, E
1, 1, , 1, 1
2, 2, 2, , 2
</code></pre>
<p>Is there any way to solve the problem? I once thought of something like the code from the answer <a href="http://stackoverflow.com/questions/15653688/preserving-column-order-in-python-pandas-dataframe">Preserving column order in Python Pandas DataFrame</a></p>
<pre><code> df.to_csv("dfTest.txt","\t",header=True,cols=["b","a","c"], engine='python')
</code></pre>
<p>However, there are hundreds of columns in my csv file, I can't manually write down the order of column names. And for each group of files, the column names are different. I tried </p>
<pre><code> set(a.columns.values).union(list(b.columns.values))
</code></pre>
<p>It also doesn't work, because set will disorder the list.</p>
| 1 | 2016-08-12T20:45:15Z | 38,926,358 | <p>You almost have it with a.columns</p>
<pre><code>col_names = a.columns.tolist() # list of column names
sorted_cols = sorted(col_names)
df.to_csv("dfTest.txt","\t",header=True,cols=sorted_cols, engine='python')
</code></pre>
<p>In one line:</p>
<pre><code>df.to_csv("dfTest.txt","\t",
header=True,
cols=sorted(a.columns.tolist()),
engine='python')
</code></pre>
| 0 | 2016-08-12T20:57:45Z | [
"python",
"csv",
"pandas"
] |
how to concatenate two csv files and keep the original order of columns in python? | 38,926,206 | <p>Actually there are many parts in this question. I have solved some parts by viewing the answer of other stack overflow questions. However, there is still one tiny problem not solved. The output csv file tends to order alphabetically or in other order, which is not what I want.</p>
<p>As an example, I'm going to concatenate two csv files vertically. The two csv look like the following.</p>
<pre><code> a.csv
B, A, C, E
1, 1, 1, 1
b.csv
B, A, D, C
2, 2, 2, 2
</code></pre>
<p>The result I'd like to get is </p>
<pre><code> c.csv
B, A, D, C, E
1, 1, , 1, 1
2, 2, 2, 2,
</code></pre>
<p>First, I read them into pandas data frames.</p>
<pre><code> a = pd.read_csv("a.csv")
b = pd.read_csv("b.csv")
</code></pre>
<p>Then concatenate them and write to csv by </p>
<pre><code> c = pd.concat([a, b], join='outer')
c.to_csv("c.csv", index=False)
</code></pre>
<p>The output csv looks like</p>
<pre><code> c.csv
A, C, D, B, E
1, 1, , 1, 1
2, 2, 2, , 2
</code></pre>
<p>Is there any way to solve the problem? I once thought of something like the code from the answer <a href="http://stackoverflow.com/questions/15653688/preserving-column-order-in-python-pandas-dataframe">Preserving column order in Python Pandas DataFrame</a></p>
<pre><code> df.to_csv("dfTest.txt","\t",header=True,cols=["b","a","c"], engine='python')
</code></pre>
<p>However, there are hundreds of columns in my csv file, I can't manually write down the order of column names. And for each group of files, the column names are different. I tried </p>
<pre><code> set(a.columns.values).union(list(b.columns.values))
</code></pre>
<p>It also doesn't work, because set will disorder the list.</p>
| 1 | 2016-08-12T20:45:15Z | 38,926,365 | <p>Build up an output order which you can then supply to <code>c.to_csv(...)</code>, eg:</p>
<pre><code>from collections import OrderedDict
out_order = OrderedDict.fromkeys(a.columns)
out_order.update(OrderedDict.fromkeys(b.columns))
out_order = list(out_order)
# ['B', 'A', 'C', 'E', 'D']
c.to_csv("c.csv", index=False, columns=out_order)
</code></pre>
| 1 | 2016-08-12T20:58:11Z | [
"python",
"csv",
"pandas"
] |
Listen to ZeroMQ in aiohttp application process | 38,926,534 | <p>I run <code>aiohttp</code> application with <code>Gunicorn</code> behind <code>nginx</code>.
In my application's initialization module I don't run the application using <code>web.run_app(app)</code> but just create an instance that will be imported by <code>Gunicorn</code> to run it in each worker <code>Gunicorn</code> creates.
So <code>Gunicorn</code> creates a few worker processes, event loops within them, and then <a href="https://github.com/KeepSafe/aiohttp/blob/v0.22.5/aiohttp/worker.py#L36" rel="nofollow">runs</a> the application's request handler in those loops.</p>
<p>My <code>aiohttp</code> application has a collection of connected <code>WebSockets</code> (mobile application clients) that I want to notify on event occurred in any of application processes started by <code>Gunicorn</code>.
And I want to notify <strong>all</strong> <code>WebSockets</code> that are connected to <strong>all application processes</strong>.
Therefore I create some kind of upstream proxy using <code>ZeroMQ</code> and I want to subscribe to it using <code>zmq.SUB</code> socket from each application process.</p>
<p>...So basically I want to achieve something like this in each application worker:</p>
<pre><code>context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://localhost:5555')
while True:
event = socket.recv()
for ws in app['websockets']:
ws.send_bytes(event)
# break before app shutdown. How?
</code></pre>
<p>How can I listen the <code>ZeroMQ</code> proxy within <code>aiohttp</code> application to forward messages to <code>WebSockets</code>?</p>
<p>Where can I put this code to run in background within event loop and how to run and shutdown it correctly within <code>aiohttp</code> application's life cycle?</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>I've already created an <a href="https://github.com/KeepSafe/aiohttp/issues/1092" rel="nofollow">issue</a> in aiohttp's GitHub repository describing the problem and proposing a possible solution. I'd highly appreciate an input here or there on matter of the problem described.</p>
| 2 | 2016-08-12T21:12:26Z | 39,346,972 | <p>Ok, the question and the discussion on this <a href="https://github.com/KeepSafe/aiohttp/issues/1092" rel="nofollow">issue</a> has led to the new functionality I've contributed to <code>aiohttp</code>, namely in version <strong>1.0</strong> we'll have an ability to register <code>on_startup</code> application signals using <code>Application.on_startup()</code> method.</p>
<p><a href="http://aiohttp.readthedocs.io/en/latest/web.html#aiohttp-web-background-tasks" rel="nofollow">Documentation</a>.<br>
<a href="https://github.com/KeepSafe/aiohttp/blob/77fa3b5b86c3774d586ece6d6a59dd6eb5c93d8d/examples/background_tasks.py" rel="nofollow">Working example on the master branch</a>.</p>
<pre class="lang-py3 prettyprint-override"><code>#!/usr/bin/env python3
"""Example of aiohttp.web.Application.on_startup signal handler"""
import asyncio
import aioredis
from aiohttp.web import Application, WebSocketResponse, run_app
async def websocket_handler(request):
ws = WebSocketResponse()
await ws.prepare(request)
request.app['websockets'].append(ws)
try:
async for msg in ws:
print(msg)
await asyncio.sleep(1)
finally:
request.app['websockets'].remove(ws)
return ws
async def on_shutdown(app):
for ws in app['websockets']:
await ws.close(code=999, message='Server shutdown')
async def listen_to_redis(app):
try:
sub = await aioredis.create_redis(('localhost', 6379), loop=app.loop)
ch, *_ = await sub.subscribe('news')
async for msg in ch.iter(encoding='utf-8'):
# Forward message to all connected websockets:
for ws in app['websockets']:
ws.send_str('{}: {}'.format(ch.name, msg))
print("message in {}: {}".format(ch.name, msg))
except asyncio.CancelledError:
pass
finally:
print('Cancel Redis listener: close connection...')
await sub.unsubscribe(ch.name)
await sub.quit()
print('Redis connection closed.')
async def start_background_tasks(app):
app['redis_listener'] = app.loop.create_task(listen_to_redis(app))
async def cleanup_background_tasks(app):
print('cleanup background tasks...')
app['redis_listener'].cancel()
await app['redis_listener']
async def init(loop):
app = Application(loop=loop)
app['websockets'] = []
app.router.add_get('/news', websocket_handler)
app.on_startup.append(start_background_tasks)
app.on_cleanup.append(cleanup_background_tasks)
app.on_shutdown.append(on_shutdown)
return app
loop = asyncio.get_event_loop()
app = loop.run_until_complete(init(loop))
run_app(app)
</code></pre>
| 0 | 2016-09-06T10:38:34Z | [
"python",
"zeromq",
"gunicorn",
"python-asyncio",
"aiohttp"
] |
Python -- list(some_float) fails but [some_float] works? | 38,926,579 | <p>I have a case where a user passes a function a single floating-point value. While trying to put that value into a list for easier data handling later, I've discovered that I cannot make a list using <code>list(some_float)</code>, but <code>[some_float]</code> does work. Python prints an error stating that "'float' object is not iterable."</p>
<p>My question for you wonderful people is why <code>[]</code> works, but <code>list()</code> does not. My understanding is that they produce identical results even if they are executed differently. I am using Python 3.4.3.</p>
| 0 | 2016-08-12T21:16:39Z | 38,926,607 | <p><code>list(thing)</code> doesn't mean "put <code>thing</code> in a list". It means "put <code>thing</code>'s <strong>elements</strong> in a list". If you want to put a <code>thing</code> in a list, that's <code>[thing]</code>.</p>
| 6 | 2016-08-12T21:19:14Z | [
"python",
"list"
] |
Python -- list(some_float) fails but [some_float] works? | 38,926,579 | <p>I have a case where a user passes a function a single floating-point value. While trying to put that value into a list for easier data handling later, I've discovered that I cannot make a list using <code>list(some_float)</code>, but <code>[some_float]</code> does work. Python prints an error stating that "'float' object is not iterable."</p>
<p>My question for you wonderful people is why <code>[]</code> works, but <code>list()</code> does not. My understanding is that they produce identical results even if they are executed differently. I am using Python 3.4.3.</p>
| 0 | 2016-08-12T21:16:39Z | 38,926,634 | <p>you have to pass iterable item </p>
<pre><code>print list.__doc__
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
</code></pre>
| 1 | 2016-08-12T21:21:34Z | [
"python",
"list"
] |
How to add a Heroku Django app's new model table to the remote Heroku Postgres with Python migrate? | 38,926,626 | <p>After successfully finishing a tutorial on <a href="https://devcenter.heroku.com/articles/getting-started-with-python#provision-a-database" rel="nofollow">a Heroku Python app with a Postgres db</a>, I made a new model on my Heroku app, based on the existing code, by copying and pasting the existing model and its table's functions and files. <strong>But I had trouble to actually let Heroku create the table on Postgres remotely.</strong> After some trial-and-error, I found the answer below.</p>
<p>Setup: Heroku Python is running locally and remotely, Heroku Postgres is only running remotely.</p>
| 0 | 2016-08-12T21:20:56Z | 38,926,627 | <p>I wanted to actually create my new table on my remote Heroku Postgres database, by running <code>heroku run python manage.py migrate</code>, which was used in the tutorial. But it didn't work right off the bat. What I needed to do was to set up a few Python files and then run that command at the end.</p>
<p>This works if you edit the model too, such as adding a new field.</p>
<p>All the files I added are into the <a href="https://github.com/heroku/python-getting-started" rel="nofollow">Heroku tutorial's code</a> based on <a href="https://devcenter.heroku.com/articles/getting-started-with-python#provision-a-database" rel="nofollow">this tutorial</a></p>
<p>This is exactly what I did:</p>
<ol>
<li><p>in <a href="https://github.com/heroku/python-getting-started/blob/master/hello/models.py" rel="nofollow">hello/models.py</a>, add</p>
<pre><code>class Mytable(models.Model):
when = models.DateTimeField('date created', auto_now_add=True)
</code></pre></li>
<li><p>Let Python generate the <code>0002_mytable.py</code> file in my local <code>hello/migrations</code> by running the following command on my Mac terminal (which was logged into Heroku and in the virtualenv):</p>
<pre><code>python manage.py makemigrations hello
</code></pre>
<p>and I got this response:</p>
<pre><code>Migrations for 'hello':
0002_mytable.py:
- Create model Mytable
</code></pre></li>
<li><p>Add this new migrations file to my remote Heroku</p>
<pre><code>git add hello/migrations/0002_mytable.py
git commit -am "added new migration file"
git push heroku master
</code></pre></li>
<li><p>Let Heroku create the table remotely on the remote Heroku Postgres</p>
<pre><code>heroku run python manage.py migrate
</code></pre>
<p>you should see</p>
<pre><code>Running python manage.py migrate on ⬢ your-heroku-url... up, run.1699
Operations to perform:
Apply all migrations: admin, contenttypes, hello, sessions, auth
Running migrations:
Rendering model states... DONE
Applying hello.0002_mytable... OK
</code></pre></li>
</ol>
| 0 | 2016-08-12T21:20:56Z | [
"python",
"django",
"postgresql",
"heroku"
] |
Using web driver to get all text from a source page in python | 38,926,658 | <p>I am using selenium webdriver (firefox) to crawl some data from a website. I just found that opening the web page is slower than just opening the source of that web page. In other words, it took much longer to go to <code>'www.google.com'</code> than to go to <code>'view-source:www.google.com'</code></p>
<p>So I was wondering whether I can use webdriver to get all text from a source page, rather than a normal page.</p>
<p>I tried using driver.page_source for the source page but it returned some mess that I don't want. </p>
| 0 | 2016-08-12T21:24:42Z | 38,926,703 | <p>If you only need the source use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>. Install it with pip: </p>
<pre><code>pip install requests
</code></pre>
<p>And use it like so:</p>
<pre><code>import requests
r = requests.get("http://google.com/")
# r.content, r.text, r.json(), r.status can be used
</code></pre>
<p>For advanced usage refer to the documentation above.</p>
<p>Note: If you need to parse the html use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> and pass it <code>r.content</code>.</p>
| 1 | 2016-08-12T21:29:21Z | [
"python",
"selenium-webdriver",
"webdriver"
] |
Openpyxl not writing to cells properly | 38,926,683 | <p>Attemping to write a Python script that will open an existing invoice template I have created and prompt for the info to fill in the cells. The file is created with the intended name, the print statement at the end successfully prints the value intended for cell C5, and the script finishes without errors. Upon opening the newly created Excel file, no data appears in cells C3 and C5. Initially I was missing the save statement and assumed that was my problem, however after adding it I'm still running into the same issue. Please help!</p>
<pre><code>import openpyxl
#prompt for invoice number
invNumber = raw_input('What is this invoice number? ')
#convert string to integer
invNumberInt = int(invNumber)
file ='test.xlsx'
wb = openpyxl.load_workbook(file)
ws = wb.get_sheet_by_name('Sheet1')
ws['C3'] = invNumberInt
#invoice due date
dueDate = raw_input('When is this invoice due? mm/dd/yyyy: ')
ws['C5'] = dueDate
wb.save(filename = "invoice%d.xlsx" % invNumberInt)
print ws['C5'].value
</code></pre>
| 0 | 2016-08-12T21:27:07Z | 39,134,903 | <ol>
<li>What happens if you open the file in Excel and save it (that corrects some openpyxl problems for me, where it has not fully updated an excel 2016 xlsx worksheet).</li>
<li>What does a file compare show between test.xlsx and invoiceN.xlsx?</li>
</ol>
| 0 | 2016-08-25T00:22:51Z | [
"python",
"excel",
"openpyxl"
] |
Open .hdr files with OpenCV | 38,926,689 | <p>I try to read <code>.hdr</code> files like this:</p>
<pre><code>img = cv2.imread(sys.argv[1])
cv2.imshow('Image', img)
</code></pre>
<p>This gives me a 3-channel 8-bit <code>Mat</code> which is either (nearly) completely white or a very dark picture. So I suppose it only gives me one image of the exposure sequence? How do I get a proper <code>Mat</code> with all the information?</p>
<ul>
<li>OpenCV version is 3.1.0.</li>
<li>HDR files used: <a href="http://people.csail.mit.edu/sparis/publi/2011/siggraph/" rel="nofollow">http://people.csail.mit.edu/sparis/publi/2011/siggraph/</a> ("Input images")</li>
</ul>
| 1 | 2016-08-12T21:27:29Z | 39,472,526 | <p>The data you have is the merged stack not individual exposures. To display it correctly, you need to tone-map the data. This is the correct procedure, for example:</p>
<pre><code>Mat hdr = imread("xxx.hdr",-1); // correct element size should be CV_32FC3
Mat ldr;
Ptr<TonemapReinhard> tonemap = createTonemapReinhard(2.2f);
tonemap->process(hdr, ldr);
ldr.convertTo(ldr, CV_8UC3, 255);
</code></pre>
<p>Then display your ldr with highgui.</p>
| 1 | 2016-09-13T14:28:32Z | [
"python",
"opencv",
"hdr"
] |
ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb -- Django 1.4 & Google App Engine | 38,926,708 | <p>This will be the second time in my life posting about almost exactly the same thing. The difference between this time and last time is about 9 months, lots of difficult learning, and the fact that for those past 9 months I have never had this issue and have frequently used MySQLdb flawlessly during the entire time period. I recognize that a similar question to this has been asked many times. I have read the responses and performed the suggested fixes. As of yet, I have still been unable to reach a successful conclusion, which is why I am posting my question.</p>
<p>Just to describe my environment: I'm running a Django app on Google App Engine locally using the Google App Engine Launcher. I'm using Mac OS X El Capitan.</p>
<p>When these apps are deployed on Google App Engine, they work flawlessly as intended. However, when running locally, I will consistently get the ImportError upon trying to run the app.</p>
<p>Let me list some of the things I have checked and/or tried to fix the problem:</p>
<p>-Installed mysql</p>
<p>-Installed mysql-python</p>
<p>-Added MySQLdb to "Libraries" section in app.yaml</p>
<p>-Checked PYTHONPATH at runtime to confirm that the proper directories are added to path.</p>
<p>-Add paths before importing as a dummy check</p>
<p>-Updated Google App Engine SDK</p>
<p>I've done even more, but can barely recall them now. When checking the path at runtime, I can clearly see the following path to the google_appengine SDK directory where MySQLdb resides:</p>
<pre><code>/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/MySQLdb-1.2.5
</code></pre>
<p>Is this not what I'm supposed to see? Should I be pointing to something else? I've also pointed to other directories where I have other python packages installed (e.g. /Library/Python/2.7/site-packages/). What am I missing? I know I'm doing something dumb, and I'm fine with that. I just want to stop wasting my own time trying to troubleshoot such a stupid issue. I use MySQL every day in other projects, and never experience issues like this. I really don't know what it is at this point.</p>
<p>Let me know if I can add anymore useful information and I will happily oblige. I will put a few of my files down below in the hopes that they may be useful.</p>
<p>app.yaml:</p>
<pre><code>application: *omitted*
version: 1
runtime: python27
api_version: 1
threadsafe: true
env_variables:
DJANGO_SETTINGS_MODULE: 'Freya.settings'
handlers:
- url: /favicon\.ico
static_files: static/images/favicon.ico
upload: static/images/favicon\.ico
- url: /static
static_dir: static
application_readable: true
- url: /.*
script: main.app
libraries:
- name: django
version: "latest"
- name: MySQLdb
version: "latest"
</code></pre>
<p>main.py:</p>
<pre><code>from google.appengine.ext.webapp import util
import django.dispatch.dispatcher
import django.core.handlers.wsgi
from django.conf import settings
import django.core.signals
import django.db
import os
settings._target = None
app = django.core.handlers.wsgi.WSGIHandler()
def main():
util.run_wsgi_app(app)
if __name__ == '__main__':
main()
</code></pre>
<p>settings.py (the database bit):</p>
<pre><code>'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '*omitted*',
'NAME': '*omitted*',
'USER': '*omitted*',
}
</code></pre>
<p>Any help is greatly appreciated.</p>
<p>Here is an example of something I tried in settings.py:</p>
<pre><code>import imp
import sys
import os
print('Checking')
try:
imp.find_module('MySQLdb')
found = True
except ImportError:
found = False
print('Found: ' + str(found))
import MySQLdb
print('Import success')
</code></pre>
<p>Doing this, when I look for 'Found: false' I don't find it. I find 'Found: true' which should really tell me that there isn't any problem finding the MySQLdb module. However, when it reaches the <code>import MySQLdb</code> line, the program crashes with <code>ImportError: No module named MySQLdb</code> and the line <code>print('Import success')</code> is never reached</p>
<p>What's going on?</p>
<p>Edit: I am going to try to do this now on my Linux partition, though I don't think that anything I do there will help me figure out what to do back on Mac OS</p>
| 0 | 2016-08-12T21:29:47Z | 39,003,811 | <p>After digging around for hours I have finally discovered the root issue. The only significant change that has occurred from the time that MySQLdb was working properly and the time that MySQLdb stopped working properly was upon my upgrading OS X to El Capitan.</p>
<p>Running:</p>
<p><code>otool -L /Library/Python/2.7/site-packages/_mysql.so</code></p>
<p>revealed that <code>_mysql.so</code> was searching for <code>libmysqlclient.18.dylib</code> in the <code>/usr/lib</code> directory when really it was located in <code>/usr/local/lib</code> directory. As a quick fix, I created a symbolic link by running the following (all on one line btw):</p>
<p><code>sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dââylib /usr/local/lib/libmysqlclient.18.dylib</code></p>
<p>Since El Capitan has implemented Apple's "rootless" mode, and the current user (me) is unable to write to <code>/usr/lib</code>, creating the symlink in <code>/usr/local/lib</code> is adequate and probably better for a Mac user.</p>
<p>After performing these steps, MySQLdb was able to load properly; my app initialized and ran successfully for the first time in a long while.</p>
| 1 | 2016-08-17T18:23:57Z | [
"python",
"mysql",
"django",
"google-app-engine",
"mysql-python"
] |
Effective Way to Validate Field Values Spark | 38,926,715 | <p>I need to validate certain columns in a data frame before saving data to hdfs. I want to know if there is an elegant and effective way to do this in pyspark 1.5.2 / python 2.7</p>
<p>For example, say I have the following data</p>
<pre><code>+-----+---+
| a| b|
+-----+---+
|"foo"|123|
+-----+---+
</code></pre>
<p>I want to make sure that every value for column <code>a</code> is no longer than 3 characters and column <code>b</code> is <code><= 500</code>.</p>
<p>My current thought is to write a udf that does a simple if/else, and return a certain value, then based on those results decide whether or not to fail the job. However, for a lot of data, I'm concerned that it will be slow or at least very heavy processing. Is there a well established way of doing this in spark already? Or is there any sort of popular strategy for doing it? I haven't been able to find much information on the subject myself.</p>
<p>I am also open to avoiding spark if there is a better way, any good suggestion would be very helpful.</p>
| 2 | 2016-08-12T21:30:19Z | 38,926,864 | <p>You can use several predefined <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=functions#module-pyspark.sql.functions" rel="nofollow">functions</a> to accomplish your objective.</p>
<pre><code>from pyspark.sql.functions import *
df = sc.parallelize([("fo", 100),("alb", 501),("roger", -10),("francis", 1000)]).toDF(["name", "salary"])
df.select("*", ((length("name") < lit(3)) & (col("salary") <= lit(500))).alias("evaluation")).show()
+-------+------+----------+
| name|salary|evaluation|
+-------+------+----------+
| fo| 100| true|
| alb| 501| false|
| roger| -10| false|
|francis| 1000| false|
+-------+------+----------+
</code></pre>
| 3 | 2016-08-12T21:42:50Z | [
"python",
"hadoop",
"apache-spark",
"bigdata",
"pyspark"
] |
Python(2.7) keeps crashing when launching scapy via console or importing it | 38,926,728 | <p>Regardless of if I do </p>
<pre><code>scapy
</code></pre>
<p>or </p>
<pre><code>Python
from scapy.all import *
</code></pre>
<p>it simply crashes python. It says "Python is not responding" with the classic little bar that does nothing. I'm currently on Win10. </p>
<p>There's only one other person that I found had this problem, and nobody bothered to answer him, couldn't find anything else about this. I've tried multiple installers from differently packaged ones. No can do. I'm about to go raving mad.</p>
<p>Many thanks in advance.</p>
| 0 | 2016-08-12T21:31:32Z | 38,935,298 | <p>Well, nobody put an answer, but I finally figured it out, so in the oddball chance someone ends up in the same predicament, here's how I got it to work: </p>
<p>Make sure the anniversary update for windows is installed, and enable the beta(or not anymore by the time your read this?) linux bash (a quick googling will show you how to do this, nothing special to do, just a few options to tick, howtogeek has a little guide if it can help you search). </p>
<p>You'll have to restart your computer. You should then be able to open an ubuntu bash on windows. <a href="http://www.secdev.org/projects/scapy/doc/installation.html" rel="nofollow">Go to to the scapy installation website</a>, and go to the "native linux" part. I personally uninstalled all other versions of python prior to this, but it might of stuck with 2.7.12 or w/e. But in any case, I installed the 2.5 that is linked in there. Then, ran the command that installs a bunch of dependencies looking something like this:</p>
<blockquote>
<p>$ sudo apt-get install tcpdump graphviz imagemagick python-gnuplot python-crypto python-pyx</p>
</blockquote>
<p>then went to download the lastest version of scapi, which, at this current time, is 2.3.1. Unzip it, navigate to the destination in your bash, and sudo python setup.py install it. </p>
<p>It now works just fine, if you simply run it with "scapy" it'll work but tell you tcpdump has a path problem or isn't installed. if you run it with sudo, you won't have that issue. </p>
<p>Anyways, figured I appreciated when people left solutions behind, so here's me doing my part - answering my own darn question.</p>
<p>EDIT: Due to microsoft problems with their not yet correctly set up batch, scapy has a few issues because some destinations are not reachable. I'm assuming that might be patched eventually (or one hopes?).</p>
| 1 | 2016-08-13T17:30:06Z | [
"python",
"wireshark",
"scapy",
"packets"
] |
Parse XML tag's attribute value via ElementTree AND replace the value string | 38,926,854 | <p>I am new to Python and trying to automate a task. I have spent two days reading the docs, looked into various other similar questions, but now, I've hit a wall and can't move forward. </p>
<p>I feel Python docs are not well documented on Elementtree module. Maybe it is just me. Also, I know I can use other modules. But please direct me with only Elementtree. Please help me guide forward.</p>
<p>The task is to parse XML and use Elementtree to replace all tag's attribute value. In web-server-parm, I need to replace ALL links which contains "<a href="http://api-stg.link.com" rel="nofollow">http://api-stg.link.com</a>." For ex...</p>
<p>FROM </p>
<p><strong>"ServerAddr="http://api-stg.link.com/dataapi/v2/exchangerates/"</strong> </p>
<p>TO</p>
<p><strong>"ServerAddr="http://api-DATA-stg.link.com/dataapi/v2/exchangerates/"</strong>. </p>
<p><strong>XML test.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ConfigRoot>
<max-layer layer="5"/>
<enabled-cache status="0"/>
<server type="fgrfreefr">
<web-server-parm mode="QA" ServerAddr="http://api-stg.link.com/dataapi/v2/securities?response=complex&amp;limit=9999999" timedOut="10000" X-API-UserId="54456464561" X-API-ProductId="ADS" ApiKey="fgggdfvdffdgdfg"/>
<web-server-parm mode="UAT" ServerAddr="http://api-uat.link.com/dataapi/v2/securities?response=complex&amp;limit=9999999" timedOut="10000" X-API-UserId="gdfsgvhdgjfjuhgdyejhgsfegtb" X-API-ProductId="ADS" ApiKey="@gggf-fsffff@"/>
</server>
<server type="vfffdg">
<web-server-parm mode="QA" ServerAddr="http://api-stg.link.com/dataapi/v2/exchangerates/" timedOut="10000" X-API-UserId="gsfsftfdfrfefrferf" X-API-ProductId="ADS" ApiKey="fgvdgggdfgttggefr"/>
<web-server-parm mode="UAT" ServerAddr="http://api-uat.link.com/dataapi/v2/exchangerates/" timedOut="10000" X-API-UserId="gdfdagtgdfsgtrsdfsg" X-API-ProductId="ADS" ApiKey="@hdvfddfdd"/>
</server>
</ConfigRoot>
</code></pre>
<p><strong>Task.py</strong>
This is what I have so far</p>
<pre><code>import xml.etree.ElementTree as ET
# import XML, SubElement, Element, tostring
#----------------------------------------------------------------------
def parseXML(xml_file):
"""
Parse XML with ElementTree
"""
tree = ET.ElementTree(file=xml_file)
root = tree.getroot()
# get the information via the children!
print "Iterating using getchildren()"
node = root.getchildren()
for server_addr in node:
node_children = server_addr.getchildren()
for node_child in node_children:
print "_________passed__________"
print "%s=%s" % (node_child.attrib, node_child.text)
test = node_child.findtext("http://api-stg.link.com/dataapi/v2/exchangerates/")
if test is None:
continue
tests = test.text
print tests
# #----------------------------------------------------------------------
if __name__ == "__main__":
parseXML("test/test.xml")
</code></pre>
| 0 | 2016-08-12T21:42:11Z | 38,927,097 | <p>Consider using <code>iter()</code> across the elements with a conditional <code>if</code> replace:</p>
<pre><code>import xml.etree.ElementTree as ET
#----------------------------------------------------------------------
def parseXML(xml_file):
"""
Parse XML with ElementTree
"""
tree = ET.ElementTree(file=xml_file)
root = tree.getroot()
# get the information via the children!
print("Iterating using getchildren()")
for serv in root.iter('server'):
for web in serv.iter('web-server-parm'):
if 'http://api-stg.link.com' in web.get('ServerAddr'):
web.set('ServerAddr', web.get('ServerAddr').\
replace("http://api-stg.link.com", "http://api-DATA-stg.link.com"))
print(ET.tostring(root).decode("UTF-8"))
tree.write("ConfigRoot_py.xml")
# #----------------------------------------------------------------------
if __name__ == "__main__":
parseXML("ConfigRoot.xml")
</code></pre>
<p><strong>Output</strong></p>
<pre><code><ConfigRoot>
<max-layer layer="5" />
<enabled-cache status="0" />
<server type="fgrfreefr">
<web-server-parm ApiKey="fgggdfvdffdgdfg" ServerAddr="http://api-DATA-stg.link.com/dataapi/v2/securities?response=complex&amp;limit=9999999" X-API-ProductId="ADS" X-API-UserId="54456464561" mode="QA" timedOut="10000" />
<web-server-parm ApiKey="@gggf-fsffff@" ServerAddr="http://api-uat.link.com/dataapi/v2/securities?response=complex&amp;limit=9999999" X-API-ProductId="ADS" X-API-UserId="gdfsgvhdgjfjuhgdyejhgsfegtb" mode="UAT" timedOut="10000" />
</server>
<server type="vfffdg">
<web-server-parm ApiKey="fgvdgggdfgttggefr" ServerAddr="http://api-DATA-stg.link.com/dataapi/v2/exchangerates/" X-API-ProductId="ADS" X-API-UserId="gsfsftfdfrfefrferf" mode="QA" timedOut="10000" />
<web-server-parm ApiKey="@hdvfddfdd" ServerAddr="http://api-DATA-stg.link.com/dataapi/v2/exchangerates/" X-API-ProductId="ADS" X-API-UserId="gdfdagtgdfsgtrsdfsg" mode="UAT" timedOut="10000" />
</server>
</ConfigRoot>
</code></pre>
| 1 | 2016-08-12T22:07:52Z | [
"python",
"xml",
"parsing",
"elementtree"
] |
Implications of flushing stdout after each print | 38,926,917 | <p>I have a script whose output is piped to <code>less</code>, and I would like the script to print it's statements into <code>less</code> as they come, rather than all at once.</p>
<p>I found that if I flush stdout (via <code>sys.stdout.flush()</code>) after each print, the line is displayed in <code>less</code> when flushed (obviously).</p>
<p>My question is: Are there any drawbacks to doing this? My script has hundreds of thousands of lines being printed, would flushing <strong>after each line</strong> cause problems?</p>
<p>My impression is yes, because you take extra resources up for displaying each time you flush, as well as completely circumventing the idea of buffered output</p>
| 1 | 2016-08-12T21:48:18Z | 38,926,942 | <p>Basically, the only drawback is that it's potentially slower. The buffering on stdin allows your program to run ahead of the physical I/O which is slow.</p>
<p>However, if you're sending it to less, you're operating at human speeds anyway -- it's not going to make a difference.</p>
| 0 | 2016-08-12T21:50:45Z | [
"python",
"python-2.7"
] |
How to get parent directory and sub directory for file | 38,926,949 | <p>I'm trying list out the names of directories a particular file belongs to. Below is an example of my file tree: </p>
<pre><code>root_folder
âââ topic_one
â  âââ one-a.txt
â  âââ one-b.txt
âââ topic_two
âââ subfolder_one
â  âââ sub-two-a.txt
âââ two-a.txt
âââ two-b.txt
</code></pre>
<p>Ideally, what I'd like to have printed out is:</p>
<pre><code>"File: file_name belongs in parent directory"
"File: file_name belongs in sub directory, parent directory"
</code></pre>
<p>I wrote this script:</p>
<pre><code>for root, dirs, files in os.walk(root_folder):
# removes hidden files and dirs
files = [f for f in files if not f[0] == '.']
dirs = [d for d in dirs if not d[0] == '.']
if files:
tag = os.path.relpath(root, os.path.dirname(root))
for file in files:
print file, "belongs in", tag
</code></pre>
<p>which gives me this output:</p>
<pre><code>one-a.txt belongs in topic_one
one-b.txt belongs in topic_one
two-a.txt belongs in topic_two
two-b.txt belongs in topic_two
sub-two-a.txt belongs in subfolder_one
</code></pre>
<p>I can't seem to figure out how to get the parent directory included for the file within a sub directory. Any help or alternative methods would be greatly appreciated.</p>
| 2 | 2016-08-12T21:51:10Z | 38,929,509 | <p>Thanks to <a href="http://stackoverflow.com/users/6451573/jean-fran%C3%A7ois-fabre">Jean-François Fabre</a> and <a href="http://stackoverflow.com/users/1040495/jjpx">Jjpx</a> for this solution:</p>
<pre><code>for root, dirs, files in os.walk(root_folder):
# removes hidden files and dirs
files = [f for f in files if not f[0] == '.']
dirs = [d for d in dirs if not d[0] == '.']
if files:
tag = os.path.relpath(root, root_folder)
for file in files:
tag_parent = os.path.dirname(tag)
sub_folder = os.path.basename(tag)
print "File:",file,"belongs in",tag_parent, sub_folder if sub_folder else ""
</code></pre>
<p>Prints out:</p>
<pre><code>File: one-a.txt belongs in topic_one
File: one-b.txt belongs in topic_one
File: two-a.txt belongs in topic_two
File: two-b.txt belongs in topic_two
File: sub-two-a.txt belongs in topic_two subfolder_one
</code></pre>
| 0 | 2016-08-13T05:23:57Z | [
"python"
] |
Multiply elementwise array and rectangular matrix | 38,927,004 | <p>I want to multiply elementwise an array of shape (10,) and a matrix of shape (10,20), basically multiply each column by the array.</p>
<p>But I got </p>
<blockquote>
<p><code>ValueError: operands could not be broadcast together with shapes (20,) (20,10)</code> </p>
</blockquote>
<p>It does work when I use a (10,10) matrix and a (10,) array. </p>
<p>I'd prefer not to do it with a <code>for</code> loop to optimize the time taken by my algorithm. (this array/matrix opreation is far deep in many other loops)</p>
| 0 | 2016-08-12T21:56:03Z | 38,927,317 | <p>If you want to multiply 2 matrix they have to have an order in math and in programs</p>
<pre><code>A => a x n
B => n x b
</code></pre>
<p>and you get <code>C = A x B</code> will be shaped <code>C => a x b</code></p>
<p>so your first array has to be (1,10) to multiply a matrix (10,20) and you will get an array (1,20)</p>
<p>to do that you can <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow">transpose</a> your first array </p>
| 0 | 2016-08-12T22:34:54Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Multiply elementwise array and rectangular matrix | 38,927,004 | <p>I want to multiply elementwise an array of shape (10,) and a matrix of shape (10,20), basically multiply each column by the array.</p>
<p>But I got </p>
<blockquote>
<p><code>ValueError: operands could not be broadcast together with shapes (20,) (20,10)</code> </p>
</blockquote>
<p>It does work when I use a (10,10) matrix and a (10,) array. </p>
<p>I'd prefer not to do it with a <code>for</code> loop to optimize the time taken by my algorithm. (this array/matrix opreation is far deep in many other loops)</p>
| 0 | 2016-08-12T21:56:03Z | 38,927,616 | <p>The first rule of broadcasting is that the arrays with fewest dimensions get expanded - and the expansion occurs at the front of the array.</p>
<p>In the (10,) * (10,20) case, there are 2 dim, so the first expands to (1,10). But that can't be changed to match (10,20).</p>
<p>So you need to explicitly change the (10,) to (10,1). The easiest way with <code>None</code>.</p>
<pre><code>x[:,None]*y
</code></pre>
<p>Note, in MATLAB that expansion occurs at the other end. But I'm not sure if MATLAB has broadcasting yet. Octave added it some years ago.</p>
<p>================</p>
<p>In the (10,) * (10,10) case, => (1,10)*(10,10) => (10,10)</p>
<pre><code>In [1403]: np.arange(4)*np.ones((4,4),int)
Out[1403]:
array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])
In [1404]: np.arange(4)[:,None]*np.ones((4,4),int)
Out[1404]:
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
</code></pre>
<p>Different results.</p>
| 2 | 2016-08-12T23:13:48Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Python Selenium Calling Hidden File Input | 38,927,073 | <p>I am using selenium-python with chromedriver.</p>
<p>In a webpage,which is <a href="https://web.whatsapp.com/" rel="nofollow">https://web.whatsapp.com/</a> ,I am trying to send a file with send_keys() to a file type input.</p>
<p>But the problem is,that input element is only visible in inspector when you drop a file on the webpage.If you close that menu(I don't mean native menu) element disappears from inspector.</p>
<p>How can I call that element if element is not displayed?</p>
<p>And element seems like this:</p>
<pre><code>xpath='//*[@id="app"]/div/div[3]/div[1]/span[2]/span/div/div[2]/input'
<input type="file" accept="image/*,video/*" multiple="" style="display: none;">
</code></pre>
<p>I tried</p>
<pre><code>driver.execute_script("document.getElementById('parent_id').style.display='block';")
driver.execute_script("document.getElementByXpath('Xpath').sendKeys('file');")
</code></pre>
<p>But none of them worked.</p>
| 1 | 2016-08-12T22:05:21Z | 38,928,116 | <p>If you wat to work with file input element then try to make it visible instead of it's parent element as below :</p>
<pre><code>xpath = '//*[@id="app"]/div/div[3]/div[1]/span[2]/span/div/div[2]/input'
file = driver.find_element_by_xpath(xpath)
file = driver.execute_script("arguments[0].style.display='block'; return arguments[0];", file)
file.seng_keys("file")
</code></pre>
| 0 | 2016-08-13T00:41:04Z | [
"javascript",
"python",
"selenium",
"input",
"hidden"
] |
KeyError: nan in dict | 38,927,099 | <p>I do as below</p>
<pre><code>import numpy as np
from numpy import nan
df = pd.DataFrame({'a':[1, 2, 0, 1, np.nan, 2, 0]})
mapper = {2.0: 0.0, 1.0: 1.0 ,0.0: 2.0, nan : nan}
df['a'] = [ mapper[x] for x in df['a'] ]
</code></pre>
<p>and </p>
<pre><code>KeyError: nan
</code></pre>
<p>I tried to change dtypes</p>
<pre><code>df['a'] = df['a'].astype(object)
</code></pre>
<p>but again </p>
<pre><code>KeyError: nan
</code></pre>
<p>what's wrong?</p>
| 2 | 2016-08-12T22:08:21Z | 38,927,116 | <p>The problem is that nan is "not a number", and as such it equals no other number, not even another nan. You can read more about it <a href="https://en.wikipedia.org/wiki/NaN">here</a>.</p>
<p>To demonstrate:</p>
<pre><code>from numpy import nan
nan == nan
=> False
</code></pre>
<p>From this it must follow that nan is not in your dict, because it doesn't equal any of the keys.</p>
| 5 | 2016-08-12T22:10:36Z | [
"python",
"numpy",
"dictionary"
] |
KeyError: nan in dict | 38,927,099 | <p>I do as below</p>
<pre><code>import numpy as np
from numpy import nan
df = pd.DataFrame({'a':[1, 2, 0, 1, np.nan, 2, 0]})
mapper = {2.0: 0.0, 1.0: 1.0 ,0.0: 2.0, nan : nan}
df['a'] = [ mapper[x] for x in df['a'] ]
</code></pre>
<p>and </p>
<pre><code>KeyError: nan
</code></pre>
<p>I tried to change dtypes</p>
<pre><code>df['a'] = df['a'].astype(object)
</code></pre>
<p>but again </p>
<pre><code>KeyError: nan
</code></pre>
<p>what's wrong?</p>
| 2 | 2016-08-12T22:08:21Z | 38,927,217 | <p>@shx2 explains why this happens. But you can still do what you want — just forget the <code>NaN</code> and use <code>Series.map</code>:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 0, 1, np.nan, 2, 0]})
mapper = {2.0: 0.0, 1.0: 1.0 ,0.0: 2.0}
df['a'] = df['a'].map(mapper)
print(df)
# a
# 0 1.0
# 1 0.0
# 2 2.0
# 3 1.0
# 4 NaN
# 5 0.0
# 6 2.0
</code></pre>
<p>If you want to map the <code>NaN</code> entries to, say, <code>55</code>, use <code>.fillna()</code>:</p>
<pre><code>df['a'] = df['a'].fillna(55)
print(df)
# a
# 0 1.0
# 1 0.0
# 2 2.0
# 3 1.0
# 4 55.0
# 5 0.0
# 6 2.0
</code></pre>
| 2 | 2016-08-12T22:21:40Z | [
"python",
"numpy",
"dictionary"
] |
keyboard stops working when typing my PYPI password in the cmd | 38,927,157 | <p>I have logged into the python package index but when I tried to upload my first python file and pressed 1 to type my username and password , the keyboard at the password section stopped working and when I pressed enter the server response is: "you must login to access this feature" ,but i just cant type the password to login !</p>
| -1 | 2016-08-12T22:15:11Z | 38,927,222 | <p>type your password and press enter</p>
<p>you won't see any <code>*</code>, that doesn't mean your keyboard stopped working (it's invisible)</p>
| 0 | 2016-08-12T22:22:18Z | [
"python",
"pypi"
] |
How can I specify a class method as a callback target in Python? | 38,927,207 | <p>I'm using the sftp module of paramiko to transfer payloads to remote hosts. Part of the <code>sftp.put</code> call allows for specifying a callback method with signature <code>func(int,int)</code>. I'm trying to put a transfer stats method into my <code>Connection</code> class to keep track of payload progress.</p>
<p>Here's the class I have currently:</p>
<pre><code>class Connection:
def __init__(self, endpoint, RSAKeyObj):
self.displayHost = bcolors.OKGREEN + endpoint + bcolors.ENDC
self.transport = paramiko.Transport((endpoint,4022))
self.transport.connect(username='transit', pkey=RSAKeyObj)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
try:
# initial sftp directory setup
log.info('[{0}]: Setting up remote directories...'.format(self.displayHost))
log.info(self.sftp.mkdir(JAIL_DIR))
except:
pass
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
@static_vars(counter=0)
def TransferStats(self, transferedBytes, totalBytes):
if (transferedBytes / totalBytes) >= TransferStats.counter:
log.info('Transferred: {}% [{}/{}]'.format(round((transferedBytes/totalBytes)*100,2), transferedBytes, totalBytes))
TransferStats.counter += 0.025
def Transmit(self,targetDir, payloadPath):
displayText = 'Transferring package {}...'.format(payloadPath)
self.TransferStats().counter=0
log.info('[%s] ' % self.displayHost + displayText)
log.info(self.sftp.put(payloadPath, '%s/%s' % (targetDir,payloadPath), callback=self.TransferStats()))
</code></pre>
<p>However when I try this, I get the following error:</p>
<blockquote>
<p>ERROR - (, TypeError('TransferStats() takes exactly 3 arguments (1 given)',), )</p>
</blockquote>
<p>This makes me think that the callback isn't getting recognized by paramiko when it tries to send it's <code>(int,int)</code> because of the <code>self</code> declaration. Is there a way around this?</p>
| 0 | 2016-08-12T22:20:24Z | 38,927,252 | <p>Your problem is in :</p>
<pre><code> log.info(self.sftp.put(payloadPath, '%s/%s' % (targetDir,payloadPath), callback=self.TransferStats()))
</code></pre>
<p>Your error :</p>
<pre><code>ERROR - (, TypeError('TransferStats() takes exactly 3 arguments (1 given)',), )
</code></pre>
<p>Is caused by calling <code>TransferStats</code> with no arguments (<code>self.TransferStats()</code> will result in 1 argument : the class (as it is a class method))</p>
<p>Just pass the classmethod:</p>
<pre><code> log.info(self.sftp.put(payloadPath, '%s/%s' % (targetDir,payloadPath), callback=self.TransferStats))
</code></pre>
<p><strong>EDIT</strong> : You have the same problem in the following line :</p>
<pre><code>self.TransferStats().counter=0
</code></pre>
<p>Remove the parentheses :</p>
<pre><code>self.TransferStats.counter=0
</code></pre>
<p>Also, your <code>counter</code> attribute on <code>TransferStats</code> is a hidden a global, resetted at each <code>Transmit</code> call.</p>
| 2 | 2016-08-12T22:25:49Z | [
"python",
"python-2.7",
"callback"
] |
Panda AssertionError columns passed, passed data had 2 columns | 38,927,230 | <p>I am working on Azure ML implementation on text analytics with NLTK, the following execution is throwing </p>
<pre><code>AssertionError: 1 columns passed, passed data had 2 columns\r\nProcess returned with non-zero exit code 1
</code></pre>
<p>Below is the code </p>
<pre><code># The script MUST include the following function,
# which is the entry point for this module:
# Param<dataframe1>: a pandas.DataFrame
# Param<dataframe2>: a pandas.DataFrame
def azureml_main(dataframe1 = None, dataframe2 = None):
# import required packages
import pandas as pd
import nltk
import numpy as np
# tokenize the review text and store the word corpus
word_dict = {}
token_list = []
nltk.download(info_or_id='punkt', download_dir='C:/users/client/nltk_data')
nltk.download(info_or_id='maxent_treebank_pos_tagger', download_dir='C:/users/client/nltk_data')
for text in dataframe1["tweet_text"]:
tokens = nltk.word_tokenize(text.decode('utf8'))
tagged = nltk.pos_tag(tokens)
# convert feature vector to dataframe object
dataframe_output = pd.DataFrame(tagged, columns=['Output'])
return [dataframe_output]
</code></pre>
<p>Error is throwing here </p>
<pre><code> dataframe_output = pd.DataFrame(tagged, columns=['Output'])
</code></pre>
<p>I suspect this to be the tagged data type passed to dataframe, can some one let me know the right approach to add this to dataframe.</p>
| 1 | 2016-08-12T22:23:17Z | 38,927,256 | <p>Try this:</p>
<pre><code>dataframe_output = pd.DataFrame(tagged, columns=['Output', 'temp'])
</code></pre>
| 1 | 2016-08-12T22:26:09Z | [
"python",
"pandas",
"dataframe",
"nltk",
"azure-ml"
] |
shortcuts in append function in python | 38,927,266 | <p>I am programming newbie here, so sorry for these elementary questions.
I am dealing with python code which has vectors and a lot of append function. For example lines like these</p>
<pre><code>a = [[],[],[]]
a[0].append(1)
a[1].append(2)
a[2].append(5)
</code></pre>
<p>So I was wondering if the above lines could be rewritten as a shorter code. Since this is a vector I guess numpy arrays could be useful here. But i have heard that append function does not goes well with numpy. I would appreciate any help on this.</p>
<p>Regards.</p>
| 0 | 2016-08-12T22:28:14Z | 38,927,309 | <p>the most pythonic way I can think of to create and then append to the list of lists. Best for Python 3 where <code>zip</code> is a generator function.</p>
<pre><code>a = [[] for i in range(0,3)]
for i,j in zip(a,[1,2,5]):
i.append(j)
</code></pre>
<p>For python 2, <code>zip</code> will allocate a lot of memory if lists are huge, so prefer the more classic:</p>
<pre><code>a = [[] for i in range(0,3)]
b=[1,2,5]
for i,l in enumerate(a):
l.append(b[i])
</code></pre>
| 1 | 2016-08-12T22:33:46Z | [
"python",
"numpy",
"append"
] |
Python: Fill space between two lines drawn on a Basemap | 38,927,272 | <p>I have drawn two lines on a Basemap created in python. Each line is created with two points (start and end points). Both lines originate from the same point.</p>
<pre><code>m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
m.plot([x, x1], [y, y1])
m.plot([x, x2], [y, y2])
</code></pre>
<p>Resulting in a plot like this:
<a href="http://i.stack.imgur.com/RQt2p.png" rel="nofollow"><img src="http://i.stack.imgur.com/RQt2p.png" alt="enter image description here"></a></p>
<p>I would like to shade in the area between these two lines (the larger slice on the lower left). I know it involves some use of fill_between() and/or fill_betweenx(), but I can't figure it out.</p>
<p>More generally:
I have two lines originating from a center point. The lines represent the sweep range of a radar. I want to fill in the area NOT included in this sweep range. This needs to work for any two lines (any sweep range). I can also pull out the beginning and ending azimuths in degrees of the sweep, if we need that.</p>
<p>Thanks for your help. </p>
| 0 | 2016-08-12T22:29:09Z | 38,938,531 | <p>Here is my solution. Wish it help!</p>
<pre><code>from matplotlib.patches import Polygon
m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
x,y = (119.46 + 121.406)/2.0,(21.62+23.43)/2.0
x1,y1 = 120.0,24.0
x2,y2 = 124.0,22.0
lons = np.array([x1,x, x2, x2,x1])
lats = np.array([y1, y, y2, y1,y1])
x, y = m( lons, lats )
xy = zip(x,y)
poly = Polygon( xy, facecolor='b', alpha=0.75 ,edgecolor = 'r', zorder =15,linewidth = 2)
plt.gca().add_patch(poly)
m.drawparallels(np.arange(21.0,24.0,0.5),labels=[1,0,0,1],size=12,linewidth=0,color= '#FFFFFF')
m.drawmeridians(np.arange(119.8,121.5,0.5),labels=[1,0,0,1],size=12,linewidth=0)
</code></pre>
<p><a href="http://i.stack.imgur.com/q2Isv.png" rel="nofollow"><img src="http://i.stack.imgur.com/q2Isv.png" alt="enter image description here"></a></p>
| 0 | 2016-08-14T01:58:43Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
Python: Fill space between two lines drawn on a Basemap | 38,927,272 | <p>I have drawn two lines on a Basemap created in python. Each line is created with two points (start and end points). Both lines originate from the same point.</p>
<pre><code>m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
m.plot([x, x1], [y, y1])
m.plot([x, x2], [y, y2])
</code></pre>
<p>Resulting in a plot like this:
<a href="http://i.stack.imgur.com/RQt2p.png" rel="nofollow"><img src="http://i.stack.imgur.com/RQt2p.png" alt="enter image description here"></a></p>
<p>I would like to shade in the area between these two lines (the larger slice on the lower left). I know it involves some use of fill_between() and/or fill_betweenx(), but I can't figure it out.</p>
<p>More generally:
I have two lines originating from a center point. The lines represent the sweep range of a radar. I want to fill in the area NOT included in this sweep range. This needs to work for any two lines (any sweep range). I can also pull out the beginning and ending azimuths in degrees of the sweep, if we need that.</p>
<p>Thanks for your help. </p>
| 0 | 2016-08-12T22:29:09Z | 38,964,397 | <p>I solved this by using a wedge patch object and using the azimuths of the radar sweeps.</p>
<pre><code>fig, ax = plt.subplots()
m = Basemap(llcrnrlon=119.46,llcrnrlat=21.62,urcrnrlon=121.406,urcrnrlat=23.43, resolution = 'i', epsg=3825)
m.drawcoastlines()
wedge = Wedge((x,y), 200000, az2, az1, edgecolor="none", color = 'grey', alpha = 0.2)
ax.add_patch(wedge)
</code></pre>
| 0 | 2016-08-15T23:19:07Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
numpy.column_stack with numeric and string arrays | 38,927,294 | <p>I have several arrays, some of them have float numbers and others have string characters, all the arrays have the same length. When I try to use numpy.column_stack in these arrays, this function convert to string the float numbers, for example:</p>
<pre><code>a = np.array([3.4,3.4,6.4])
b = np.array(['holi','xlo','xlo'])
B = np.column_stack((a,b))
print B
>>> [['3.4' 'holi']
['3.4' 'xlo']
['3.4' 'xlo']
type(B[0,0])
>>> numpy.string
</code></pre>
<p>Why? It's possible to avoid it?
Thanks a lot for your time.</p>
| 1 | 2016-08-12T22:31:49Z | 38,927,331 | <p>To store such mixed type data, most probably you would be required to store them as Object dtype arrays or use <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow"><code>structured arrays</code></a>. Going with the Object dtype arrays, we could convert either of the input arrays to an Object dtype upfront and then stack it alongside the rest of the arrays to be stacked. The rest of the arrays would be converted automatically to Object dtype to give us a stacked array of that type. Thus, we would have an implementation like so-</p>
<pre><code>np.column_stack((a.astype(np.object),b))
</code></pre>
<p>Sample run to show how to construct a stacked array and retrieve the individual arrays back -</p>
<pre><code>In [88]: a
Out[88]: array([ 3.4, 3.4, 6.4])
In [89]: b
Out[89]:
array(['holi', 'xlo', 'xlo'],
dtype='|S4')
In [90]: out = np.column_stack((a.astype(np.object),b))
In [91]: out
Out[91]:
array([[3.4, 'holi'],
[3.4, 'xlo'],
[6.4, 'xlo']], dtype=object)
In [92]: out[:,0].astype(float)
Out[92]: array([ 3.4, 3.4, 6.4])
In [93]: out[:,1].astype(str)
Out[93]:
array(['holi', 'xlo', 'xlo'],
dtype='|S4')
</code></pre>
| 2 | 2016-08-12T22:37:22Z | [
"python",
"numpy"
] |
numpy.column_stack with numeric and string arrays | 38,927,294 | <p>I have several arrays, some of them have float numbers and others have string characters, all the arrays have the same length. When I try to use numpy.column_stack in these arrays, this function convert to string the float numbers, for example:</p>
<pre><code>a = np.array([3.4,3.4,6.4])
b = np.array(['holi','xlo','xlo'])
B = np.column_stack((a,b))
print B
>>> [['3.4' 'holi']
['3.4' 'xlo']
['3.4' 'xlo']
type(B[0,0])
>>> numpy.string
</code></pre>
<p>Why? It's possible to avoid it?
Thanks a lot for your time.</p>
| 1 | 2016-08-12T22:31:49Z | 38,927,737 | <p>The easiest structured array approach is with the <code>rec.fromarrays</code> function:</p>
<pre><code>In [1411]: a=np.array([3.4,3.4,6.4]); b=np.array(['holi','xlo','xlo'])
In [1412]: B = np.rec.fromarrays([a,b],names=['a','b'])
In [1413]: B
Out[1413]:
rec.array([(3.4, 'holi'), (3.4, 'xlo'), (6.4, 'xlo')],
dtype=[('a', '<f8'), ('b', '<U4')])
In [1414]: B['a']
Out[1414]: array([ 3.4, 3.4, 6.4])
In [1415]: B['b']
Out[1415]:
array(['holi', 'xlo', 'xlo'],
dtype='<U4')
</code></pre>
<p>Check its docs for more parameters. But it basically constructs an empty array of the correct compound dtype, and copies your arrays to the respective fields.</p>
| 2 | 2016-08-12T23:30:10Z | [
"python",
"numpy"
] |
Python - Capture Individaul value result of request | 38,927,321 | <p>I am new to Python. I am trying to capture individual values that returned from the request result.</p>
<p>Here is part of my code to send the request:</p>
<pre><code>opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_payload)
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
# Perform the request
result = opener.open(request).read()
print result
</code></pre>
<p>The print result gives me the output below (messy formatting)</p>
<pre><code>{"@odata.context":"https://outlook.office365.com/api/v1.0/$metadata#Me/Events(Start,End)/$entity","@odata.id":"https://outlook.office365.com
/api/v1.0/Users('user1@domain.com')/Events('AAMkADA1OWVjOTkxLTlmYmEtNDAwMS04YWU3LTNkNYDHE4YjU2OGI1ZABGBBBBBBD_fa49_h8OTJ5eGdjSTEF3BwBOcC
SV9aNzSoXurwI4R0IgBBBBBBBENAABOcCSV9aNzSoXurwI4R0IgAAHn0Cy0AAA=')","@odata.etag":"W/\"TnAklfWjc0qF7q8COEdDTHDAB5+uOdw==\"","Id":"AAMkADA1OWVjO
TkxLTlmYmEtNDAwMS04YWU3LTMHKNDE2YjU2OGI1ZABGAAAAAAD_fa49_h8OTJ5eGdjSTEF3BwBOcCSV9aNzSoXurwI4R0IgCCCCCCCENAABOcCSV9aNzSoXurwI4R0IgAAHn0Cy0AAA="
,"Start":"2016-08-13T15:00:00-07:00","End":"2016-08-13T16:00:00-07:00"}
</code></pre>
<p>Is there a way that I load the result into json.load and capture individual values for @odata.context, @odata.id, @odata.etag, Id, Start, End?</p>
<p>I tried this, but no luck.</p>
<pre><code>data = json.load(result)
print data["@odata.context"]
</code></pre>
| -1 | 2016-08-12T22:35:27Z | 38,927,551 | <p>Have you tried using json loads. load in the background uses the method .read() so if you wanted to use it you must use a file like object like StringIO or file/open</p>
<p>Like this:</p>
<pre><code>import urllib2
import json
import base64
test_load = "foo=bar"
user = "test"
pwd = "test"
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request("http://scooterlabs.com/echo.json?%s" % test_load, data=b'data')
auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
request.add_header('Authorization', 'Basic %s' % auth)
request.add_header('Content-Type', 'application/json')
request.add_header('Accept', 'application/json')
request.get_method = lambda: 'POST'
result = opener.open(request).read()
jsons = json.loads(result)
print("FULL: %s" % result)
print(jsons[u'method'])
print(jsons[u'request'])
</code></pre>
<p><strong>Edit:</strong>
It seems as if the comments already answered the question... sorry</p>
| 0 | 2016-08-12T23:05:23Z | [
"python"
] |
Splitting multiple pipe delimited values in multiple columns of a comma delimited CSV and mapping them to each other | 38,927,384 | <p>I have a csv with comma delimiters that has multiple values in a column that are delimited by a pipe and I need to map them to another column with multiple pipe delimited values and then give them their own row along with data in the original row that doesn't have multiple values. My CSV looks like this (with commas between the categories):</p>
<pre><code>row name city amount
1 frank | john | dave toronto | new york | anaheim 10
2 george | joe | fred fresno | kansas city | reno 20
</code></pre>
<p>I need it to look like this:</p>
<pre><code>row name city amount
1 frank toronto 10
2 john new york 10
3 dave anaheim 10
4 george fresno 20
5 joe kansas city 20
6 fred reno 20
</code></pre>
| 1 | 2016-08-12T22:42:45Z | 38,927,650 | <p>Maybe not the nicest but working solution:
(works with no piped lines and for different pipe-length)</p>
<pre><code>df = pd.read_csv('<your_data>.csv')
str_split = ' | '
# Calculate maximum length of piped (' | ') values
df['max_len'] = df[['name', 'city']].apply(lambda x: max(len(x[0].split(str_split)),
len(x[0].split(str_split))), axis=1)
max_len = df['max_len'].max()
# Split '|' piped cell values into columns (needed at unpivot step)
# Create as many new 'name_<x>' & 'city_<x>' columns as 'max_len'
df[['name_{}'.format(i) for i in range(max_len)]] = df['name'].apply(lambda x: \
pd.Series(x.split(str_split)))
df[['city_{}'.format(i) for i in range(max_len)]] = df['city'].apply(lambda x: \
pd.Series(x.split(str_split)))
# Unpivot 'name_<x>' & 'city_<x>' columns into rows
df_pv_name = pd.melt(df, value_vars=['name_{}'.format(i) for i in range(max_len)],
id_vars=['amount'])
df_pv_city = pd.melt(df, value_vars=['city_{}'.format(i) for i in range(max_len)],
id_vars=['amount'])
# Rename upivoted columns (these are the final columns)
df_pv_name = df_pv_name.rename(columns={'value':'name'})
df_pv_city = df_pv_city.rename(columns={'value':'city'})
# Rename 'city_<x>' values (rows) to be 'key' for join (merge)
df_pv_city['variable'] = df_pv_city['variable'].map({'city_{}'.format(i):'name_{}'\
.format(i) for i in range(max_len)})
# Join unpivoted 'name' & 'city' dataframes
df_res = df_pv_name.merge(df_pv_city, on=['variable', 'amount'])
# Drop 'variable' column and NULL rows if you have not equal pipe-length in original rows
# If you want to drop any NULL rows then replace 'all' to 'any'
df_res = df_res.drop(['variable'], axis=1).dropna(subset=['name', 'city'], how='all',
axis=0).reset_index(drop=True)
</code></pre>
<p>The result is:</p>
<pre><code> amount name city
0 10 frank toronto
1 20 george fresno
2 10 john new york
3 20 joe kansas city
4 10 dave anaheim
5 20 fred reno
</code></pre>
<p>Another test input: </p>
<pre><code> name city amount
0 frank | john | dave | joe | bill toronto | new york | anaheim | los angeles | caracas 10
1 george | joe | fred fresno | kansas city 20
2 danny miami 30
</code></pre>
<p>Result of this test (if you don't want <code>NaN</code> rows then replace <code>how='all'</code> to <code>how='any'</code> in the code at merging):</p>
<pre><code> amount name city
0 10 frank toronto
1 20 george fresno
2 30 danny miami
3 10 john new york
4 20 joe kansas city
5 10 dave anaheim
6 20 fred NaN
7 10 joe los angeles
8 10 bill caracas
</code></pre>
| 1 | 2016-08-12T23:18:03Z | [
"python",
"csv"
] |
Splitting multiple pipe delimited values in multiple columns of a comma delimited CSV and mapping them to each other | 38,927,384 | <p>I have a csv with comma delimiters that has multiple values in a column that are delimited by a pipe and I need to map them to another column with multiple pipe delimited values and then give them their own row along with data in the original row that doesn't have multiple values. My CSV looks like this (with commas between the categories):</p>
<pre><code>row name city amount
1 frank | john | dave toronto | new york | anaheim 10
2 george | joe | fred fresno | kansas city | reno 20
</code></pre>
<p>I need it to look like this:</p>
<pre><code>row name city amount
1 frank toronto 10
2 john new york 10
3 dave anaheim 10
4 george fresno 20
5 joe kansas city 20
6 fred reno 20
</code></pre>
| 1 | 2016-08-12T22:42:45Z | 38,927,717 | <p>Given a row:</p>
<pre><code>['1','frank|joe|dave', 'toronto|new york|anaheim', '20']
</code></pre>
<p>you can use</p>
<pre><code>itertools.izip_longest(*[value.split('|') for value in row])
</code></pre>
<p>on it to obtain following structure:</p>
<pre><code>[('1', 'frank', 'toronto', '20'),
(None, 'joe', 'new york', None),
(None, 'dave', 'anaheim', None)]
</code></pre>
<p>Here we want to replace all <code>None</code> values with last seen value in corresponding column. Can be done when looping over result.</p>
<p>So given a TSV already splitted by tabs following code should do the trick:</p>
<pre><code>import itertools
def flatten_tsv(lines):
result = []
for line in lines:
flat_lines = itertools.izip_longest(*[value.split('|') for value in line])
for flat_line in flat_lines:
result.append([result[-1][i] if v is None else v
for i, v in enumerate(flat_line)])
return result
</code></pre>
| 1 | 2016-08-12T23:27:24Z | [
"python",
"csv"
] |
How can I perform word tokenization of a text, using the tokenize annotator, with pycorenlp (Python wrapper for Stanford CoreNLP), without ssplit? | 38,927,415 | <p>I am trying to run <a href="https://github.com/smilli/py-corenlp" rel="nofollow">pycorenlp</a>, which is a Python wrapper for <a href="http://stanfordnlp.github.io/CoreNLP/" rel="nofollow">Stanford CoreNLP</a>, to perform word tokenization of a text, using the <a href="http://stanfordnlp.github.io/CoreNLP/tokenize.html#description" rel="nofollow"><code>tokenize</code></a> annotator.</p>
<p>I first launch a Stanford CoreNLP: </p>
<pre><code>java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 50000
</code></pre>
<p>then run:</p>
<pre><code>from pycorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP('http://localhost:9000')
text_input = 'this is a test.'
print('text_input: {0}'.format(text_input))
text_output = nlp.annotate(text_input, properties={
'annotators': 'tokenize',
'outputFormat': 'json'
})
print('text_output: {0}'.format(text_output))
</code></pre>
<p>Surprisingly, this gives no output:</p>
<pre><code>text_input: this is a test.
text_output: {}
</code></pre>
<p>Why?</p>
<hr>
<p>If I add the <a href="http://stanfordnlp.github.io/CoreNLP/ssplit.html" rel="nofollow"><code>ssplit</code></a>, then <code>text_output</code> isn't empty anymore:</p>
<pre><code>text_input = 'this is a test.'
print('text_input: {0}'.format(text_input))
text_output = nlp.annotate(text_input, properties={
'annotators': 'tokenize,ssplit',
'outputFormat': 'json'
})
print('text_output: {0}'.format(text_output))
</code></pre>
<p>outputs:</p>
<pre><code>text_input: this is a test.
text_output: {u'sentences': [{u'parse': u'SENTENCE_SKIPPED_OR_UNPARSABLE', u'index': 0, u'tokens': [{u'index': 1, u'word': u'this', u'after': u' ', u'characterOffsetEnd': 4, u'characterOffsetBegin': 0, u'originalText': u'this', u'before': u''}, {u'index': 2, u'word': u'is', u'after': u' ', u'characterOffsetEnd': 7, u'characterOffsetBegin': 5, u'originalText': u'is', u'before': u' '}, {u'index': 3, u'word': u'a', u'after': u' ', u'characterOffsetEnd': 9, u'characterOffsetBegin': 8, u'originalText': u'a', u'before': u' '}, {u'index': 4, u'word': u'test', u'after': u'', u'characterOffsetEnd': 14, u'characterOffsetBegin': 10, u'originalText': u'test', u'before': u' '}, {u'index': 5, u'word': u'.', u'after': u'', u'characterOffsetEnd': 15, u'characterOffsetBegin': 14, u'originalText': u'.', u'before': u''}]}]}
</code></pre>
<p>Can't I use the <a href="http://stanfordnlp.github.io/CoreNLP/tokenize.html#description" rel="nofollow"><code>tokenize</code></a> annotator without having to use the <a href="http://stanfordnlp.github.io/CoreNLP/ssplit.html" rel="nofollow"><code>ssplit</code></a> annotator?</p>
<p>The <a href="http://stanfordnlp.github.io/CoreNLP/dependencies.html" rel="nofollow">overview of the annotator dependencies</a> seems to say I should be able to use the <a href="http://stanfordnlp.github.io/CoreNLP/tokenize.html#description" rel="nofollow"><code>tokenize</code></a> annotator alone:</p>
<p><a href="http://i.stack.imgur.com/cqPgh.png" rel="nofollow"><img src="http://i.stack.imgur.com/cqPgh.png" alt="enter image description here"></a></p>
| 0 | 2016-08-12T22:45:49Z | 38,931,392 | <p>You are right, the API doesn't seem to be responding if the only annotator provided is 'tokenize'. It should be have defaulted to <code>PTBTokenizer</code> as mentioned in the docs. Another relevant question is present here: <a href="http://stackoverflow.com/q/21742186/1005215">Stanford CoreNLP gives NullPointerException</a> . However, if you only want to tokenize and do nothing else, you can do:</p>
<pre><code>nwani@ip-172-31-43-96:~/stanford-corenlp-full-2015-12-09$ ~/jre1.8.0_101/bin/java -mx4g -cp "*" edu.stanford.nlp.process.PTBTokenizer <<< "this is a test"
this
is
a
test
PTBTokenizer tokenized 4 tokens at 19.11 tokens per second.
</code></pre>
| 1 | 2016-08-13T09:43:17Z | [
"python",
"nlp",
"stanford-nlp",
"tokenize"
] |
Impala/SQL: select a sub-table and join | 38,927,422 | <p>I am trying to use the following code to find the last month data in table_1, then left join it with table_2:</p>
<pre><code>import pandas as pd
query = 'select * from table_1 where table_1.ts > "2016-07-12 00:00:00" as recent_table left join table_2 on table_1.t2__fk=table_2.id'
cursor = impala_con.cursor()
cursor.execute('USE my_db')
cursor.execute(query)
df_result = as_pandas(cursor)
df_result
</code></pre>
<p>but got the error below:</p>
<pre><code>HiveServer2Error: AnalysisException: Syntax error in line 1:
...s > "2016-07-10 00:00:00" as recent_table left join table_2...
^
Encountered: AS
Expected: AND, BETWEEN, DIV, GROUP, HAVING, ILIKE, IN, IREGEXP, IS, LIKE, LIMIT, NOT, OFFSET, OR, ORDER, REGEXP, RLIKE, UNION
CAUSED BY: Exception: Syntax error
</code></pre>
<p>Does anyone know what I missed here? And what's the proper way to achieve this goal. Thanks!</p>
| 0 | 2016-08-12T22:46:19Z | 38,927,484 | <p>That's cause your query syntax is wrong. You can't use alias for conditional statement as pointed below. Aliases are used only for table name and column name.</p>
<pre><code>where table_1.ts > "2016-07-12 00:00:00" as recent_table
</code></pre>
<p>The correct query would be</p>
<pre><code>select t1.*
from table_1 t1
left join table_2 t2 on t1.t2__fk = t2.id
where t1.ts > "2016-07-12 00:00:00";
</code></pre>
| 1 | 2016-08-12T22:56:02Z | [
"python",
"sql",
"impala"
] |
How to find Spark RDD created in different cores of a computer | 38,927,439 | <p>I just wanted to educate myself more on Spark. So wanted to ask this question. </p>
<p>I have Spark currently installed on my local machine. Its a Mach with 16GB. </p>
<p>I have connected a Jupyter notebook running with Pyspark. </p>
<p>So now when I do any coding in that notebook, like reading the data and converting the data into Spark DataFrame, I wanted to check:</p>
<p>1). Where all the dataset is distributed on local machine. Like does it distribute the dataset using different cores of CPU etc?. Is there a way to find that out? </p>
<p>2). Running the code and computation just using Jupyter notebook without spark is different from running Jupyter notebook with Pyspark? Like the first one just uses one core of the machine and runs using one thread while Jupyter notebook with Pyspark runs the code and computing on different cores of CPU with multi-threading/processing? Is this understanding correct?. </p>
<p>Is there a way to check these. </p>
<p>Thanks</p>
| 0 | 2016-08-12T22:48:21Z | 38,929,653 | <p>Jupyter has mainly three parts Jupyter Notebook, Jupyter Clients and Kernels. <a href="http://jupyter.readthedocs.io/en/latest/architecture/how_jupyter_ipython_work.html" rel="nofollow">http://jupyter.readthedocs.io/en/latest/architecture/how_jupyter_ipython_work.html</a></p>
<p><em>Here is short note on Kernel from Jupyter homepage.</em></p>
<blockquote>
<p>Kernels are processes that run interactive code in a particular
programming language and return output to the user. Kernels also
respond to tab completion and introspection requests.</p>
</blockquote>
<p>Jupyter's job is to communicate between the Kernel(Like python kernel, spark kernel ..) and web interface(your notebook). So under the hood spark is running drivers and executors for you, Jupyter helps in communicating with the spark driver. </p>
<blockquote>
<p>1). Where all the dataset is distributed on local machine. Like does
it distribute the dataset using different cores of CPU etc?. Is there
a way to find that out?</p>
</blockquote>
<p>Spark will spawn n number of executors(process responsible for executing a task) as specified using <code>--num-executors</code>, executors are managed by a spark driver(program/process responsible for running the Job over the Spark Engine). So the number of executors are specified while you run a spark program, you will find this kernel conf directory.</p>
<blockquote>
<p>2). Running the code and computation just using Jupyter notebook
without spark is different from running Jupyter notebook with Pyspark?
Like the first one just uses one core of the machine and runs using
one thread while Jupyter notebook with Pyspark runs the code and
computing on different cores of CPU with multi-threading/processing?
Is this understanding correct?.</p>
</blockquote>
<p>Yes, as I explained Jupyter is merely an interface letting you run code. Under the hood, Jupyter connects to Kernels be it normal Python or Apache Spark.</p>
<p>Spark has it's own good UI to monitor jobs, by default it runs on spark master server on port 4040. In your case, it will available on <a href="http://localhost:4040" rel="nofollow">http://localhost:4040</a></p>
| 0 | 2016-08-13T05:46:39Z | [
"python",
"apache-spark",
"ipython"
] |
Pandas boxplot with ranges in x-axis | 38,927,459 | <p>I have the foll. dataframe in pandas:</p>
<pre><code>value combined_delta
100 7
100 45
100 49
100 12
100 71
94.09 21
91.42 45
88.7 36
87.26 34
77.61 55
76.3 28
73.81 89
71 80
69.5 27
67.45 12
66.96 127
66.18 43
54.48 68
54.15 23
53.29 48
53.29 49
53.25 302
51.99 24
51.99 116
50.73 22
49.7 101
31.05 107
31 63
30.19 116
30.12 58
29.38 31
29.18 8
29 104
28.6 61
28.6 63
28.56 60
28.11 35
27.36 50
27.32 63
26.87 103
26.87 257
26.42 55
26.35 85
26.1 27
25.79 21
25.79 66
25.66 77
25.53 9
25.46 92
25.46 248
24.67 15
24.6 93
24.39 5
24.01 28
24.01 82
23.86 19
23.18 133
22.71 41
22.62 37
21.81 43
21.52 34
21.43 35
21.23 40
21.23 25
20 75
19.98 31
19.98 44
19.84 12
19.82 62
18.83 26
18.71 202
18.02 7
18 28
17.99 39
17.75 40
17.68 81
17.67 16
17.55 54
17.25 13
16.63 19
12.14 22
12.01 24
12 59
11.95 49
11.54 39
</code></pre>
<p>How can I make a boxplot where the x-axis shows ranges for <code>value</code>: 0-20, 20-40, 40-60,60-80,80-100 and the y-axis shows <code>combined_delta</code> values?</p>
<p>I can use seaborn like this:</p>
<pre><code>ax = sns.boxplot(x="value", y="combined_delta", data=df)
</code></pre>
<p>However, this will not create the ranges from the x-axis the way I want</p>
| 2 | 2016-08-12T22:52:28Z | 38,927,562 | <pre><code>cut = pd.cut(df.value, [0, 20, 40, 60, 80, 100])
boxdf = df.groupby(cut) \
.apply(lambda df: df.combined_delta.reset_index(drop=True)) \
.unstack(0)
sns.boxplot(data=boxdf);
</code></pre>
<p><a href="http://i.stack.imgur.com/Ulbxo.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ulbxo.png" alt="enter image description here"></a></p>
| 3 | 2016-08-12T23:06:38Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
Pandas boxplot with ranges in x-axis | 38,927,459 | <p>I have the foll. dataframe in pandas:</p>
<pre><code>value combined_delta
100 7
100 45
100 49
100 12
100 71
94.09 21
91.42 45
88.7 36
87.26 34
77.61 55
76.3 28
73.81 89
71 80
69.5 27
67.45 12
66.96 127
66.18 43
54.48 68
54.15 23
53.29 48
53.29 49
53.25 302
51.99 24
51.99 116
50.73 22
49.7 101
31.05 107
31 63
30.19 116
30.12 58
29.38 31
29.18 8
29 104
28.6 61
28.6 63
28.56 60
28.11 35
27.36 50
27.32 63
26.87 103
26.87 257
26.42 55
26.35 85
26.1 27
25.79 21
25.79 66
25.66 77
25.53 9
25.46 92
25.46 248
24.67 15
24.6 93
24.39 5
24.01 28
24.01 82
23.86 19
23.18 133
22.71 41
22.62 37
21.81 43
21.52 34
21.43 35
21.23 40
21.23 25
20 75
19.98 31
19.98 44
19.84 12
19.82 62
18.83 26
18.71 202
18.02 7
18 28
17.99 39
17.75 40
17.68 81
17.67 16
17.55 54
17.25 13
16.63 19
12.14 22
12.01 24
12 59
11.95 49
11.54 39
</code></pre>
<p>How can I make a boxplot where the x-axis shows ranges for <code>value</code>: 0-20, 20-40, 40-60,60-80,80-100 and the y-axis shows <code>combined_delta</code> values?</p>
<p>I can use seaborn like this:</p>
<pre><code>ax = sns.boxplot(x="value", y="combined_delta", data=df)
</code></pre>
<p>However, this will not create the ranges from the x-axis the way I want</p>
| 2 | 2016-08-12T22:52:28Z | 38,927,580 | <p>Use <code>pd.cut</code> to create the groups you want and plot <code>combined_delta</code> against those.</p>
<pre><code>df['value_group'] = pd.cut(df['value'], bins=range(0, 101, 20))
ax = sns.boxplot(x="value_group", y="combined_delta", data=df)
</code></pre>
<p><a href="http://i.stack.imgur.com/0UIfM.png" rel="nofollow"><img src="http://i.stack.imgur.com/0UIfM.png" alt="Boxplot"></a></p>
| 3 | 2016-08-12T23:09:19Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
AttributeError: 'Ui_Login' object has no attribute 'GetTable' | 38,927,480 | <p>Im creating a login and signup page that links to other GUI using PyQt. Most of the code works but when i try to sign up a new user, it gives me a <strong>AttributeError: 'Ui_Login' object has no attribute 'GetTable'</strong>. GetTable is defined in the code for the databse created with MySQl whic is called into the Login class and Signup class.
Please in new to python and programming in general. Sorry if this question seems daft. but i have read a lot on previously asked ones and i cant seem to understand what it is saying. Thanks</p>
<pre><code># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Login.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
import sys
import DBmanager as db
from PyQt4 import QtCore, QtGui
from newuser import Ui_Form
from createprofile import Ui_StudentLogin
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
#######SIGN IN/ LOG IN#################################################################################################
class Ui_Login(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.dbu = db.DatabaseUtility('UsernamePassword_DB', 'masterTable')
self.setupUi(self)
self.confirm = None
def setupUi(self, Login):
Login.setObjectName(_fromUtf8("Form"))
Login.resize(400, 301)
self.label = QtGui.QLabel(Login)
self.label.setGeometry(QtCore.QRect(60, 60, 71, 21))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Login)
self.label_2.setGeometry(QtCore.QRect(60, 120, 81, 21))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.userName = QtGui.QLineEdit(Login)
self.userName.setGeometry(QtCore.QRect(140, 60, 151, 21))
self.userName.setObjectName(_fromUtf8("userName"))
self.passWord = QtGui.QLineEdit(Login)
self.passWord.setGeometry(QtCore.QRect(140, 120, 151, 21))
self.passWord.setObjectName(_fromUtf8("passWord"))
self.label_3 = QtGui.QLabel(Login)
self.label_3.setGeometry(QtCore.QRect(160, 10, 131, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.loginButton1 = QtGui.QPushButton(Login)
self.loginButton1.setGeometry(QtCore.QRect(40, 210, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.loginButton1.setFont(font)
self.loginButton1.setObjectName(_fromUtf8("loginButton1"))
self.loginButton1.clicked.connect(self.login_Button1)
self.signUpButton = QtGui.QPushButton(Login)
self.signUpButton.setGeometry(QtCore.QRect(160, 210, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.signUpButton.setFont(font)
self.signUpButton.setObjectName(_fromUtf8("signUpButton"))
self.signUpButton.clicked.connect(self.signUp_Button)
self.cancel1 = QtGui.QPushButton(Login)
self.cancel1.setGeometry(QtCore.QRect(280, 210, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.cancel1.setFont(font)
self.cancel1.setObjectName(_fromUtf8("cancel1"))
self.connect(self, QtCore.SIGNAL('triggered()'), self.cancel_1)
self.retranslateUi(Login)
QtCore.QMetaObject.connectSlotsByName(Login)
def retranslateUi(self, Login):
Login.setWindowTitle(_translate("Form", "Login", None))
self.label.setText(_translate("Form", "USERNAME", None))
self.label_2.setText(_translate("Form", "PASSWORD", None))
self.label_3.setText(_translate("Form", "LOGIN PAGE", None))
self.loginButton1.setText(_translate("Form", "LOGIN", None))
self.signUpButton.setText(_translate("Form", "SIGN UP", None))
self.cancel1.setText(_translate("Form", "CANCEL", None))
@QtCore.pyqtSignature("on_cancel1_clicked()")
def cancel_1(self):
self.close()
@QtCore.pyqtSignature("on_loginButton1_clicked()")
def login_Button1(self):
username = self.userName.text()
password = self.passWord.text()
if not username:
QtGui.QMessageBox.warning(self, 'Guess What?', 'Username Missing!')
elif not password:
QtGui.QMessageBox.warning(self, 'Guess What?', 'Password Missing!')
else:
self.AttemptLogin(username, password)
def AttemptLogin(self, username, password):
t = self.dbu.GetTable()
print (t)
for col in t:
if username == col[1]:
if password == col[2]:
QtGui.QMessageBox.information(self, 'WELCOME', 'Success!!')
self.createProfilePage()
self.close()
else:
QtGui.QMessageBox.warning(self, 'OOPS SORRY!', 'Password incorrect...')
return
def createProfilePage(self):
self.createprofile = Ui_StudentLogin()
self.createprofile.show()
@QtCore.pyqtSignature("on_signUpButton_clicked()")
def signUp_Button(self):
self.newuser = Ui_Form(self)
self.newuser.show()
#######SIGN UP/ CREATE NEW USER#################################################################################################
class Ui_Form(QtGui.QWidget):
def __init__(self,dbu):
QtGui.QWidget.__init__(self)
self.setupUi(self)
self.dbu = dbu
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(400, 300)
self.label = QtGui.QLabel(Form)
self.label.setGeometry(QtCore.QRect(60, 70, 51, 16))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.nameGet = QtGui.QLineEdit(Form)
self.nameGet.setGeometry(QtCore.QRect(120, 70, 191, 21))
self.nameGet.setObjectName(_fromUtf8("nameGet"))
self.label_2 = QtGui.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(50, 120, 46, 13))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(30, 170, 71, 16))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.regNoGet = QtGui.QLineEdit(Form)
self.regNoGet.setGeometry(QtCore.QRect(120, 120, 191, 21))
self.regNoGet.setObjectName(_fromUtf8("regNoGet"))
self.passWordGet = QtGui.QLineEdit(Form)
self.passWordGet.setGeometry(QtCore.QRect(120, 170, 191, 21))
self.passWordGet.setObjectName(_fromUtf8("passWordGet"))
self.label_4 = QtGui.QLabel(Form)
self.label_4.setGeometry(QtCore.QRect(100, 20, 181, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.nextButton = QtGui.QPushButton(Form)
self.nextButton.setGeometry(QtCore.QRect(140, 250, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.nextButton.setFont(font)
self.nextButton.setObjectName(_fromUtf8("nextButton"))
self.nextButton.clicked.connect(self.next_Button)
self.cancelButton = QtGui.QPushButton(Form)
self.cancelButton.setGeometry(QtCore.QRect(260, 250, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.cancelButton.setFont(font)
self.cancelButton.setObjectName(_fromUtf8("cancelButton"))
self.cancelButton.clicked.connect(self.cancel_Button)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "New User", None))
self.label.setText(_translate("Form", "NAME", None))
self.label_2.setText(_translate("Form", "REG. NO", None))
self.label_3.setText(_translate("Form", "PASSWORD", None))
self.label_4.setText(_translate("Form", " CREATE NEW USER", None))
self.nextButton.setText(_translate("Form", "SUBMIT", None))
self.cancelButton.setText(_translate("Form", "CANCEL", None))
@QtCore.pyqtSignature("on_cancelButton_clicked()")
def cancel_Button(self):
self.close()
@QtCore.pyqtSignature("on_nextButton_clicked()")
def next_Button(self):
username = self.nameGet.text()
password = self.passWordGet.text()
regno = self.regNoGet.text()
if not username:
QtGui.QMessageBox.warning(self, 'Warning', 'Username Missing')
elif not password:
QtGui.QMessageBox.warning(self, 'Warning!', 'Password Missing')
elif not regno:
QtGui.QMessageBox.warning(self, 'Warning!', 'RegNo Missing')
else:
t = self.dbu.GetTable()
print (t)
for col in t:
if username == col[1]:
QtGui.QMessageBox.warning(self, 'Dang it!', 'Username Taken. :(')
else:
self.dbu.AddEntryToTable (username, password, regno)
QtGui.QMessageBox.information(self, 'Awesome!!', 'User Added SUCCESSFULLY!')
self.close()
## def createProfileWindow(self):
## self.createprofile = Ui_StudentLogin()
## self.createprofile.show()
##
## def generate_report(self):
## data_line1 = self.nameGet.displayText()
## data_line2 = self.regNoGet.displayText()
## data_line3 = self.passWordGet.displayText()
## print data_line1
## print data_line2
## print data_line3
##
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Ui_Login()
ex.show()
sys.exit(app.exec_())
</code></pre>
| 1 | 2016-08-12T22:55:06Z | 38,927,673 | <p>Your code expects this line:</p>
<pre><code>db.DatabaseUtility('UsernamePassword_DB', 'masterTable')
</code></pre>
<p>to return an object with a <code>GetTable</code> method (and assign that object to <code>self.dbu</code>). Therefore when you call <code>self.dbu.GetTable()</code> you get an error if whatever was returned from:</p>
<pre><code>db.DatabaseUtility('UsernamePassword_DB', 'masterTable')
</code></pre>
<p>doesn't have that method. So check what:</p>
<pre><code>db.DatabaseUtility('UsernamePassword_DB', 'masterTable')
</code></pre>
<p>actually returns and adjust your code accordingly.</p>
| 0 | 2016-08-12T23:21:09Z | [
"python",
"pyqt"
] |
AttributeError: 'Ui_Login' object has no attribute 'GetTable' | 38,927,480 | <p>Im creating a login and signup page that links to other GUI using PyQt. Most of the code works but when i try to sign up a new user, it gives me a <strong>AttributeError: 'Ui_Login' object has no attribute 'GetTable'</strong>. GetTable is defined in the code for the databse created with MySQl whic is called into the Login class and Signup class.
Please in new to python and programming in general. Sorry if this question seems daft. but i have read a lot on previously asked ones and i cant seem to understand what it is saying. Thanks</p>
<pre><code># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Login.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
import sys
import DBmanager as db
from PyQt4 import QtCore, QtGui
from newuser import Ui_Form
from createprofile import Ui_StudentLogin
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
#######SIGN IN/ LOG IN#################################################################################################
class Ui_Login(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.dbu = db.DatabaseUtility('UsernamePassword_DB', 'masterTable')
self.setupUi(self)
self.confirm = None
def setupUi(self, Login):
Login.setObjectName(_fromUtf8("Form"))
Login.resize(400, 301)
self.label = QtGui.QLabel(Login)
self.label.setGeometry(QtCore.QRect(60, 60, 71, 21))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Login)
self.label_2.setGeometry(QtCore.QRect(60, 120, 81, 21))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.userName = QtGui.QLineEdit(Login)
self.userName.setGeometry(QtCore.QRect(140, 60, 151, 21))
self.userName.setObjectName(_fromUtf8("userName"))
self.passWord = QtGui.QLineEdit(Login)
self.passWord.setGeometry(QtCore.QRect(140, 120, 151, 21))
self.passWord.setObjectName(_fromUtf8("passWord"))
self.label_3 = QtGui.QLabel(Login)
self.label_3.setGeometry(QtCore.QRect(160, 10, 131, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.loginButton1 = QtGui.QPushButton(Login)
self.loginButton1.setGeometry(QtCore.QRect(40, 210, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.loginButton1.setFont(font)
self.loginButton1.setObjectName(_fromUtf8("loginButton1"))
self.loginButton1.clicked.connect(self.login_Button1)
self.signUpButton = QtGui.QPushButton(Login)
self.signUpButton.setGeometry(QtCore.QRect(160, 210, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.signUpButton.setFont(font)
self.signUpButton.setObjectName(_fromUtf8("signUpButton"))
self.signUpButton.clicked.connect(self.signUp_Button)
self.cancel1 = QtGui.QPushButton(Login)
self.cancel1.setGeometry(QtCore.QRect(280, 210, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.cancel1.setFont(font)
self.cancel1.setObjectName(_fromUtf8("cancel1"))
self.connect(self, QtCore.SIGNAL('triggered()'), self.cancel_1)
self.retranslateUi(Login)
QtCore.QMetaObject.connectSlotsByName(Login)
def retranslateUi(self, Login):
Login.setWindowTitle(_translate("Form", "Login", None))
self.label.setText(_translate("Form", "USERNAME", None))
self.label_2.setText(_translate("Form", "PASSWORD", None))
self.label_3.setText(_translate("Form", "LOGIN PAGE", None))
self.loginButton1.setText(_translate("Form", "LOGIN", None))
self.signUpButton.setText(_translate("Form", "SIGN UP", None))
self.cancel1.setText(_translate("Form", "CANCEL", None))
@QtCore.pyqtSignature("on_cancel1_clicked()")
def cancel_1(self):
self.close()
@QtCore.pyqtSignature("on_loginButton1_clicked()")
def login_Button1(self):
username = self.userName.text()
password = self.passWord.text()
if not username:
QtGui.QMessageBox.warning(self, 'Guess What?', 'Username Missing!')
elif not password:
QtGui.QMessageBox.warning(self, 'Guess What?', 'Password Missing!')
else:
self.AttemptLogin(username, password)
def AttemptLogin(self, username, password):
t = self.dbu.GetTable()
print (t)
for col in t:
if username == col[1]:
if password == col[2]:
QtGui.QMessageBox.information(self, 'WELCOME', 'Success!!')
self.createProfilePage()
self.close()
else:
QtGui.QMessageBox.warning(self, 'OOPS SORRY!', 'Password incorrect...')
return
def createProfilePage(self):
self.createprofile = Ui_StudentLogin()
self.createprofile.show()
@QtCore.pyqtSignature("on_signUpButton_clicked()")
def signUp_Button(self):
self.newuser = Ui_Form(self)
self.newuser.show()
#######SIGN UP/ CREATE NEW USER#################################################################################################
class Ui_Form(QtGui.QWidget):
def __init__(self,dbu):
QtGui.QWidget.__init__(self)
self.setupUi(self)
self.dbu = dbu
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(400, 300)
self.label = QtGui.QLabel(Form)
self.label.setGeometry(QtCore.QRect(60, 70, 51, 16))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.nameGet = QtGui.QLineEdit(Form)
self.nameGet.setGeometry(QtCore.QRect(120, 70, 191, 21))
self.nameGet.setObjectName(_fromUtf8("nameGet"))
self.label_2 = QtGui.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(50, 120, 46, 13))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(30, 170, 71, 16))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.regNoGet = QtGui.QLineEdit(Form)
self.regNoGet.setGeometry(QtCore.QRect(120, 120, 191, 21))
self.regNoGet.setObjectName(_fromUtf8("regNoGet"))
self.passWordGet = QtGui.QLineEdit(Form)
self.passWordGet.setGeometry(QtCore.QRect(120, 170, 191, 21))
self.passWordGet.setObjectName(_fromUtf8("passWordGet"))
self.label_4 = QtGui.QLabel(Form)
self.label_4.setGeometry(QtCore.QRect(100, 20, 181, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.nextButton = QtGui.QPushButton(Form)
self.nextButton.setGeometry(QtCore.QRect(140, 250, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.nextButton.setFont(font)
self.nextButton.setObjectName(_fromUtf8("nextButton"))
self.nextButton.clicked.connect(self.next_Button)
self.cancelButton = QtGui.QPushButton(Form)
self.cancelButton.setGeometry(QtCore.QRect(260, 250, 75, 23))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.cancelButton.setFont(font)
self.cancelButton.setObjectName(_fromUtf8("cancelButton"))
self.cancelButton.clicked.connect(self.cancel_Button)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "New User", None))
self.label.setText(_translate("Form", "NAME", None))
self.label_2.setText(_translate("Form", "REG. NO", None))
self.label_3.setText(_translate("Form", "PASSWORD", None))
self.label_4.setText(_translate("Form", " CREATE NEW USER", None))
self.nextButton.setText(_translate("Form", "SUBMIT", None))
self.cancelButton.setText(_translate("Form", "CANCEL", None))
@QtCore.pyqtSignature("on_cancelButton_clicked()")
def cancel_Button(self):
self.close()
@QtCore.pyqtSignature("on_nextButton_clicked()")
def next_Button(self):
username = self.nameGet.text()
password = self.passWordGet.text()
regno = self.regNoGet.text()
if not username:
QtGui.QMessageBox.warning(self, 'Warning', 'Username Missing')
elif not password:
QtGui.QMessageBox.warning(self, 'Warning!', 'Password Missing')
elif not regno:
QtGui.QMessageBox.warning(self, 'Warning!', 'RegNo Missing')
else:
t = self.dbu.GetTable()
print (t)
for col in t:
if username == col[1]:
QtGui.QMessageBox.warning(self, 'Dang it!', 'Username Taken. :(')
else:
self.dbu.AddEntryToTable (username, password, regno)
QtGui.QMessageBox.information(self, 'Awesome!!', 'User Added SUCCESSFULLY!')
self.close()
## def createProfileWindow(self):
## self.createprofile = Ui_StudentLogin()
## self.createprofile.show()
##
## def generate_report(self):
## data_line1 = self.nameGet.displayText()
## data_line2 = self.regNoGet.displayText()
## data_line3 = self.passWordGet.displayText()
## print data_line1
## print data_line2
## print data_line3
##
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Ui_Login()
ex.show()
sys.exit(app.exec_())
</code></pre>
| 1 | 2016-08-12T22:55:06Z | 38,927,704 | <p>The issue seems to be in your initialization of the <code>Ui_Form</code>. In this snippet</p>
<pre><code>@QtCore.pyqtSignature("on_signUpButton_clicked()")
def signUp_Button(self):
self.newuser = Ui_Form(self)
self.newuser.show()
</code></pre>
<p>it looks like you are passing <code>self</code>, in this case an instance of the <code>Ui_Login</code> class, as the dbu to the constructor of the `Ui_Form' class. Instead you should pass the dbu like so.</p>
<pre><code>@QtCore.pyqtSignature("on_signUpButton_clicked()")
def signUp_Button(self):
self.newuser = Ui_Form(self.dbu)
self.newuser.show()
</code></pre>
<p>You will find a lot of code that doesn't call out keyword arguments in constructors like this, but I find it to be bad practice in maintaining a readable codebase. So I would advise you to do something like this in future to help you avoid confusion.</p>
<pre><code>self.newuser = Ui_Form(dbu=self.dbu)
</code></pre>
| 0 | 2016-08-12T23:25:58Z | [
"python",
"pyqt"
] |
Polaroid Effect with Images in Python | 38,927,526 | <p>I'm trying to take an image and add the following effect from imagemagick <a href="http://www.imagemagick.org/Usage/transform/#polaroid" rel="nofollow">http://www.imagemagick.org/Usage/transform/#polaroid</a>. I've searched for Python code examples and have been unsuccessful. I don't need to use imagemagick(wand, pythonmagick, etc.) this was just the only example of this I could find. I don't want to use the command line example like listed. I would love to be able to include it in my photo booth python code.</p>
| 1 | 2016-08-12T23:01:06Z | 38,955,798 | <p>With <a href="/questions/tagged/wand" class="post-tag" title="show questions tagged 'wand'" rel="tag">wand</a>, you will need to implement the C-API methods <code>MagickPolaroidImage</code> & <code>MagickSetImageBorderColor</code></p>
<pre class="lang-py prettyprint-override"><code>import ctypes
from wand.api import library
from wand.color import Color
from wand.drawing import Drawing
from wand.image import Image
# Tell Python about C library
library.MagickPolaroidImage.argtypes = (ctypes.c_void_p, # MagickWand *
ctypes.c_void_p, # DrawingWand *
ctypes.c_double) # Double
library.MagickSetImageBorderColor.argtypes = (ctypes.c_void_p, # MagickWand *
ctypes.c_void_p) # PixelWand *
# Define FX method. See MagickPolaroidImage in wand/magick-image.c
def polaroid(wand, context, angle=0.0):
if not isinstance(wand, Image):
raise TypeError('wand must be instance of Image, not ' + repr(wand))
if not isinstance(context, Drawing):
raise TypeError('context must be instance of Drawing, not ' + repr(context))
library.MagickPolaroidImage(wand.wand,
context.resource,
angle)
# Example usage
with Image(filename='rose:') as image:
# Assigne border color
with Color('white') as white:
library.MagickSetImageBorderColor(image.wand, white.resource)
with Drawing() as annotation:
# ... Optional caption text here ...
polaroid(image, annotation)
image.save(filename='/tmp/out.png')
</code></pre>
<p><a href="http://i.stack.imgur.com/6RaJe.png" rel="nofollow"><img src="http://i.stack.imgur.com/6RaJe.png" alt="Polaroid effect with Python & wand"></a></p>
| 0 | 2016-08-15T13:15:06Z | [
"python",
"imagemagick",
"python-imaging-library",
"imagemagick-convert",
"pythonmagick"
] |
Convert pandas cut operation to a regular string | 38,927,585 | <p>I get the foll. output from a pandas cut operation:</p>
<pre><code>0 (0, 20]
1 (0, 20]
2 (0, 20]
3 (0, 20]
4 (0, 20]
5 (0, 20]
6 (0, 20]
7 (0, 20]
8 (0, 20]
9 (0, 20]
</code></pre>
<p>How can I convert the (0, 20] to 0 - 20?</p>
<p>I am doing this:</p>
<pre><code>.str.replace('(', '').str.replace(']', '').str.replace(',', ' -')
</code></pre>
<p>Any better approach?</p>
| 2 | 2016-08-12T23:10:22Z | 38,927,619 | <p>assuming the output was assigned to a variable <code>cut</code></p>
<pre><code>cut.astype(str)
</code></pre>
<p>To remove bracketing</p>
<pre><code>cut.astype(str).str.strip('()[]')
</code></pre>
| 2 | 2016-08-12T23:14:02Z | [
"python",
"pandas"
] |
Convert pandas cut operation to a regular string | 38,927,585 | <p>I get the foll. output from a pandas cut operation:</p>
<pre><code>0 (0, 20]
1 (0, 20]
2 (0, 20]
3 (0, 20]
4 (0, 20]
5 (0, 20]
6 (0, 20]
7 (0, 20]
8 (0, 20]
9 (0, 20]
</code></pre>
<p>How can I convert the (0, 20] to 0 - 20?</p>
<p>I am doing this:</p>
<pre><code>.str.replace('(', '').str.replace(']', '').str.replace(',', ' -')
</code></pre>
<p>Any better approach?</p>
| 2 | 2016-08-12T23:10:22Z | 38,927,645 | <p>Use the <code>labels</code> parameter of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>pd.cut</code></a>:</p>
<pre><code>pd.cut(df['some_col'], bins=[0,20,40,60], labels=['0-20', '20-40', '40-60'])
</code></pre>
<p>I don't know what your exact <code>pd.cut</code> command looks like, but the code above should give you a good idea of what to do.</p>
<p>Example usage:</p>
<pre><code>df = pd.DataFrame({'some_col': range(5, 56, 5)})
df['cut'] = pd.cut(df['some_col'], bins=[0,20,40,60], labels=['0-20','20-40','40-60'])
</code></pre>
<p>Example output:</p>
<pre><code> some_col cut
0 5 0-20
1 10 0-20
2 15 0-20
3 20 0-20
4 25 20-40
5 30 20-40
6 35 20-40
7 40 20-40
8 45 40-60
9 50 40-60
10 55 40-60
</code></pre>
| 4 | 2016-08-12T23:16:59Z | [
"python",
"pandas"
] |
How do I make a force-directed graph in python? | 38,927,682 | <p>I want a graph that shows a few nodes, directional arrows between nodes representing a relationship, with thickness relative to the strength of their connection.</p>
<p>In R this is very simple</p>
<pre><code>library("qgraph")
test_edges <- data.frame(
from = c('a', 'a', 'a', 'b', 'b'),
to = c('a', 'b', 'c', 'a', 'c'),
thickness = c(1,5,2,2,1))
qgraph(test_edges, esize=10, gray=TRUE)
</code></pre>
<p>Which produces:
<a href="http://i.stack.imgur.com/4eTLp.png" rel="nofollow"><img src="http://i.stack.imgur.com/4eTLp.png" alt="force directed graph via R"></a></p>
<p>But in Python I haven't been able to find a clear example. NetworkX and igraph seem to hint that it's possible, but I haven't been able to figure it out.</p>
| 1 | 2016-08-12T23:23:38Z | 38,930,780 | <p>I first tried doing this with NetworkX's standard drawing functions, which use matplotlib, but I was not very successful.</p>
<p>However, NetworkX also <a href="https://networkx.github.io/documentation/development/reference/drawing.html#module-networkx.drawing.nx_agraph" rel="nofollow">supports drawing to the <code>dot</code> format</a>, which <a href="https://stackoverflow.com/a/2363990/539465">supports edge weight, as the <code>penwidth</code> attribute</a>.</p>
<p>So here is a solution:</p>
<pre><code>import networkx as nx
G = nx.DiGraph()
edges = [
('a', 'a', 1),
('a', 'b', 5),
('a', 'c', 2),
('b', 'a', 2),
('b', 'c', 1),
]
for (u, v, w) in edges:
G.add_edge(u, v, penwidth=w)
nx.nx_pydot.write_dot(G, '/tmp/graph.dot')
</code></pre>
<p>Then, to show the graph, run in a terminal:</p>
<pre><code>dot -Tpng /tmp/graph.dot > /tmp/graph.png
xdg-open /tmp/graph.png
</code></pre>
<p>(or the equivalent on your OS)</p>
<p>Which shows:</p>
<p><a href="https://i.stack.imgur.com/xvPU1.png" rel="nofollow"><img src="https://i.stack.imgur.com/xvPU1.png" alt="output of the graph described by OP"></a></p>
| 2 | 2016-08-13T08:25:01Z | [
"python",
"data-visualization",
"igraph",
"networkx",
"r-qgraph"
] |
How can I identify the correct td tag using bs4 in python when HTML code is inconsistent | 38,927,775 | <p>I'm using BeautifulSoup4 in Python to parse some HTML code. I've managed to drill down to the correct table and identify the td tags, but the problem I'm facing is that the style attribute in the tags is inconsistently applied and it is making the task of getting the correct td tag a real challenge.</p>
<p>The data I'm trying to pull is a date field, but at any one time there will be multiple td tags that are hidden using CSS (what is visible depends on the option value selected elsewhere in the HTML code). </p>
<p>Actual examples:</p>
<pre><code><td style="display: none;">01/03/2016</td>
<td style="display: table-cell;">27/10/2015</td> <-- this is the tag I want
</code></pre>
<p>and</p>
<pre><code><td style="display:none">23/02/2016</td>
<td style="">09/05/2011</td> <-- this is the tag I want
<td style="display: none;">29/03/2011</td>
<td style="display:none">19/10/2010</td>
</code></pre>
<p>and</p>
<pre><code><td>27/10/2015</td> <-- this is the tag I want
<td style="display: none">01/03/2016</td>
<td style="display: none">22/03/2016</td>
</code></pre>
<p>and</p>
<pre><code><td style="display:none">11/04/2015</td>
<td style="display: table-cell;">02/02/2016</td> <-- this is the tag I want
<td style="display: none">18/10/2013</td>
</code></pre>
<p>How would I exclude/remove the incorrect items (which have styles of <code>display:none</code> and <code>display: none</code>) to leave me with the one that I do actually want?</p>
| 1 | 2016-08-12T23:37:05Z | 38,933,177 | <p>Filter the tds using a list comp, keeping only if the td does not have a style attribute in the set <code>{"display:none", "display: none;","display: none;","display: none"}</code>:</p>
<pre><code>In [8]: h1 = """"<td style="display: none;">01/03/2016</td>
...: <td style="display: table-cell;">27/10/2015</td>"""
In [9]: h2 = """"<td style="display:none">23/02/2016</td>
...: <td style="">09/05/2011</td> <-- this is the tag I want
...: <td style="display: none;">29/03/2011</td>
...: <td style="display:none">19/10/2010</td>"""
In [10]: h3 = """"<td>27/10/2015</td> <-- this is the tag I want
....: <td style="display: none">01/03/2016</td>
....: <td style="display: none">22/03/2016</td>"""
In [11]: h4 = """<td style="display:none">11/04/2015</td>
....: <td style="display: table-cell;">02/02/2016</td> <-- this is the tag I want
....: <td style="display: none">18/10/2013</td>"""
In [12]: ignore = {"display:none", "display: none;", "display: none;", "display: none"}
In [13]: for html in [h1, h2, h3, h4]:
....: soup = BeautifulSoup(html, "html.parser")
....: print([td for td in soup.find_all("td") if not td.get("style") in ignore])
....:
[<td style="display: table-cell;">27/10/2015</td>]
[<td style="">09/05/2011</td>]
[<td>27/10/2015</td>]
[<td style="display: table-cell;">02/02/2016</td>]
</code></pre>
| 1 | 2016-08-13T13:23:43Z | [
"python",
"html",
"beautifulsoup",
"bs4"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num.append(tmp)
suma+=i
</code></pre>
<p><strong>using dictionaries</strong>:</p>
<pre><code>n=100000
num={}
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num[tmp]=i
suma+=i
</code></pre>
<p>I am only concerned about performance. Why does the second example using dictionaries run incredibly fast, faster than the first example with lists. the example with dictionaries runs almost thirty-fold faster!</p>
<p>I tested these 2 code using n=1000000, and the first code run in 1032 seconds and the second one run in just 3.3 second,,, amazin'!</p>
| 4 | 2016-08-12T23:39:36Z | 38,927,878 | <p>In a list, the code <code>if tmp not in num:</code> is O(n)<strike>, while it is O(lgn) in dict</strike>.</p>
<p><strong>Edit</strong>: The dict is based on hashing, so it is much quicker than liner list search.
Thanks @user2357112 for point this.</p>
| 0 | 2016-08-12T23:54:52Z | [
"python",
"performance",
"list",
"dictionary"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num.append(tmp)
suma+=i
</code></pre>
<p><strong>using dictionaries</strong>:</p>
<pre><code>n=100000
num={}
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num[tmp]=i
suma+=i
</code></pre>
<p>I am only concerned about performance. Why does the second example using dictionaries run incredibly fast, faster than the first example with lists. the example with dictionaries runs almost thirty-fold faster!</p>
<p>I tested these 2 code using n=1000000, and the first code run in 1032 seconds and the second one run in just 3.3 second,,, amazin'!</p>
| 4 | 2016-08-12T23:39:36Z | 38,927,933 | <p>I am almost positive that the "magic sauce" using a dictionary lies in the fact that the dictionary is comprised of key->value pairs.</p>
<p>in a list, youre dealing with arrays, which means the for loop has to start at index 0 inside of your list in order to loop through every record.</p>
<p>the dictionary just has to find the key->value pair in question on the first 'go-round' and return it, hence the speed...</p>
<p>basically, testing for membership in a set of key->value pairs is a lot quicker than searching an entire list for a value. the larger your list gets the slower it will be... but this isnt always the case, there are scenarios where a list will be faster... but i believe this may be the answer youre looking for</p>
| 0 | 2016-08-13T00:04:37Z | [
"python",
"performance",
"list",
"dictionary"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num.append(tmp)
suma+=i
</code></pre>
<p><strong>using dictionaries</strong>:</p>
<pre><code>n=100000
num={}
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num[tmp]=i
suma+=i
</code></pre>
<p>I am only concerned about performance. Why does the second example using dictionaries run incredibly fast, faster than the first example with lists. the example with dictionaries runs almost thirty-fold faster!</p>
<p>I tested these 2 code using n=1000000, and the first code run in 1032 seconds and the second one run in just 3.3 second,,, amazin'!</p>
| 4 | 2016-08-12T23:39:36Z | 38,927,968 | <p>In Python, the average time complexity of a dictionary key lookup is O(1), since they are implemented as hash tables. The time complexity of lookup in a list is O(n) on average. In your code, this makes a difference in the line <code>if tmp not in num:</code>, since in the list case, Python needs to search through the whole list to detect membership, whereas in the dict case it does not except for the absolute worst case.</p>
<p>For more details, check out <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">TimeComplexity</a>.</p>
| 4 | 2016-08-13T00:10:35Z | [
"python",
"performance",
"list",
"dictionary"
] |
Python dictionary vs list, which is faster? | 38,927,794 | <p>I was coding a Euler problem, and I ran into question that sparked my curiosity. I have two snippets of code. One is with lists the other uses dictionaries. </p>
<p><strong>using lists</strong>:</p>
<pre><code>n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num.append(tmp)
suma+=i
</code></pre>
<p><strong>using dictionaries</strong>:</p>
<pre><code>n=100000
num={}
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num[tmp]=i
suma+=i
</code></pre>
<p>I am only concerned about performance. Why does the second example using dictionaries run incredibly fast, faster than the first example with lists. the example with dictionaries runs almost thirty-fold faster!</p>
<p>I tested these 2 code using n=1000000, and the first code run in 1032 seconds and the second one run in just 3.3 second,,, amazin'!</p>
| 4 | 2016-08-12T23:39:36Z | 38,929,814 | <p>If it's about speed, you should not create any lists:</p>
<pre><code>n = 100000
factors = ((frozenset(factors(i)), i) for i in range(2, n+1))
num = {k:v for k,v in factors if len(k)==2}
suma = sum(num.values())
</code></pre>
| 1 | 2016-08-13T06:14:26Z | [
"python",
"performance",
"list",
"dictionary"
] |
Parsing a Pandas dataframe with an unknown number of columns for use in statsmodels.api | 38,927,844 | <p>I would like to create a generic script to perform linear regressions on multiple data sets. Each data set will have the same y-variable called "SM" and an unknown number of x-variables. I have been able to do this successfully if I know exactly which data will be used for the regression. For example:</p>
<pre><code>import pandas
import statsmodels.api as sm
import statsmodels.formula.api as smf
from patsy import dmatrices
data = pandas.read_excel('test.xlsx')
</code></pre>
<p>Then, print data gives:</p>
<pre><code>print data
SM Glass mag
SiO2 73.500 77.27 0.00
TiO2 0.233 0.15 7.37
Al2O3 11.230 11.49 0.00
FeO* 4.240 2.85 92.46
MnO 0.082 0.06 0.00
MgO 0.040 0.00 0.00
CaO 0.410 0.22 0.00
Na2O 5.630 4.58 0.00
K2O 4.620 3.38 0.00
</code></pre>
<p>Then I prepare the dataframe and do the linear regression:</p>
<pre><code>y, X = dmatrices('SM ~ Glass + mag', data=data, return_type='dataframe')
mod = sm.OLS(y, X)
res = mod.fit()
print res.summary()
</code></pre>
<p>This all works great. BUT, I'd like to be able to import an excel file with an unknown number of columns so I can do:</p>
<pre><code>y, X = dmatrices('SM ~ X1 + X2 + X3 + ... Xn', data=data, return_type='dataframe')
</code></pre>
<p>I can parse the data frame and pull out individual columns, but I don't know how to them put them into the formula needed to do the linear regression. Any advice is appreciated!</p>
| 1 | 2016-08-12T23:47:36Z | 38,927,871 | <p>See if this works:</p>
<pre><code>df = pd.DataFrame(np.arange(20).reshape(2, 10), columns=list('abcdefghij'))
formula = '{} ~ {}'.format(df.columns[0], ' + '.join(df.columns[1:]))
formula
'a ~ b + c + d + e + f + g + h + i + j'
</code></pre>
| 0 | 2016-08-12T23:53:31Z | [
"python",
"pandas",
"linear-regression",
"statsmodels",
"patsy"
] |
How to call the function from user input? | 38,927,857 | <p>I'm trying to call <code>Floyd_Warshall(G)</code> from <code>user_command</code> however I get this <code>error</code>:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 24, in <module>
Floyd_Warshall()
NameError: name 'Floyd_Warshall' is not defined
</code></pre>
<p>How to call it to get rid of this error?</p>
<pre><code>import sys
import re
print("File containing graph: ")
while True:
user_input = input()
if user_input == "input1.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
print("Enter command: ")
user_command = input()
if user_command == "help":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_command == "floyd":
Floyd_Warshall()
else:
print ("dijkstra")
elif user_input == "input2.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_input == "input3.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_input == "exit":
sys.exit(0)
else:
print("Wrong choice")
def Floyd_Warshall(G):
............
............
if __name__ == '__main__':
Floyd_Warshall()
</code></pre>
| 0 | 2016-08-12T23:50:51Z | 38,929,416 | <p>function should be defined before calling it. So place the function before while loop</p>
<pre><code>import sys
import re
# also this function needs one input mandatorily
def Floyd_Warshall(G):
............
............
print("File containing graph: ")
while True:
user_input = input()
if user_input == "input1.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
print("Enter command: ")
user_command = input()
if user_command == "help":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_command == "floyd":
Floyd_Warshall()
else:
print ("dijkstra")
elif user_input == "input2.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_input == "input3.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_input == "exit":
sys.exit(0)
else:
print("Wrong choice")
if __name__ == '__main__':
Floyd_Warshall()
</code></pre>
| 0 | 2016-08-13T05:08:40Z | [
"python",
"function",
"python-3.x",
"input"
] |
How to call the function from user input? | 38,927,857 | <p>I'm trying to call <code>Floyd_Warshall(G)</code> from <code>user_command</code> however I get this <code>error</code>:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 24, in <module>
Floyd_Warshall()
NameError: name 'Floyd_Warshall' is not defined
</code></pre>
<p>How to call it to get rid of this error?</p>
<pre><code>import sys
import re
print("File containing graph: ")
while True:
user_input = input()
if user_input == "input1.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
print("Enter command: ")
user_command = input()
if user_command == "help":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_command == "floyd":
Floyd_Warshall()
else:
print ("dijkstra")
elif user_input == "input2.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_input == "input3.txt":
print("Possible Commands are:")
print("dijkstra x - Runs Dijkstra starting at node X. X must be an integer")
print("floyd - Runs Floyd's algorithm")
print("help - prints this menu")
print("exit or ctrl-D - Exits the program")
elif user_input == "exit":
sys.exit(0)
else:
print("Wrong choice")
def Floyd_Warshall(G):
............
............
if __name__ == '__main__':
Floyd_Warshall()
</code></pre>
| 0 | 2016-08-12T23:50:51Z | 38,929,535 | <p>Its would not run anyway: </p>
<pre><code>Floyd_Warshall()
</code></pre>
<p>and </p>
<pre><code>def Floyd_Warshall(G):
</code></pre>
<p>are not compatible. The function needs a variable input, which is missing when you call it with <code>Floyd_Warshall()</code></p>
| 0 | 2016-08-13T05:29:33Z | [
"python",
"function",
"python-3.x",
"input"
] |
python pandas reindexing removes data at 0.0 | 38,927,875 | <p>I have three columns of data: two position values and one data value. I would like to pivot this data so that the elements of one column become the new columns and the elements of another one of the original columns become the indices. These data will be plotted using <code>pcolormesh</code>. <code>pcolormesh</code> expects the data to be structured such that it doesn't have to guess what to do. That is if there is a column of nans, <code>pcolormesh</code> will not fill in this column correctly. So I have written some code to correctly shape the data so that it can be fed to <code>pcolormesh</code>.</p>
<p>The problem I have is that the code seems to remove data around <code>x = 0.0</code>. I think this is occuring on the line where the dataframe is being reindexed to include the "missing" rows.</p>
<p>I've added a plot (and hence some extra code) to give a visual aide to the problem statement. The left plot shows the original data, the right plot shows the result after the data has been reshaped for <code>pcolormesh</code>.</p>
<p>The code example I have provided should run in an ipython notebook by only copying and pasting.</p>
<p>Any suggestions are welcome. Perhaps this solution is super complicated? It sure feels that way.</p>
<p><a href="http://i.stack.imgur.com/QBxUJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/QBxUJ.png" alt="enter image description here"></a></p>
<pre><code>%matplotlib inline
import decimal
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
test_df = pd.DataFrame()
test_df['x'] = [-2, -1.5, -0.9, -0.7, -0.5, 0.0, 0.5, 1.1]
test_df['y'] = [1,2,4,5,6,7,5,4]
test_df['v'] = np.random.randn(8)
def get_precision(number):
"""
gives the precision, or decimal place, of the number
http://stackoverflow.com/questions/6189956/easy-way-of-finding-decimal-places
"""
return int(abs(decimal.Decimal(str(number)).as_tuple().exponent))
def min_max(column):
column_min = np.floor(column.min())
column_max = np.ceil(column.max())
return column_min, column_max
def construct_df_for_pcolormesh(df, col, ix, values, columns_increment, index_increment):
columns_increment = 1.0/columns_increment
index_increment = 1.0/index_increment
columns_precision = get_precision(columns_increment)
index_precision = get_precision(index_increment)
columns_min, columns_max = min_max(df[col])
index_min, index_max = min_max(df[ix])
columns = np.linspace(columns_min, columns_max, (columns_max - columns_min)*columns_increment + 1)
index = np.linspace(index_min, index_max, (index_max - index_min)*index_increment + 1)
new_index = [(round(c, columns_precision), round(i, index_precision)) for c in columns for i in index]
df_for_pcolormesh = df.set_index([col, ix]).reindex(new_index).reset_index()
df_for_pcolormesh = df_for_pcolormesh.pivot(index=ix, columns=col, values=values)
return df_for_pcolormesh
fig, (ax,ax1)= plt.subplots(1,2, sharey=True, sharex=True)
test_df.plot(kind='scatter', x='x', y='y', s=100, grid=True, ax=ax)
ax.set_ylim(0,8)
ax.set_xlim(-2.5, 1.5)
ax.set_title('Plot with all the data')
data_df = construct_df_for_pcolormesh(test_df, 'x', 'y', 'v', 0.1, 0.1)
depths = data_df.index
xx = data_df.columns
d, x = np.meshgrid(depths, xx)
data = np.ma.masked_invalid(data_df.values)
ax1.pcolormesh(x, d, data.transpose(), cmap='viridis')
ax1.grid(True)
ax1.set_ylim(0,8)
ax1.set_xlim(-2.5, 1.5)
ax1.set_title('Plot with missing\ndatapoint at x=0.0')
</code></pre>
| 2 | 2016-08-12T23:54:06Z | 38,930,393 | <p>I am not sure about the real reason. However, I changed your <code>min_max</code> function to:</p>
<pre><code>def min_max(column):
column_min = np.floor(column.min())
column_max = np.ceil(column.max()) + 1
return column_min, column_max
</code></pre>
<p>And then it worked:</p>
<p><a href="http://i.stack.imgur.com/MG5RV.png" rel="nofollow"><img src="http://i.stack.imgur.com/MG5RV.png" alt="enter image description here"></a></p>
| 2 | 2016-08-13T07:34:49Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Have 2 flask pages that share a database, need to merge their models | 38,927,891 | <p>Need some guidance with this please. I have two pages or apps made with flask(+sqlalchemy) - one that acts as the front page and the other one that works as some kind of admin or extranet for the first one.</p>
<p>The apps use their own views and models but they share the same database and this is starting to mess things up when I try to make changes to the schema. </p>
<p>The way the project is setup is the next:
<a href="http://i.stack.imgur.com/j8IJy.png" rel="nofollow">file structure image</a></p>
<pre><code>/www
|- /flaskapp
| |- /flaskapp
| |- models.py
| |- views.py
| |- form.py
| |- init.py
| |- oauth.py
| |- /static
| |- /templates
| |- /flask
|
|- /extranet
|-/extranet
|- models.py
|- views.py
|- form.py
|- init.py
|- oauth.py
|- /static
|- /templates
</code></pre>
<p>So I need to merge the two pages' models into one model file so I can have more control over my database schema, migrations, etc. How can I do this in a proper way?</p>
| 0 | 2016-08-12T23:56:25Z | 38,929,064 | <p>It is unclear what problem you are trying to solve. SQLAlchemy has a <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/api.html" rel="nofollow">declarative API</a> that allows you to sub-class some base (in Flask-SQLAlchemy, conventionally, <code>db.Model</code>); it then automatically builds <a href="http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html" rel="nofollow">mappings</a> between those sub-classes and tables in your database.</p>
<p>As long as <code>db</code> refers to the same <code>SQLAlchemy</code> object in both <code>models.py</code> files (e.g., has been imported from the same scope), mappings will be formed for the whole schema. If you need to run some sort of migration tool using a <code>db</code> object with the full set of mappings, you could write a module:</p>
<pre><code># combine_db.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask()
db = SQLAlchemy(app)
import flaskapp.models # imports `db` from combine_db
import extranet.models # imports `db` from combine_db
</code></pre>
<p>Then your migration tool can import <code>db</code> from <code>combine_db</code>!</p>
<p>If you don't like the circular-import approach, you can try wrapping your model sub-class definitions in a function, which you can import from <code>flaskapp</code> and <code>extranet</code> at the top of the file, and later call with <code>db</code> as an argument. (I haven't tested this.)</p>
| 0 | 2016-08-13T04:04:55Z | [
"python",
"flask",
"flask-sqlalchemy"
] |
Pygame move a object to mouse | 38,927,892 | <p>I wanted to move a sprite (bullet) slowly to the coordinates of the mouse by calculating the x and y of the image with: </p>
<pre><code>angle = math.atan2(dX,dY) * 180/math.pi
x = speed * sin(angle)
y = speed * cos(angle)
</code></pre>
<p>The problem is that even though a sprite points to the mouse (in this game, the gun) with the same angle (using pygame.transform.rotate) the bullet still moves to incorrect coordinates.</p>
<p><strong>Current Code Example:</strong></p>
<pre><code>dX = MouseX - StartpointX
dY = Mouse_Y - StartPointY
Angle = ( math.atan2(dX,dY) * 180/math.pi ) + 180
Bullet_X =Bullet_X + Speed * math.sin(Angle)
Bullet_Y = Bullet_Y + Speed * math.cos(Angle)
</code></pre>
<p>How do I solve this?</p>
<p><a href="http://i.stack.imgur.com/x4JLL.png" rel="nofollow">An example to show it clearly</a></p>
| 0 | 2016-08-12T23:56:31Z | 38,954,726 | <h2>There are three things wrong with your calculations.</h2>
<ol>
<li><code>math.atan2</code> takes the arguments in the order y and x, not x and y. This isn't a huge deal since you can compensate for it.</li>
<li><code>math.cos</code> and <code>math.sin</code> takes <strong>radians</strong> as arguments. You have converted the angle to <em>degrees</em>.</li>
<li><em>Cosine</em> represent the x-value while <em>sine</em> represent the y-value.</li>
</ol>
<p>So the calculations should be something like this:</p>
<pre><code>dx = mouse_x - x
dy = mouse_y - y
angle = math.atan2(dy, dx)
bullet_x += speed * math.cos(angle)
bullet_y += speed * math.sin(angle)
</code></pre>
<h2>Short example using the solution</h2>
<pre><code>import pygame
import math
pygame.init()
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
x, y, dx, dy = 360, 240, 0, 0
player = pygame.Surface((32, 32))
player.fill((255, 0, 255))
bullet_x, bullet_y = 360, 240
speed = 10
bullet = pygame.Surface((16, 16))
bullet.fill((0, 255, 255))
def update(mouse_x, mouse_y):
global x, y, dx, dy, bullet_x, bullet_y
dx = mouse_x - x
dy = mouse_y - y
angle = math.atan2(dy, dx)
bullet_x += speed * math.cos(angle)
bullet_y += speed * math.sin(angle)
run_update = False
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
run_update = True
mouse_x, moues_y = pygame.mouse.get_pos()
if run_update:
update(mouse_x, moues_y)
if 0 > bullet_x or bullet_x > 800 or 0 > bullet_y or bullet_y > 800:
bullet_x, bullet_y = 360, 240
run_update = False
screen.fill((0, 0, 0))
screen.blit(player, (x, y))
screen.blit(bullet, (bullet_x, bullet_y))
pygame.display.update()
</code></pre>
| 0 | 2016-08-15T12:02:34Z | [
"python",
"pygame",
"mouse"
] |
request.headers.get('Authorization') is empty in Flask production | 38,927,945 | <p>I have the following flask method that simple returns back the value of the Authorization header:</p>
<pre><code>@app.route('/test', methods=['POST'])
def test():
return jsonify({"data" : request.headers.get('Authorization') })
</code></pre>
<p>When I submit the following curl request to my API which has been deployed to a DO instance, the header comes back as null:</p>
<p>curl --data '' -H "Authorization: test" api.mysite.com/test</p>
<pre><code>{
"data": null
}
</code></pre>
<p>Yet when I submit the same request on my instance running locally it returns the header contents</p>
<pre><code>{
"data": "test"
}
</code></pre>
<p>Any ideas?</p>
| 0 | 2016-08-13T00:06:29Z | 38,928,853 | <p>Have you tried using a proper <code>Authorization</code> header? Possibly the header is being filtered out by a web application firewall or proxy because it doesn't specify a scheme. For example:</p>
<pre>
curl --data '' -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" api.mysite.com/test
</pre>
<p>This sends a basic authorization header with the base64 encoded credentials <code>username:password</code>.</p>
| 1 | 2016-08-13T03:17:11Z | [
"python",
"http",
"flask",
"authorization"
] |
Python subprocess call throws errors when using find | 38,927,956 | <p>I am making a script in <code>python3</code> using <code>call</code> from the <code>subprocess</code> library. The problem that I am having is that this command <code>find . -mtime +3 | xargs rm -rf</code> will work perfectly fine when put into the terminal but when I do this:</p>
<pre class="lang-py prettyprint-override"><code>from subprocess import call
call(["find", ".", "-mtime", "+3", "|", "xargs", "rm", "-rf"])
</code></pre>
<p>I end up getting an error that looks something like this:</p>
<pre class="lang-sh prettyprint-override"><code>find: paths must precede expression: |
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]
1
</code></pre>
<p>What I am doing wrong? Please help :-)</p>
| -1 | 2016-08-13T00:07:33Z | 38,928,082 | <p><code>|</code> isn't a command argument; it is shell syntax for joining two commands together.</p>
<p>The simplest way to use a pipe is to pass a single string to <code>subprocess</code> and let a shell parse it:</p>
<pre><code>from subprocess import call
call("find . -mtime +3 | xargs rm -rf", shell=True)
</code></pre>
<p>In this case, it works nicely because the command line is very simple; nothing needs quoting.</p>
<p>You can set up a pipe in Python, but it's not as succinct as a single <code>|</code> character.</p>
<pre><code>from subprocess import Popen, PIPE
p1 = Popen(["find", ".", "-mtime", "+3"], stdout=PIPE)
p2 = Popen(["xargs", "rm", "-rf"], stdin=p1.stdout)
p1.stdout.close()
p2.wait()
</code></pre>
<p>See the Python documentation for <a href="https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline" rel="nofollow">further reference</a>.</p>
| 3 | 2016-08-13T00:33:30Z | [
"python",
"bash",
"python-3.x",
"find",
"subprocess"
] |
Default export in Python 3 | 38,927,979 | <p>In a project I'm working on, I'm separating a lot of bigger files into smaller pieces so they're easier to work with. One specific example is creating class based views from function based views in Django:</p>
<pre><code># app/views/LoginView.py
class LoginView(View):
...
# urls.py
from app.views import LoginView
urlpatterns = [
# Here, I have to use LoginView twice
url(r'^login', LoginView.LoginView.as_view())
]
</code></pre>
<p>Above, I have to use <code>LoginView</code> twice when I want to call it, since importing <code>LoginView</code> imports the module, and not the method from the module, even though they are the same name. Ideally, I'd like to avoid having to call <code>LoginView.LoginView</code> each time.</p>
<p>In Javascript, I can just say <code>export default function my_function() { ... }</code> without naming it, and when it's imported it's default, e.g <code>import my_function from './some_module.js';</code></p>
<p>Is there any way to do something like this in Python 3? I do not want to do <code>from app.views.LoginView import LoginView</code> because, especially in a big Django project and in a file like <code>urls.py</code>, it isn't feasible to have each import on a separate line.</p>
| 3 | 2016-08-13T00:12:16Z | 38,928,273 | <p>You can import <code>LoginView</code> as a name under <code>app.views</code> using the <code>__init__.py</code> of <code>app.views</code>.</p>
<p>In <code>app/views/__init__.py</code>:</p>
<pre><code>from LoginView import LoginView
</code></pre>
<p>In <code>urls.py</code></p>
<pre><code>import app.views
urlpatterns = [
url(r'^login', app.views.LoginView.as_view())
]
</code></pre>
| 4 | 2016-08-13T01:12:21Z | [
"python",
"django",
"python-3.5"
] |
Django with Crispy-forms VariableDoesNotExist | 38,927,992 | <p>I have been trying to load a form into a modal for about a week now and I just can't figure out what it is I'm doing wrong. It is a simple form for someone to send an email to me, and I started out trying to modularize the form and am now just trying to load it direcly into base.html.</p>
<p>My model:</p>
<pre><code>from django.db import models
# Create your models here.
class EmailMe(models.Model):
subject = models.CharField(max_length=63)
body = models.TextField(max_length=2047)
email = models.EmailField()
def __str__(self):#shows object title when called from command line
return self.name`
</code></pre>
<p>my form:</p>
<pre><code>from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout
from emailme.models import EmailMe
class EmailMeForm(forms.ModelForm):
subject = forms.CharField(max_length=63)
body = forms.CharField(max_length=2047)
email = forms.EmailField()
class Meta:
model = EmailMe
fields = '__all__'
def __str__(self):#shows object title when called from command line
return self.name
def __init__(self, *args, **kwargs):
super(EmailMeForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'myModal'
self.helper.form_class = 'form-horizontal'
self.helper.form_action = 'emailme'
self.helper.form_method = 'POST'
self.helper.layout = Layout(
Fields(
'subject',
'body',
'email',
),
FormActions(
Submit('submit', 'submit')
)
)
</code></pre>
<p>My view:</p>
<pre><code>from mysite.forms import EmailMeForm
def home(request):
return render_to_response('base.html')
def emailme(request):
if request.POST:
form = EmailMeForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('home/')#reverse_lazy('home'))
else:
form = EmailMeForm()
ctx = {}
ctx.update(csrf(request))
args['form'] = form
return render_to_response('emailme_form.html',
{'form': form},
context_instance=ctx)
</code></pre>
<p>urls:</p>
<pre><code>"""mysite URL Configuration
"""
from django.conf.urls import url, include
from django.contrib import admin
from mysite import views as mysite_views
from emailme import views as emailme_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^emailme/', emailme_views.emailme, name='emailme'),
url(r'^home/', mysite_views.home, name='home'),
]
</code></pre>
<p>base.html:</p>
<pre><code>{% load crispy_forms_tags %}
<div class="modal-content">
{% csrf_token %}
{% crispy form form.helper %}
</div>
</code></pre>
<p>I'm using Django 1.9, crispy-forms, and bootstrap. Here is the error:</p>
<pre><code>Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/home/
Django Version: 1.9.8
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'emailme',
'crispy_forms',
'bootstrap3']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/pi/Django-bootstrap/bin/mysite/templates/base.html, error at line 77
Failed lookup for key [%s] in %r 67 :
68 :
69 :
70 : <div class="container">
71 : <!-- Modal -->
72 : <div class="modal fade" id="myModal" role="dialog">
73 : <div class="modal-dialog">
74 : <!-- Modal content-->
75 : <div class="modal-content">
76 : {% csrf_token %}
77 : {% crispy form form.helper %}
78 : </div>
79 : </div>
80 : </div>
81 : </div>
82 :
83 :
84 :
85 : <div class="container">
86 : <!-- Example row of columns -->
87 : <div class="row">
Traceback:
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
883. current = current[bit]
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/context.py" in __getitem__
77. raise KeyError(key)
During handling of the above exception ('form'), another exception occurred:
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
889. if isinstance(current, BaseContext) and getattr(type(current), bit):
During handling of the above exception (type object 'Context' has no attribute 'form'), another exception occurred:
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
898. current = current[int(bit)]
During handling of the above exception (invalid literal for int() with base 10: 'form'), another exception occurred:
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Django-bootstrap/bin/mysite/mysite/views.py" in home
13. return render_to_response('base.html')
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/shortcuts.py" in render_to_response
39. content = loader.render_to_string(template_name, context, using=using)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
97. return template.render(context, request)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in render
206. return self._render(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _render
197. return self.nodelist.render(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in render
992. bit = node.render_annotated(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in render_annotated
959. return self.render(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/crispy_forms/templatetags/crispy_forms_tags.py" in render
214. c = self.get_render(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/crispy_forms/templatetags/crispy_forms_tags.py" in get_render
107. actual_form = form.resolve(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in resolve
850. value = self._resolve_lookup(context)
File "/home/pi/Django-bootstrap/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
905. (bit, current)) # missing attribute
Exception Type: VariableDoesNotExist at /home/
Exception Value: Failed lookup for key [form] in "[{'False': False, 'None': None, 'True': True}]"
</code></pre>
| 0 | 2016-08-13T00:13:38Z | 38,929,385 | <p>The problem is that you are trying to use your <code>form</code> in your <code>base.html</code> (for all views). But the form is only added to the context in your <code>emailme</code> view. The home page view (<code>home</code>) does not provide any <code>form</code>, hence the error when you try to load the home page.</p>
<p>You either need to add the form to the home page view (and any other views that use <code>base.html</code>):</p>
<pre><code>def home(request):
return render_to_response('base.html', {'form': EmailMeForm()})
</code></pre>
<p>or use a <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#writing-your-own-context-processors" rel="nofollow">context processor</a> to insert the form into to the template context globally.</p>
| 0 | 2016-08-13T05:01:19Z | [
"python",
"django",
"twitter-bootstrap",
"django-models",
"django-crispy-forms"
] |
Avoid creating app with flask-cli | 38,927,996 | <p>I'm using a custom manage.py script for my flask app, which is created with a factory pattern.</p>
<p>This script needs to both be able to run the server and run my tests. I use an external tool to run my tests, so I do not need to create an app to run the tests. How can I only create the app when running certain commands?</p>
<p>My script currently looks like:</p>
<pre><code>import subprocess
import sys
from flask import current_app
from flask.cli import FlaskGroup
import click
from quizApp import create_app
@click.pass_context
def get_app(ctx, _):
"""Create an app with the correct config.
"""
return create_app(ctx.find_root().params["config"])
@click.option("-c", "--config", default="development",
help="Name of config to use for the app")
@click.group(cls=FlaskGroup, create_app=get_app)
def cli(**_):
"""Define the top level group.
"""
pass
@cli.command("test")
def test():
"""Set the app config to testing and run pytest, passing along command
line args.
"""
# This looks stupid, but see
# https://github.com/pytest-dev/pytest/issues/1357
sys.exit(subprocess.call(['py.test',
'--cov=quizApp',
'--flake8',
'--pylint',
'./']))
if __name__ == '__main__':
cli()
</code></pre>
<p>I tried creating a second group, but it seemed that only one group can "run" at a time, so I'm not exactly sure how to solve this.</p>
| 0 | 2016-08-13T00:14:27Z | 39,786,386 | <p>you need to add:</p>
<pre><code>cli.add_command(test)
</code></pre>
<p>before:</p>
<pre><code>if __name__ == '__main__':
cli()
</code></pre>
<p>And I am not sure if it is the only left thing you need to do. I am also study this and feel confused. But if you want to add a command in the FlaskGroup, you must do that. I feel confused when I want to use Factory and CLI in the flask project. Maybe at last you need to try Flask-Script extension, at least it works.</p>
| 0 | 2016-09-30T07:52:50Z | [
"python",
"flask",
"python-click"
] |
Asking user to input a file from their computer | 38,928,015 | <p>New python 2.7 user. I just started learning about dictionaries and asking the user for input so I can make a little code to practice manipulating dictionaries such as simple math computations. </p>
<p>I am able to ask a user to input something manually such as :</p>
<pre><code> fav_numbs = (raw_input("What is your favorite car and color?: "))
</code></pre>
<p>I am wanting to get the user's information in a dictionary. Instead of asking the user to manually type in their favorite cars and colors of that car, I want them to import their own file from their computer. So far, I have came up with:</p>
<pre><code> fav_cars = raw_input('Enter file name that contains your favorite cars and color. The file must have the first column as favorite cars and a second column includes your favorite color of that particular car: ')
myfile = open(fav_cars, 'r')
</code></pre>
<p>I am assuming the user can just put in the file name the same way as one can input a file into their python code? I know that if the python file and the file being imported are in the same folder, all that is needed is the file name. </p>
<p>My next set of code includes:</p>
<pre><code> if __name__ == "__main__":
Testfilename = '????' #this is what I do not know what to put in my code!
fav_cars_dict = {}
path = open(Testfilename)
</code></pre>
<p>Based on when I want to input a file into my code myself, I would just put the file name where I have question marks above. What do I put here, if I do not know the name of the file the user will be putting in? I did not include the code after this, but will if it is needed to help the problem. I just proceeded to convert the file to a dictionary using for-loops by filling in the question marks with a file that has 10 sets of numbers in one column that I created.</p>
| 0 | 2016-08-13T00:19:24Z | 38,928,480 | <p>Assuming this is run on the command line, you'll want to use <code>argparse</code> to get the file path from the user, instead of <code>raw_input</code>. But either way, you shouldn't worry about where the user is importing the file from. Files specified by relative and absolute path are practically handled the same way. So your "???" would still be fav_cars. If you're really curious, os.path.abspath(<em>path</em>) will give you the absolute path for any valid path the user enters. </p>
| 0 | 2016-08-13T01:59:43Z | [
"python",
"python-2.7",
"dictionary"
] |
Asking user to input a file from their computer | 38,928,015 | <p>New python 2.7 user. I just started learning about dictionaries and asking the user for input so I can make a little code to practice manipulating dictionaries such as simple math computations. </p>
<p>I am able to ask a user to input something manually such as :</p>
<pre><code> fav_numbs = (raw_input("What is your favorite car and color?: "))
</code></pre>
<p>I am wanting to get the user's information in a dictionary. Instead of asking the user to manually type in their favorite cars and colors of that car, I want them to import their own file from their computer. So far, I have came up with:</p>
<pre><code> fav_cars = raw_input('Enter file name that contains your favorite cars and color. The file must have the first column as favorite cars and a second column includes your favorite color of that particular car: ')
myfile = open(fav_cars, 'r')
</code></pre>
<p>I am assuming the user can just put in the file name the same way as one can input a file into their python code? I know that if the python file and the file being imported are in the same folder, all that is needed is the file name. </p>
<p>My next set of code includes:</p>
<pre><code> if __name__ == "__main__":
Testfilename = '????' #this is what I do not know what to put in my code!
fav_cars_dict = {}
path = open(Testfilename)
</code></pre>
<p>Based on when I want to input a file into my code myself, I would just put the file name where I have question marks above. What do I put here, if I do not know the name of the file the user will be putting in? I did not include the code after this, but will if it is needed to help the problem. I just proceeded to convert the file to a dictionary using for-loops by filling in the question marks with a file that has 10 sets of numbers in one column that I created.</p>
| 0 | 2016-08-13T00:19:24Z | 38,929,253 | <p>To have an input argument, use sys python library. Add to a file </p>
<pre><code>import sys
import os
if __name__ == "__main__":
test_dir_name = os.getcwd() # Current directory
test_file_name = sys.argv[1] # Get the first input argument
path = open(os.path.join(test_dir_name, test_file_name))
</code></pre>
<p>If the above file is named PythonDictReader.py, you can execute using</p>
<pre><code>python PythonDictReader.py file_name
</code></pre>
| 0 | 2016-08-13T04:40:40Z | [
"python",
"python-2.7",
"dictionary"
] |
Identify whether or not a number is prime | 38,928,040 | <p>The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong? </p>
<pre><code>quuN = int(input("ENTER NUMBER : "))
quuM = 2
if (quuN <= 0) :
print("ENTER NON-NEGATIVE NUMBER PLEASE")
elif (quuN % quuM == 0) :
print(" IS PRIME " )
else :
print("IS NOT PRIME ")
</code></pre>
| -3 | 2016-08-13T00:25:25Z | 38,928,073 | <p>The logic is incorrect </p>
<p>A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.</p>
<p>Simple python code below</p>
<pre><code>def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
</code></pre>
| 0 | 2016-08-13T00:32:06Z | [
"python"
] |
Identify whether or not a number is prime | 38,928,040 | <p>The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong? </p>
<pre><code>quuN = int(input("ENTER NUMBER : "))
quuM = 2
if (quuN <= 0) :
print("ENTER NON-NEGATIVE NUMBER PLEASE")
elif (quuN % quuM == 0) :
print(" IS PRIME " )
else :
print("IS NOT PRIME ")
</code></pre>
| -3 | 2016-08-13T00:25:25Z | 38,928,075 | <p>The above code is checking if a number is even or odd. If you enter a prime number, for example 17, the code checks if 17 is less than or equal to 0. Then it checks <em>17%2</em> which evalutes to 1, and is not 0. Hence the else block is executed which prints <strong>IS NOT PRIME</strong>.</p>
<p>If you enter an even number, it prints <strong>IS PRIME.</strong></p>
<p>This code checks for Prime numbers.</p>
<pre><code>def is_prime(n):
import math
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
</code></pre>
| 0 | 2016-08-13T00:32:25Z | [
"python"
] |
Identify whether or not a number is prime | 38,928,040 | <p>The below code keeps displaying "is not prime" for a prime number and "is prime" for a number that is not prime. What am I doing wrong? </p>
<pre><code>quuN = int(input("ENTER NUMBER : "))
quuM = 2
if (quuN <= 0) :
print("ENTER NON-NEGATIVE NUMBER PLEASE")
elif (quuN % quuM == 0) :
print(" IS PRIME " )
else :
print("IS NOT PRIME ")
</code></pre>
| -3 | 2016-08-13T00:25:25Z | 38,932,460 | <p>I assume you're a beginner with python so let me point out the logic to check primality of numbers in your code is not correct, you should read first carefully the definition of <a href="https://en.wikipedia.org/wiki/Prime_number" rel="nofollow">primes numbers</a>, when you do so, try to understand this little example which shows you how to check prime numbers:</p>
<pre><code>import math
def is_prime_naive(number):
if number == 2:
return True
if number % 2 == 0:
return False
i = 3
sqrt_number = math.sqrt(number)
while i <= sqrt_number:
if number % i == 0:
return False
i = i+2
return True
for i in range(2,101):
print "{0} {1} prime".format(i,"is" if is_prime_naive(i) else "is not")
</code></pre>
<p>Now, be aware the above code is one of the simplest but also slowest way to check whether a number is prime or not. When you become familiar enough with the concept of primes then you should check for fastest way to check primality, some examples could be the Fermat and Miller Rabin primality tests. So, good luck with primes, you'll sure have fun with them ;-) </p>
| 0 | 2016-08-13T11:55:58Z | [
"python"
] |
Adding a column to existing csv file as an array (Python) | 38,928,112 | <p>Have a csv file called 'data.csv' in the following format:</p>
<pre><code>test1,test2,test3
1,2,3
4,5,6
7,8,9
</code></pre>
<p>Given a list in the format ['test4', 4, 7, 10], how can I create a new csv file 'adjusted.csv' with all the data from data.csv and the added column like so:</p>
<pre><code>test1,test2,test3, test4
1,2,3,4
4,5,6,7
7,8,9,10
</code></pre>
| 1 | 2016-08-13T00:40:46Z | 38,928,203 | <p>read lines in</p>
<pre><code>with open('data.csv', 'r') as fi:
lines = [[i.strip() for i in line.strip().split(',')] \
for line in fi.readlines()]
col = ['test4', 4, 7, 10]
</code></pre>
<p>Concatenate each row with corresponding element of <code>col</code>. Using enumerate to help keep track of which list index to use.</p>
<pre><code>new_lines = [line + [str(col[i])] for i, line in enumerate(lines)]
</code></pre>
<p>Output to file</p>
<pre><code>with open('adjusted.csv', 'w') as fo:
for line in new_lines:
fo.write(','.join(line) + '\n')
</code></pre>
| 0 | 2016-08-13T01:00:34Z | [
"python",
"list",
"csv"
] |
Adding a column to existing csv file as an array (Python) | 38,928,112 | <p>Have a csv file called 'data.csv' in the following format:</p>
<pre><code>test1,test2,test3
1,2,3
4,5,6
7,8,9
</code></pre>
<p>Given a list in the format ['test4', 4, 7, 10], how can I create a new csv file 'adjusted.csv' with all the data from data.csv and the added column like so:</p>
<pre><code>test1,test2,test3, test4
1,2,3,4
4,5,6,7
7,8,9,10
</code></pre>
| 1 | 2016-08-13T00:40:46Z | 38,928,315 | <p>I would just treat the csv like the raw text it is. Load in each line, strip off the line break, append the new entry, then put the line break back. <strong>This only works if the entries in test4 are guaranteed to be in the same order as the rows in data.csv.</strong> </p>
<p>If instead test4 needs to be added to rows based on meeting certain conditions, that would change things a lot. In that case you would probably want to turn both into Pandas dataframes, then perform a proper merge on the required conditions.</p>
<pre><code>test4 = ['test4', 4, 7, 10]
with open(data.csv, 'r') as ifile
with open(adjusted.csv, 'w') as ofile:
for line, new in zip(ifile, test4):
new_line = line.rstrip('\n') + ',' + str(new) + '\n'
ofile.write(new_line)
</code></pre>
<p>You can also condense the first two lines into this:</p>
<pre><code>with open(data.csv, 'r') as ifile, open(adjusted.csv, 'w') as ofile:
</code></pre>
<p>Do whichever reads more clearly.</p>
| 1 | 2016-08-13T01:22:09Z | [
"python",
"list",
"csv"
] |
Adding a column to existing csv file as an array (Python) | 38,928,112 | <p>Have a csv file called 'data.csv' in the following format:</p>
<pre><code>test1,test2,test3
1,2,3
4,5,6
7,8,9
</code></pre>
<p>Given a list in the format ['test4', 4, 7, 10], how can I create a new csv file 'adjusted.csv' with all the data from data.csv and the added column like so:</p>
<pre><code>test1,test2,test3, test4
1,2,3,4
4,5,6,7
7,8,9,10
</code></pre>
| 1 | 2016-08-13T00:40:46Z | 38,928,332 | <p>Since you're working with csv files use the <code>csv</code> <code>readers</code> and <code>writers</code> to improve readability:</p>
<pre><code>import csv
new_data = ['test4', 4, 7, 10]
with open(r'data.csv', 'r') as in_csv, open(r'adj_data.csv', 'w') as out_csv:
reader = csv.reader(in_csv)
writer = csv.writer(out_csv)
for row, new_col in zip(reader, new_data):
row.append(new_col)
writer.writerow(row)
</code></pre>
| 0 | 2016-08-13T01:24:23Z | [
"python",
"list",
"csv"
] |
mongodb: how to check if a value is associated to a specific key | 38,928,131 | <p>I'm trying to write a python program that checks if a value is mapped to a specific key in a mongodb document. Is there anyway to do this?</p>
<pre><code>if { key_1 : value_1 } in db_i/collection_j/document_k:
do this
elif { key_1 : value_2 } in db_i/collection_j/document_k:
do something else
</code></pre>
| 0 | 2016-08-13T00:45:01Z | 38,981,834 | <p>Figured out the answer, thanks to the comments above:</p>
<pre><code>if db.collection.find_one({"Pod":"24"},{"Available":False}) is None:
perform update that "$sets" {"Available":False}
else:
do nothing because {Available:False} already exists
print "Pod 24 is already unavailable"
</code></pre>
<p>This allows me to check if the key-value pair exists in the query document (Pod 24) and do something (change Available to False) based on the result.</p>
| 0 | 2016-08-16T18:16:05Z | [
"python",
"mongodb"
] |
Patching a parent class | 38,928,243 | <p>I'm having trouble getting a parent class mocked with <code>mock.patch</code>.</p>
<p>Here's a test case:</p>
<p>In <code>parent.py</code>:</p>
<pre><code>import mock
class Parent():
def __init__(self):
print("Original recipe")
</code></pre>
<p>In <code>child.py</code>:</p>
<pre><code>from parent import Parent
class Child(Parent):
def foo(self):
print('Parent is {}'.format(Parent))
</code></pre>
<p>In <code>test.py</code>:</p>
<pre><code>import mock
from child import Child
c = Child() # expect 'Original recipe'
c.foo()
with mock.patch('child.Parent'):
c = Child() # expect silence
c.foo()
</code></pre>
<p>When I run <code>test.py</code> I expect to get:</p>
<pre><code>Original recipe
Parent is <class 'parent.Parent'>
Parent is <MagicMock name='Parent' id='4325705712'>
</code></pre>
<p>but instead I get:</p>
<pre><code>Original recipe
Parent is <class 'parent.Parent'>
Original recipe
Parent is <MagicMock name='Parent' id='4325705712'>
</code></pre>
<p>So the patch is happening (from the "Parent is" statement) but not for the class inheritance. How can I fix that?</p>
| 1 | 2016-08-13T01:06:35Z | 38,928,265 | <p>You are not patching the <code>Parent</code> class, you are patching the <code>child</code> module, changing its <code>Parent</code> attribute to a mock. This does not change <code>Child</code> at all, because it still uses the old <code>Parent</code> class as base class.</p>
<p>In Python 3, you can instead patch <code>Child.__bases__</code> to change the base class at runtime. This come with its weirdnesses, of course.</p>
<h1>Additional details</h1>
<p>Python has no "variables", only names bound to specific objects in memory. Changing those names bindings (e.g. patching the scope they are contained it with <code>mock.patch</code> or <code>setattr</code>) has absolutely no effect on previous uses of these bindings.</p>
<p>This means that although you do patch the <code>Parent</code> attribute of the <code>child</code> module, replacing it by a <code>Mock</code>, as the module has already loaded, the class is already defined with the old target of the <code>Parent</code> attribute, which is, the original <code>Parent</code> class.</p>
<h1>Other ways to test <code>Child</code> instances</h1>
<h2>As if <code>Parent</code> as external</h2>
<pre><code>with mock.patch('child.Child.method_that_calls_method_on_parent'):
...
</code></pre>
<p>If you want to isolate and mock method on <code>Parent</code> when testing instances of <code>Child</code>, you could make the calls to <code>Parent</code> sit in dedicated methods (and then patch these methods), as you'd do test external classes.</p>
<h2>Patching methods on <code>Parent</code></h2>
<p>If you know in advance which methods of <code>Parent</code> you'll need to patch, you can just imply patch the methods on <code>Parent</code>.</p>
<pre><code>with mock.patch('parent.Parent.method'):
...
</code></pre>
<p>This will mutate the value of the <code>Parent</code> attribute (which is the same for the <code>child</code> and <code>parent</code> modules, as <code>child</code> imports <code>Parent</code> from <code>parent</code>), instead of modifying which objects the <code>Parent</code> attribute points to in a particular module as you were doing before.</p>
<h2>Making <code>Parent</code> behave like a <code>Mock</code></h2>
<pre><code>with mock.patch('parent.Parent.__getattribute__'):
...
</code></pre>
<p>This is the most close to the intent of your original code. It relies on changing the way Python gets attributes from the <code>Parent</code> class, effectively patching all of its possible attributes.</p>
<p>The disadvantage with this is that you'd get a mock even for non-existing attributes, but that was the case with your original approach as well. This can be overcome by replacing <code>__getattribute__</code> with a wrapper that returns a mock only for found attributes :</p>
<pre><code>def _getmock(self, name):
value = object.__getattribute__(self, name)
return Mock(value)
_original = getattr(parent.Parent, '__getattribute__')
setattr(parent.Parent, '__getattribute__', _getmock)
try:
...
finally:
setattr(parent.Parent, '__getattribute__', _original)
</code></pre>
<p>(Your test suite probably provides a way to temporarily patch <code>_getmock</code> as <code>parent.Parent.__getattribute__</code>, as <code>mock.patch</code> does, which would make this simpler.)</p>
<p>This can be further customized to specify the type and parameters of the mock created depending on the attribute name (<code>name</code> in <code>_getmock</code>) or value (<code>value</code> in <code>_getmock</code>), or making it so that the same mock is returned for when the same attribute name is accessed multiple times.</p>
| 2 | 2016-08-13T01:11:15Z | [
"python",
"python-3.x",
"mocking"
] |
Convert multiple types of dates | 38,928,292 | <p>I'm working with data that comes from different places and need to convert dates into the same format. Below are few examples of what I have:</p>
<pre><code>Thu Dec 03 07:27:23 GMT 2015
3-Dec-15
2015-12-04T06:58:54Z
23-Sep-2015 07:03:37 UTC
</code></pre>
<p>The desired output format should be the same for all dates, like this:</p>
<pre><code>12/03/2007
12/03/2015
12/04/2015
09/23/2015
</code></pre>
<p>Any suggestions how to achieve that with Python? Thanks in advance!</p>
| 3 | 2016-08-13T01:17:21Z | 38,928,309 | <p>Yes, the <a href="https://pypi.python.org/pypi/python-dateutil/1.5" rel="nofollow">dateutil</a> library provides date format detection with the <a href="http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2" rel="nofollow"><code>parse</code></a> function :</p>
<pre><code>from dateutil.parser import parse
parse(text).strftime("%m/%d/%Y")
</code></pre>
| 3 | 2016-08-13T01:20:39Z | [
"python",
"date",
"datetime",
"format"
] |
Error of running an executable file from Python subprosess | 38,928,330 | <p>I am trying to run an executable file (a linear programming solver CLP.exe) from Python 3.5. </p>
<pre><code> Import subprocess
exeFile = " C:\\MyPath\\CLP.exe"
arg1 = "C:\\Temp\\LpModel.mps"
arg2 = "-max"
arg3 = " -dualSimplex"
arg4 = " -printi all"
arg5 = "-solution t solutionFile.txt"
subprocess.check_output([exeFile, arg1, arg2, arg3, arg4, arg5], stderr=subprocess.STDOUT, shell=False)
</code></pre>
<p>When I run the python file in Eclipse PyDev, I can see the results in Eclipse console. </p>
<p>But, no solution results are saved at the file of "solutionFile.txt".</p>
<p>In the Eclipse console, I got: </p>
<pre><code> b'Coin LP version 1.16, build Dec 25 2015
command line - C:\\MyPath\\clp.exe C:\\Temp\\LpModel.mps -max -dualSimplex -printi all -solution C:\\Temp\\solution.txt
At line 1 NAME ClpDefau
At line 2 ROWS
At line 5 COLUMNS
At line 8 RHS
At line 10 BOUNDS
At line 13 ENDATA
Problem ClpDefau has 1 rows, 2 columns and 2 elements
Model was imported from C:\\Temp\\LpModel.mps in 0.001 seconds
No match for -max - ? for list of commands
No match for -dualSimplex - ? for list of commands
No match for -printi all - ? for list of commands
No match for -solution C:\\Temp\\solution.txt - ? for list of commands
Presolve 0 (-1) rows, 0 (-2) columns and 0 (-2) elements
Empty problem - 0 rows, 0 columns and 0 elements
Optimal - objective value 4
After Postsolve, objective 4, infeasibilities - dual 0 (0), primal 0 (0)
Optimal objective 4 - 0 iterations time 0.002, Presolve 0.00
</code></pre>
<p>When I run the command in MS windows shell from command line: </p>
<pre><code> C:\\MyPath\\clp.exe C:\\Temp\\LpModel.mps -max -dualSimplex -printi all -solution C:\\Temp\\solution.txt
</code></pre>
<p>I can get results in the solution file. And, the bold lines do not appear in the output if I run the command in the command line.</p>
<p>Why the solition.txt file was not created and no solutions results were saved to it if I run the command from Python subprocess ? </p>
| 1 | 2016-08-13T01:24:12Z | 38,928,366 | <p>Every space separated token needs to be another argument in the array for <code>subprocess.check_output</code></p>
<pre><code>exeFile = " C:\\MyPath\\CLP.exe"
subprocess.check_output([
exeFile,
"C:\\Temp\\LpModel.mps",
"-max",
"-dualSimplex",
"-printi",
"all",
"-solution",
"t",
"solutionFile.txt"],
stderr=subprocess.STDOUT,
shell=False)
</code></pre>
| 1 | 2016-08-13T01:31:53Z | [
"python",
"eclipse",
"python-3.x",
"pydev",
"clp"
] |
Python os.walk skip directories with specific name instead of path | 38,928,423 | <p>So I have a file system that I want to be able to check and update using python. my solution was os.walk but it becomes problematic with my needs and my file system. This is how the directories are laid out:</p>
<pre><code>Root
dir1
subdir
1
2
3...
file1
file2
dir2
subdir
1
2
3...
file1
file2
...
</code></pre>
<p>The main directories have different names hence "dir1" and "dir2" but the directories inside those have the same name as each other and contain a lot of different files and directories. The sub directories are the ones I want to exclude from os.walk as they add unnecessary computing.</p>
<p>Is there a way to exclude directories from os.walk based on the directory's name instead of path or will I need to do something else?</p>
| 0 | 2016-08-13T01:45:10Z | 38,928,455 | <p><code>os.walk</code> allows you to modify the list of directories it gives you. If you take some out, it won't descend into those directories.</p>
<pre><code>for dirpath, dirnames, filenames in os.walk("/root/path"):
if "subdir" in dirnames:
dirnames.remove("subdir")
# process the files here
</code></pre>
<p>(Note that this doesn't work if you use the bottom-up style of scanning.)</p>
<p><a href="https://docs.python.org/2/library/os.html#os.walk">See the documentation</a></p>
| 5 | 2016-08-13T01:51:42Z | [
"python",
"os.walk"
] |
regular expression match issue in Python 2.7 | 38,928,601 | <p>Using Python 2.7, want to use regular expression to find the <code>Hello</code> part of a given string. The rule is, <code>Hello</code> maybe in the pattern starts with <code>{(1N)</code>, <code>{(2N)</code> (until <code>10N</code>), or combination of them <code>{(1N,2N,3N,4N)</code>, and ends with <code>}</code>.</p>
<p>Besides match the <code>Hello</code> part, I also want to know if <code>1N</code> match, or <code>2N</code> match or <code>10N</code> match, or either <code>1N</code> or <code>2N</code> match.</p>
<p>Any solutions are appreciated. </p>
<pre><code> Some content {(1N,2N,3N,4N) Hello } Some content
Some content {(1N) Python } Some content
Some content {(2N) Regex } Some content
</code></pre>
<p>In the first example, I want to know <code>1N</code>,<code>2N</code>,<code>3N</code>,<code>4N</code> matches, and the matched string is <code>Hello</code>;</p>
<p>In the 2nd example, I want to know <code>1N</code> matches, and matched string is <code>Python</code>;
In the 3rd example, I want to know <code>2N</code> matches, and matched string is <code>Regex</code>;</p>
<p>regards,
Lin</p>
| 1 | 2016-08-13T02:23:04Z | 38,928,651 | <p>Regular expressions cannot really count (which is why you say you tried to write 10 times the same pattern), but instead you can match the sequence and then split to count :</p>
<pre><code>In [100]: match = re.compile(r"\{\s?\(\s?((\d+N,?)+)\)\s?(.*)\s?\}").search("Some content { (1N,2N,3N,4N) Hello } Some content")
In [101]: items, _, text = match.groups()
In [102]: splitted = items.split(',')
In [103]: print(splitted)
['1N', '2N', '3N', '4N']
In [104]: print(text)
Hello
</code></pre>
<p>NOTE: All the <code>\s?</code> are there to handle optional blanks, remove them if you know you don't need at certain places.</p>
| 2 | 2016-08-13T02:36:25Z | [
"python",
"regex",
"python-2.7"
] |
regular expression match issue in Python 2.7 | 38,928,601 | <p>Using Python 2.7, want to use regular expression to find the <code>Hello</code> part of a given string. The rule is, <code>Hello</code> maybe in the pattern starts with <code>{(1N)</code>, <code>{(2N)</code> (until <code>10N</code>), or combination of them <code>{(1N,2N,3N,4N)</code>, and ends with <code>}</code>.</p>
<p>Besides match the <code>Hello</code> part, I also want to know if <code>1N</code> match, or <code>2N</code> match or <code>10N</code> match, or either <code>1N</code> or <code>2N</code> match.</p>
<p>Any solutions are appreciated. </p>
<pre><code> Some content {(1N,2N,3N,4N) Hello } Some content
Some content {(1N) Python } Some content
Some content {(2N) Regex } Some content
</code></pre>
<p>In the first example, I want to know <code>1N</code>,<code>2N</code>,<code>3N</code>,<code>4N</code> matches, and the matched string is <code>Hello</code>;</p>
<p>In the 2nd example, I want to know <code>1N</code> matches, and matched string is <code>Python</code>;
In the 3rd example, I want to know <code>2N</code> matches, and matched string is <code>Regex</code>;</p>
<p>regards,
Lin</p>
| 1 | 2016-08-13T02:23:04Z | 38,928,744 | <pre><code>In [82]: string = "Some content {(1N,2N,3N,4N) Hello } Some content"
In [83]: result = re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string)
In [84]: nums = re.findall(r"10N|[1-9]N", result[0][0])
In [85]: nums
Out[85]: ['1N', '2N', '3N', '4N']
In [86]: matchString = result[0][1]
In [87]: matchString
Out[87]: 'Hello'
</code></pre>
<p>For the new string:</p>
<pre><code>In [1]: import re
In [2]: string = "{(1N,2N,3N,4N) Hello } Some Content {(5N) World }"
In [3]: re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string)
Out[3]: [('(1N,2N,3N,4N)', 'Hello'), ('(5N)', 'World')]
In [4]: result = re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string)
In [5]: nums = [re.findall(r"10N|[1-9]N", item[0]) for item in result]
In [6]: nums
Out[6]: [['1N', '2N', '3N', '4N'], ['5N']]
In [7]: matchString = [s[1] for s in result]
In [8]: matchString
Out[8]: ['Hello', 'World']
</code></pre>
| 1 | 2016-08-13T02:53:32Z | [
"python",
"regex",
"python-2.7"
] |
Vectorizing a function that finds the nearest value in an array | 38,928,617 | <p>I've written the following function:</p>
<pre><code>import numpy as np
def _find_nearest(array, value):
"""Find the index in array whose element is nearest to value.
Parameters
----------
array : np.array
The array.
value : number
The value.
Returns
-------
integer
The index in array whose element is nearest to value.
"""
if array.argmax() == array.size - 1 and value > array.max():
return array.size
return (np.abs(array - value)).argmin()
</code></pre>
<p>I'd like to vectorize this function, so that I can pass several values at once. That is, I'd like to have <code>value</code> be an array, and have <code>_find_nearest</code> return, rather than a single index, the indices for each of the values in the submitted <code>value_array</code>.</p>
<p>Can anyone see a way to do this?</p>
| 1 | 2016-08-13T02:27:36Z | 38,928,648 | <p>Inside the parent function, where both the <code>value</code> and the <code>array</code> are visible, you can use a <code>lambda</code> to enable the vectorization. I shall call the parent function <code>main</code></p>
<pre><code>def main():
value = np.random.rand(10, 1)
array = np.random.rand(100, 100)
vec_nearest = lambda x: _find_nearest(array, x)
np.vectorize(vec_nearest)(value)
</code></pre>
<p>This will work on one <code>array</code>, and multiple values of <code>vector</code>. The return will be an array.</p>
| 1 | 2016-08-13T02:35:14Z | [
"python",
"numpy",
"vectorization"
] |
iterating a stock tick data with append on python | 38,928,632 | <p>I am trying to combine a series of stock tick data based on the dates.
But it wont work. Please help.</p>
<pre><code>import pandas as pd
import tushare as ts
def get_all_tick(stockID):
dates=pd.date_range('2016-01-01',periods=5,freq='D')
append_data=[]
for i in dates:
stock_tick=pd.DataFrame(ts.get_tick_data(stockID,date=i))
stock_tick.sort('volume',inplace=True, ascending=False)
stock_tick=stock_tick[:10]
stock_tick.sort('time',inplace=True, ascending=False)
append_data.append(stock_tick.iterrows())
get_all_tick('300243')
</code></pre>
| -1 | 2016-08-13T02:31:16Z | 38,929,454 | <p>Eyeballing your code, the most obvious missing thing is a <code>return</code> statement:</p>
<pre><code>def get_all_tick(stockID):
dates=pd.date_range('2016-01-01',periods=5,freq='D')
append_data=[]
for i in dates:
# ...
return append_data
</code></pre>
<p>Whatever is in the return statement will be the result of calling <code>get_all_tick('300243')</code></p>
| 0 | 2016-08-13T05:14:06Z | [
"python",
"loops",
"append",
"concat",
"stock"
] |
iterating a stock tick data with append on python | 38,928,632 | <p>I am trying to combine a series of stock tick data based on the dates.
But it wont work. Please help.</p>
<pre><code>import pandas as pd
import tushare as ts
def get_all_tick(stockID):
dates=pd.date_range('2016-01-01',periods=5,freq='D')
append_data=[]
for i in dates:
stock_tick=pd.DataFrame(ts.get_tick_data(stockID,date=i))
stock_tick.sort('volume',inplace=True, ascending=False)
stock_tick=stock_tick[:10]
stock_tick.sort('time',inplace=True, ascending=False)
append_data.append(stock_tick.iterrows())
get_all_tick('300243')
</code></pre>
| -1 | 2016-08-13T02:31:16Z | 38,967,196 | <p>I figure it out myself. </p>
<pre><code>def get_all_tick(stockID):
.........
df = pd.DataFrame()
for i in get_date:
stock_tick = ts.get_tick_data(stockID, date=i)
stock_tick['Date']=i
stock_tick.sort('volume', inplace=True, ascending=False)
stock_tick = stock_tick[:10]
stock_tick.sort('time', inplace=True, ascending=False)
df = df.append(stock_tick)
df.to_excel('tick.xlsx',sheet_name='Sheet1')
get_all_tick('300243')
</code></pre>
| 1 | 2016-08-16T05:27:31Z | [
"python",
"loops",
"append",
"concat",
"stock"
] |
Python 3.5: Print Canvas Text | 38,928,665 | <p>Could anyone share with me how to print the text of the text widget added to a Canvas object? In the code below, I want the system return the value of "hello" when mouse on the text, however, it turns out giving me "1". Don't know why. Could anyone help me?</p>
<p>Many many thanks!!!</p>
<pre><code>import tkinter
from tkinter import *
def show_text(event):
print (canvas.text)
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")
mainloop()
</code></pre>
| -1 | 2016-08-13T02:38:38Z | 38,929,698 | <p>According to the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_text.html" rel="nofollow">canvas docs</a>:</p>
<blockquote>
<p>You can display one or more lines of text on a canvas C by creating a
text object:</p>
<pre><code>id = C.create_text(x, y, option, ...)
</code></pre>
<p>This returns the object ID of the text object on canvas C.</p>
</blockquote>
<p>Now, you gotta modify the code something like this:</p>
<pre><code>import tkinter
from tkinter import *
def show_text(event):
print (canvas.itemcget(obj_id, 'text'))
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
obj_id = canvas.create_text(20, 30, text="hello")
mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/VFoNQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/VFoNQ.png" alt="getting-text-from-canvas"></a></p>
<p>Follow up (see the documentation for <a href="http://effbot.org/tkinterbook/label.htm#Tkinter.Label.config-method" rel="nofollow">Label.config</a>:</p>
<pre><code>import tkinter
from tkinter import *
from tkinter import ttk
def show_text(event):
print (canvas.itemcget(canvas.text, 'text'))
#The command of writing text 'hello' in sch_Label to replace the text 'the info shows here'
sch_Label.config(text = 'hello!')
master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")
pad1 = ttk.Notebook(master)
pad1.pack(side=RIGHT, expand=1, fill="both")
tab1 = Frame(pad1)
pad1.add(tab1, text = "Schedule")
pad1.pack(side=RIGHT)
sch_Label = ttk.Label(tab1, text='The info shows here')
sch_Label.pack(side="top", anchor="w")
mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/QR6ox.gif" rel="nofollow"><img src="http://i.stack.imgur.com/QR6ox.gif" alt="enter image description here"></a></p>
| 1 | 2016-08-13T05:52:23Z | [
"python",
"tkinter",
"tkinter-canvas"
] |
How to understand ndarray.reshape function? | 38,928,669 | <p>The prototype of <code>reshape()</code> is that <code>reshape(shape, order="C")</code>, and the type of shape is tuple.
So we should call this function with <code>myarray.reshape((1000, 1, 32, 32))</code>, But I find that many use <code>myarray.reshape(1000, 1, 32, 32)</code>, why?</p>
| 2 | 2016-08-13T02:39:07Z | 38,928,861 | <p>It's a bit of hidden flexibility built into the <code>reshape</code> method.</p>
<p>The keyword here needs to be explicit: you <em>can't</em> do for example:</p>
<pre><code>myarray.reshape(1000, 1, 32, 32, "C")
</code></pre>
<p>You'll get a <code>TypeError</code>, saying that an integer is required.</p>
<p>(In fact, even using a tuple:</p>
<pre><code>myarray.reshape((1000, 1, 32, 32), "C")
</code></pre>
<p>raises the <code>TypeError</code>.)</p>
<p>If you look at the source code (e.g., at <a href="https://github.com/numpy/numpy/blob/945c308e96fb815729e8f8aeb0ad6b39b8bdf84a/numpy/core/src/multiarray/methods.c#L171" rel="nofollow">GitHub</a>, you'll see that, after the keywords are parsed, there is a check for 0 or 1 arguments. In that case, the argument is interpreted as a tuple. If there are more arguments, each is interpreted as an integer and combined into a tuple as the new shape (the keyword arguments have already been taken out).</p>
<hr>
<p>As to which one you should use: I guess there's not really a good answer.<br>
You could stick with the documentation, and use tuples.<br>
The multiple-integer-arguments convention, however, feels rather obvious.</p>
<p>Do stick to the convention that you, or the project you're working on, use(s). Don't use tuples and individual integer arguments in the same project.</p>
| 3 | 2016-08-13T03:19:12Z | [
"python",
"numpy"
] |
Python test class stuck on 'Instantiating tests' | 38,928,748 | <p>My test class produces the required plot, but I have to manually stop execution every time - the console continues to show 'Instantiating tests'; can anyone spot why the execution never halts? Any tips on increasing my code's 'Pythonic-ness' would also be appreciated!</p>
<p>(Python 3.5 running in PyCharm CE 2016.2.1 on Mac OS X 10.11.6)</p>
<pre><code># A program to test various sorting algorithms. It generates random lists of various sizes,
# sorts them, and then tests that:
# a. the list is in ascending order
# b. the set of elements is the same as the original list
# c. record the time taken
import random
import timeit
from unittest import TestCase
import matplotlib.pyplot as plt
from Sorter import insertionsort, mergesort, quicksort
class TestSort(TestCase):
def test_sorting(self):
times_insertionsort = [] # holds the running times for insertion sort
times_quicksort = [] # holds the running times for quick sort
times_mergesort = [] # holds the running times for merge sort
lengths = [] # holds the array lengths
# determine the number of lists to be created
for i in range(0, 13):
# initialise a new empty list
pre_sort = []
# determine the list's length, then populate the list with 'random' data
for j in range(0, i * 100):
pre_sort.append(random.randint(0, 1000))
# record the length of the list
lengths.append(len(pre_sort))
# record the time taken by quicksort to sort the list
start_time = timeit.default_timer()
post_quicksort = quicksort(pre_sort)
finish_time = timeit.default_timer()
times_quicksort.append((finish_time - start_time) * 1000)
# record the time taken by insertionsort to sort the list
start_time = timeit.default_timer()
post_insertionsort = insertionsort(pre_sort)
finish_time = timeit.default_timer()
times_insertionsort.append((finish_time - start_time) * 1000)
# record the time taken by mergesort to sort the list
start_time = timeit.default_timer()
post_mergesort = mergesort(pre_sort)
finish_time = timeit.default_timer()
times_mergesort.append((finish_time - start_time) * 1000)
# check that:
# a. the list is in ascending order
# b. the set of elements is the same as the original list
for k in range(0, len(pre_sort) - 1):
self.assertTrue(post_insertionsort[k] in pre_sort)
self.assertTrue(post_insertionsort[k] <= post_insertionsort[k + 1])
self.assertTrue(post_mergesort[k] == post_insertionsort[k])
self.assertTrue(post_mergesort[k] == post_quicksort[k])
# plot the results
plt.plot(lengths, times_insertionsort, 'r')
plt.plot(lengths, times_quicksort, 'g')
plt.plot(lengths, times_mergesort, 'b')
plt.xlabel('List size')
plt.ylabel('Execution time (ms)')
plt.show()
</code></pre>
| 0 | 2016-08-13T02:53:49Z | 38,929,105 | <p>You need to close the window where the plot is shown in order for the script (your test in this case) to continue/complete/finish. <a href="http://matplotlib.org/faq/howto_faq.html#use-show" rel="nofollow">From the docs</a>, emphasis mine:</p>
<blockquote>
<p>When you want to view your plots on your display, the user interface backend will need to start the GUI mainloop. This is what <code>show()</code> does. It tells matplotlib to raise all of the figure windows created so far and start the mainloop. <strong>Because this mainloop is blocking by default (i.e., script execution is paused), you should only call this once per script, at the end. Script execution is resumed after the last window is closed.</strong> Therefore, if you are using matplotlib to generate only images and do not want a user interface window, you do not need to call show (see Generate images without having a window appear and What is a backend?).</p>
</blockquote>
<p>Or don't use <code>show()</code> for the tests and just generate an image which you can verify against later.</p>
| 1 | 2016-08-13T04:10:56Z | [
"python",
"matplotlib"
] |
What does this mean in regular expressions? re.match(r"(^[cf-qs-z]+)", any file name)? | 38,928,755 | <p>I stumbled upon this code and I do not know what does it match:</p>
<pre><code>re.match(r"(^[cf-qs-z]+)", words)
</code></pre>
| -1 | 2016-08-13T02:55:23Z | 38,928,776 | <ul>
<li>The <code>f-q</code> and <code>s-z</code> are <em>character ranges</em>, meaning any letter from <code>f</code> to <code>q</code> and from <code>s</code> to <code>z</code> in the alphabet, case sensitive</li>
<li><code>c</code> is a <em>literal character</em> <code>c</code> - no special meaning</li>
<li><code>^</code> defines the <em>beginning of a string</em></li>
<li><code>+</code> is a <em>quantifier</em>, it means "one or more"</li>
<li>parenthesis define a <em>capturing group</em></li>
</ul>
<p>In other words the expression would match 1 more characters that are <code>c</code> or in <code>f</code> to <code>q</code> or <code>s</code> to <code>z</code> range at the start of a string.</p>
<p>In cases like this, if you need an explanation for an existing regular expression, try pasting it to <a href="https://regex101.com" rel="nofollow">https://regex101.com</a>, here is what it generates for this expression: <a href="https://regex101.com/r/cU0yT7/1" rel="nofollow">https://regex101.com/r/cU0yT7/1</a>.</p>
| 3 | 2016-08-13T02:59:34Z | [
"python",
"regex",
"python-2.7",
"pattern-matching",
"match"
] |
Different results in numpy vs matlab | 38,928,832 | <p>I'm trying to implement a gradient descent algorithm that was previously written in matlab in python with numpy, but I'm getting a set of similar but different results.</p>
<p>Here's the matlab code</p>
<pre><code>function [theta] = gradientDescentMulti(X, y, theta, alpha, num_iters)
m = length(y);
num_features = size(X,2);
for iter = 1:num_iters;
temp_theta = theta;
for i = 1:num_features
temp_theta(i) = theta(i)-((alpha/m)*(X * theta - y)'*X(:,i));
end
theta = temp_theta;
end
end
</code></pre>
<p>and my python version</p>
<pre><code>def gradient_descent(X,y, alpha, trials):
m = X.shape[0]
n = X.shape[1]
theta = np.zeros((n, 1))
for i in range(trials):
temp_theta = theta
for p in range(n):
thetaX = np.dot(X, theta)
tMinY = thetaX-y
temp_theta[p] = temp_theta[p]-(alpha/m)*np.dot(tMinY.T, X[:,p:p+1])
theta = temp_theta
return theta
</code></pre>
<p>Test case and results in matlab</p>
<pre><code>X = [1 2 1 3; 1 7 1 9; 1 1 8 1; 1 3 7 4]
y = [2 ; 5 ; 5 ; 6];
[theta] = gradientDescentMulti(X, y, zeros(4,1), 0.01, 1);
theta =
0.0450
0.1550
0.2225
0.2000
</code></pre>
<p>test case and result in python</p>
<pre><code>test_X = np.array([[1,2,1,3],[1,7,1,9],[1,1,8,1],[1,3,7,4]])
test_y = np.array([[2], [5], [5], [6]])
theta, cost = gradient_descent(test_X, test_y, 0.01, 1)
print theta
>>[[ 0.045 ]
[ 0.1535375 ]
[ 0.20600144]
[ 0.14189214]]
</code></pre>
| 0 | 2016-08-13T03:13:13Z | 38,928,929 | <p>This line in your Python:</p>
<pre><code> temp_theta = theta
</code></pre>
<p>doesn't do what you think it does. It doesn't make a copy of <code>theta</code> and "assign" it to the "variable" <code>temp_theta</code> -- it just says "<code>temp_theta</code> is now a new name for the object currently named by <code>theta</code>". </p>
<p>So when you modify <code>temp_theta</code> here:</p>
<pre><code> temp_theta[p] = temp_theta[p]-(alpha/m)*np.dot(tMinY.T, X[:,p:p+1])
</code></pre>
<p>You're actually modifying <code>theta</code> -- because there's only the one array, now with two names.</p>
<p>If you instead write</p>
<pre><code> temp_theta = theta.copy()
</code></pre>
<p>you'll get something like</p>
<pre><code>(3.5) dsm@notebook:~/coding$ python peter.py
[[ 0.045 ]
[ 0.155 ]
[ 0.2225]
[ 0.2 ]]
</code></pre>
<p>which matches your Matlab results.</p>
| 7 | 2016-08-13T03:34:02Z | [
"python",
"matlab",
"numpy"
] |
getting input in a function and calling it in another function | 38,928,900 | <p>how would this work? Lets say I have a function called getInput that gets three numbers based on user input </p>
<pre><code>def getInput():
num1 = int(input("please enter a int"))
num2 = int(input("please enter a int"))
num3 = int(input("please enter a int"))
</code></pre>
<p>how would I use this function in another function to do checks regarding the input? For example</p>
<pre><code>def calculation():
getInput()
if num1 > (num2 * num3):
print('Correct')
</code></pre>
<p>thanks!</p>
| 1 | 2016-08-13T03:28:26Z | 38,928,922 | <p>You need to <code>return</code> the variables (<code>num1</code>, <code>num2</code>, <code>num3</code>) from the <code>getInput</code> function.</p>
<p>Like this:</p>
<pre><code>def getInput():
num1 = int(input("please enter a int"))
num2 = int(input("please enter a int"))
num3 = int(input("please enter a int"))
return num1, num2, num3
</code></pre>
<p>then you can do:</p>
<pre><code>def calculation():
num1, num2, num3 = getInput()
if num1 > (num2 * num3):
print('Correct')
</code></pre>
| 2 | 2016-08-13T03:32:07Z | [
"python",
"function",
"input"
] |
getting input in a function and calling it in another function | 38,928,900 | <p>how would this work? Lets say I have a function called getInput that gets three numbers based on user input </p>
<pre><code>def getInput():
num1 = int(input("please enter a int"))
num2 = int(input("please enter a int"))
num3 = int(input("please enter a int"))
</code></pre>
<p>how would I use this function in another function to do checks regarding the input? For example</p>
<pre><code>def calculation():
getInput()
if num1 > (num2 * num3):
print('Correct')
</code></pre>
<p>thanks!</p>
| 1 | 2016-08-13T03:28:26Z | 38,929,010 | <p>Use an array for scalability. You may one day need to return 1000 values. Get the three numbers, place them in an array and return them as follows:</p>
<pre><code>num_list = [];
i = 3;
temp = 0;
while i > 0:
temp = int(input("please enter a int"));
num_list.append(temp);
temp=0;
i--;
return num_list;
</code></pre>
<p>Now get the returned data and use it as follows:</p>
<pre><code> def calculation():
getInput();
if num_list[1] > (num_list[2] * num_list[3]):
print('Correct')
</code></pre>
| 1 | 2016-08-13T03:52:37Z | [
"python",
"function",
"input"
] |
Heroku Scheduler vs Heroku Temporize Scheduler, what's the difference? | 38,928,911 | <p>I'm wondering what is the difference between the <a href="https://elements.heroku.com/addons/scheduler" rel="nofollow">Heroku Scheduler</a> add-on and the <a href="https://elements.heroku.com/addons/temporize" rel="nofollow">Heroku Temporize Scheduler</a> add-on. They both seem to be free and do scheduled jobs.</p>
<p>And how do they both compare to running a <a href="http://stackoverflow.com/a/474543/4825465">Python sched</a> in Heroku?</p>
<p>I would like to run just one cron job to scrape some websites every minute with Heroku Python saving to Postgres. (I'm also trying to figure out what to write in a cron job to do so, but that's another question.)</p>
<hr>
<p>Update with the solution:</p>
<p><strong>Thanks to danneu's suggestions, the working solution was using the Heroku Scheduler. It was super simple to set up thanks to <a href="http://guidovanoorschot.nl/adding-cron-jobs-to-a-django-project-with-heroku-scheduler/" rel="nofollow">this tutorial</a>.</strong></p>
<p>(I tried using sched and twisted, but both times I got:</p>
<pre><code>Application Error
An error occurred in the application and your page could not be served. Please try again in a few moments.
If you are the application owner, check your logs for details.
</code></pre>
<p>This was possibly due to my lack of experience of putting them in the correct place. It didn't work with a sync worker Heroku guricorn. I don't know the details.)</p>
| 2 | 2016-08-13T03:30:31Z | 38,942,364 | <p>Temporize is a 3rd party service. You'd have to read what the limitations of their free plan is. It looks like the free plan only lets you run a task 20 times per day which is a far cry from your needs of a 1-minute interval.</p>
<p>Heroku's Scheduler is offered by Heroku. It spins up a server for each task and bills you for the runtime. The minimum task interval on Heroku scheduler is 10 minutes which also won't give you what you want.</p>
<p>For a 1-minute interval that scrapes a page, I'd just run a concurrent loop in my Heroku app process. <code>setTimeout</code> in Javascript is an example of a concurrent loop that can run alongside your application server (if you were using Node). It looks like the Twisted example in your Python sched link is the Python equivalent.</p>
<p>If you're using Heroku's free-tier (which I think you are after seeing you in IRC), you get 1,000 runtime hours each month once you verify your account (else you only get 550 hours), which I imagine means giving them your credit card number. 1,000 hours is enough for a single dyno to run all month for free.</p>
<p>However, the free-tier dyno will sleep (turn off) if it has gone X amount of minutes without receiving an HTTP request. Obviously the Twisted/concurrent loop approach will only work while the dyno is awake and running since the loop runs inside your application process.</p>
<p>So if your dyno falls asleep, your concurrent loop will stop until your dyno wakes back up and resumes.</p>
<p>If you want your dyno to stay awake all month, you can upgrade your dyno for $7/mo. </p>
| 1 | 2016-08-14T12:42:23Z | [
"python",
"postgresql",
"heroku",
"cron",
"scheduled-tasks"
] |
Build Python as UCS-4 via pyenv | 38,928,942 | <p>I run into this issue <a href="http://stackoverflow.com/q/17443166/1391441">ImportError numpy/core/multiarray.so: undefined symbol: PyUnicodeUCS2_AsASCIIString</a> installing Python in a <a href="https://github.com/yyuu/pyenv-virtualenv" rel="nofollow">pyenv-virtualenv</a> environment.</p>
<p>In my case, it happens with the <code>matplotlib</code> package instead of <code>numpy</code> (as in the above question), but it's basically the same issue.</p>
<p>The answer given in that question is a simple:</p>
<blockquote>
<p>Rebuild NumPy against a Python built as UCS-4.</p>
</blockquote>
<p>I don't know how to do this. In <a href="http://stackoverflow.com/a/19575808/1391441">this other question</a> it is said that one has to use:</p>
<pre><code>./configure --enable-unicode=ucs4
</code></pre>
<p>but I don't know how to use that command along with <a href="https://github.com/yyuu/pyenv" rel="nofollow">pyenv</a>.</p>
<p>This issue is also mentioned in <code>pyenv</code>'s repo <a href="https://github.com/yyuu/pyenv/issues/518" rel="nofollow">issue list</a>, and a solution given in <a href="https://github.com/yyuu/pyenv/issues/518#issuecomment-199827456" rel="nofollow">a comment</a>. Sadly (for me) I can not understand how to apply the fix explained in said comment.</p>
<p>So my question basically is: how do I build Python as UCS-4 via <code>pyenv</code>?</p>
| 0 | 2016-08-13T03:37:24Z | 38,930,764 | <p>Installing <code>python</code> with <code>pyenv</code> with <code>ucs2</code>:</p>
<pre><code>$ export PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2
$ pyenv install -v 2.7.11
...
$ pyenv local 2.7.11
$ pyenv versions
system
* 2.7.11 (set by /home/nwani/.python-version)
$ /home/nwani/.pyenv/shims/python
Python 2.7.11 (default, Aug 13 2016, 13:42:13)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sysconfig
>>> sysconfig.get_config_vars()['CONFIG_ARGS']
"'--prefix=/home/nwani/.pyenv/versions/2.7.11' '--enable-unicode=ucs2' '--libdir=/home/nwani/.pyenv/versions/2.7.11/lib' 'LDFLAGS=-L/home/nwani/.pyenv/versions/2.7.11/lib ' 'CPPFLAGS=-I/home/nwani/.pyenv/versions/2.7.11/include '"
</code></pre>
<p>Installing <code>python</code> with <code>pyenv</code> with <code>ucs4</code>:</p>
<pre><code>$ pyenv uninstall 2.7.11
pyenv: remove /home/nwani/.pyenv/versions/2.7.11? y
$ export PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs4
$ pyenv install -v 2.7.11
...
$ pyenv local 2.7.11
$ pyenv versions
system
* 2.7.11 (set by /home/nwani/.python-version)
$ /home/nwani/.pyenv/shims/python
Python 2.7.11 (default, Aug 13 2016, 13:49:09)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sysconfig
>>> sysconfig.get_config_vars()['CONFIG_ARGS']
"'--prefix=/home/nwani/.pyenv/versions/2.7.11' '--enable-unicode=ucs4' '--libdir=/home/nwani/.pyenv/versions/2.7.11/lib' 'LDFLAGS=-L/home/nwani/.pyenv/versions/2.7.11/lib ' 'CPPFLAGS=-I/home/nwani/.pyenv/versions/2.7.11/include '"
</code></pre>
| 1 | 2016-08-13T08:23:01Z | [
"python",
"ucs2",
"pyenv",
"ucs",
"ucs-4"
] |
Installing scikits.samplerate fails | 38,928,949 | <p>I'd like to use "scikits.samplerate", but installation fails.
I'm using Windows10 (64 Bits) for Python 3.51 with Anaconda.</p>
<p>Firstly, I followed this instruction:
<a href="https://scikits.appspot.com/samplerate" rel="nofollow">https://scikits.appspot.com/samplerate</a></p>
<pre><code>>pip install scikits.samplerate Collecting scikits.samplerate Using cached scikits.samplerate-0.3.3.tar.gz
Complete output from command python setup.py egg_info:
SamplerateInfo:
libraries samplerate not found in c:\users\username\anaconda3\lib
libraries samplerate not found in C:\
libraries samplerate not found in c:\users\username\anaconda3\libs
Traceback (most recent call last):
File "scikits\samplerate\setup.py", line 15, in configuration
sf_config = sf_info.get_info(2)
File "c:\users\username\anaconda3\lib\site-packages\numpy\distutils\system_info.py", line 568, in get_info
raise self.notfounderror(self.notfounderror.__doc__)
numpy.distutils.system_info.NotFoundError: Some third-party program or library is not found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\username\AppData\Local\Temp\pip-build-9sjnkaf5\scikits.samplerate\setup.py", line 74, in <module>
classifiers = CLASSIFIERS,
File "c:\users\username\anaconda3\lib\site-packages\numpy\distutils\core.py", line 135, in setup
config = configuration()
File "C:\Users\username\AppData\Local\Temp\pip-build-9sjnkaf5\scikits.samplerate\setup.py", line 59, in configuration
config.add_subpackage(DISTNAME)
File "c:\users\username\anaconda3\lib\site-packages\numpy\distutils\misc_util.py", line 1002, in add_subpackage
caller_level = 2)
File "c:\users\username\anaconda3\lib\site-packages\numpy\distutils\misc_util.py", line 971, in get_subpackage
caller_level = caller_level + 1)
File "c:\users\username\anaconda3\lib\site-packages\numpy\distutils\misc_util.py", line 908, in _get_configuration_from_setup_py
config = setup_module.configuration(*args)
File "scikits\samplerate\setup.py", line 20, in configuration
[samplerate].""")
numpy.distutils.system_info.NotFoundError: SRC (http://www.mega-nerd.com/SRC/) library not found. Directories to search
for the libraries can be specified in the site.cfg file, in section
[samplerate].
---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\username\AppData\Local\Temp\pip-build-9sjnkaf5\scikits.samplerate\
</code></pre>
<p>... Next, I followed this instruction:
<a href="https://anaconda.org/hcc/scikits.samplerate" rel="nofollow">https://anaconda.org/hcc/scikits.samplerate</a></p>
<pre><code>>conda install -c hcc scikits.samplerate=0.3.3 Using Anaconda Cloud api site https://api.anaconda.org Fetching package metadata: ...... Solving package specifications: . Error: Package missing in current win-64 channels:
- scikits.samplerate 0.3.3*
You can search for this package on anaconda.org with
anaconda search -t conda scikits.samplerate 0.3.3*
</code></pre>
<p>... so, I serached:</p>
<pre><code>[Anaconda3] C:\Users\username>anaconda search -t conda scikitsâ² Using Anaconda Cloud api site https://api.anaconda.orgâ² Run 'anaconda show <USER/PACKAGE>' to get more details:â² Packages:â²
Name | Version | Package Types | Platformsâ²
------------------------- | ------ | --------------- | ---------------â²
HCC/scikits.samplerate | 0.3.3 | conda | linux-64â²
: A python module for high quality audio resamplingâ²
anaconda/scikits-image | 0.7.1 | conda | linux-64, win-32, win-64, linux-32, osx-64â²
davidbgonzalez/scikits.talkbox | 0.2.5 | conda | linux-64â²
desilinguist/scikits-bootstrap | 0.3.1 | conda | linux-64, osx-64â²
krisvanneste/scikits.timeseries | 0.91.3 | conda | win-64â²
lukepfister/scikits.cuda | master_2016.2 | conda | linux-64â²
: Python interface to GPU-powered librariesâ²
menpo/scikits.sparse | 0.2 | conda | linux-64, osx-64â²
miguelalexanderdiaz/scikits.cuda | 0.5.0b1 | conda | linux-64â²
: Python interface to GPU-powered librariesâ²
poppy-project/scikits.samplerate | 0.3.3 | conda | linux-armv7lâ²
: Simple Hamming Marker Detection using OpenCVâ²
rgrout/scikits.bootstrap | 0.3.2 | conda | linux-64, osx-64â²
: Bootstrap confidence interval estimation routines for SciPy.â² Found 10 packagesâ² â² [Anaconda3] C:\Users\username>anaconda show poppy-project/scikits.samplerateâ² Using Anaconda Cloud api site https://api.anaconda.orgâ² Name: scikits.samplerateâ² Summary: Simple Hamming Marker Detection using OpenCVâ² Access: publicâ² Package Types: condaâ² Versions:â² + 0.3.3â² â² To install this package with conda run:â²
conda install --channel https://conda.anaconda.org/poppy-project scikits.samplerateâ² â² [Anaconda3] C:\Users\username>conda install
--channel https://conda.anaconda.org/poppy-project scikits.samplerateâ² Using Anaconda Cloud api site https://api.anaconda.orgâ² Fetching package metadata: ......â² Solving package specifications: .â² Error: Package missing in current win-64 channels:â²
- scikits.samplerateâ² â² You can search for this package on anaconda.org withâ² â²
anaconda search -t conda scikits.samplerateâ²
</code></pre>
<p>... I have done what I was told, but still it fails.
Does anyone have a solution?
Is this really installable?</p>
| 0 | 2016-08-13T03:38:43Z | 38,929,336 | <p>I am not sure if this would work, but glad if it does. Have you tried to edit the site.cfg file and try the installation again.This is what line 20 error in your question says as well.</p>
<p>The user here has done it on Ubuntu, maybe a similar approach works for Windows as well.</p>
<p><a href="http://msnoise.org/doc/installation.html" rel="nofollow">http://msnoise.org/doc/installation.html</a></p>
<pre><code>You first need to install the SRC library:
sudo apt-get install libsamplerate0 libsamplerate0-dev
This python package will probably be the most tricky to install. If you are lucky, you can just
pip install scikits.samplerate
On my Ubuntu 12.04, this results in an error because the SRC library path is not found. The reason is that the setup searches SRC in /usr/lib and not in /usr/lib/x86_64-linux-gnu where the library is actually present. To install, you need to download the archive from pypi and edit some configuration file:
wget https://pypi.python.org/packages/source/s/scikits.samplerate/scikits.samplerate-0.3.3.tar.gz#md5=96c8d8ba3aa95a9db15994f78792efb4
tar -xvf scikits.samplerate-0.3.3.tar.gz
cd scikits.samplerate-0.3.3
then edit the site.cfg example file and insert the following lines:
[samplerate]
library_dirs=/usr/lib/x86_64-linux-gnu
include_dirs=/usr/include
To know where the SRC library is on you machine:
sudo dpkg -L libsamplerate0
sudo dpkg -L libsamplerate0-dev
then, build and install:
python setup.py build
python setup.py install
</code></pre>
| 0 | 2016-08-13T04:53:49Z | [
"python",
"install",
"anaconda",
"scikits"
] |
Python and sqlite3 data structure to store table name and columns for multiple reuse | 38,929,005 | <p>I'm using python sqlite3 api to create a database.
In all examples I saw on the documentation table names and colum names are hardcoded inside queries..but this could be a potential problem if I re-use the same table multiple times (ie, creating table, inserting records into table, reading data from table, alter table and so on...) because In case of table modification I need to change the hardcoded names in multiple places and this is not a good programming practice..
How can I solve this problem?
I thought creating a class with just constructor method in order to store all this string names..and use it inside the class that will operation on database..but as I'm not an expert python programmer I would like to share my thoughts...</p>
<pre><code>class TableA(object):
def __init__(self):
self.table_name = 'tableA'
self.name_col1 = 'first_column'
self.type_col1='INTEGER'
self.name_col2 = 'second_column'
self.type.col2 = 'TEXT'
self.name_col3 = 'third_column'
self.type_col3 = 'BLOB'
</code></pre>
<p>and then inside the DB classe</p>
<pre><code>table_A = TableA()
def insert_table(self):
conn = sqlite3.connect(self._db_name)
query = 'INSERT INTO ' + table_A.table_name + ..... <SNIP>
conn.execute(query)
</code></pre>
<p>Is this a proper way to proceed?</p>
| 0 | 2016-08-13T03:51:31Z | 38,929,114 | <p>If you are going to start using classes to provide an abstraction layer for your database tables, you might as well start using an ORM. Some examples are <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> and <a href="https://www.google.com.au/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwiLpePlwr3OAhVEkJQKHYa3DUIQFggbMAA&url=http%3A%2F%2Fwww.sqlobject.org%2F&usg=AFQjCNHkK2hl0vwT6BKzo62_YCTNLoI-0g&sig2=eYX0ekics0PS-qauqrXYQw&bvm=bv.129422649,d.dGo" rel="nofollow">SQLObject</a>, both of which are extremely popular.</p>
<p>Here's a taste of SQLAlchemy:</p>
<pre><code>from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
Base = declarative_base()
class TableA(Base):
__tablename__ = 'tableA'
id = Column(Integer, primary_key=True)
first_column = Column(Integer)
second_column = Column(String)
# etc...
engine = create_engine('sqlite:///test.db')
Base.metadata.bind = engine
session = sessionmaker(bind=engine)()
ta = TableA(first_column=123, second_column='Hi there')
session.add(ta)
session.commit()
</code></pre>
<p>Of course you would choose semantic names for the table and columns, but you can see that declaring a table is something along the lines of what you were proposing in your question, i.e. using a class. Inserting records is simplified by creating instances of that class.</p>
| 0 | 2016-08-13T04:13:14Z | [
"python",
"sqlite3"
] |
Python and sqlite3 data structure to store table name and columns for multiple reuse | 38,929,005 | <p>I'm using python sqlite3 api to create a database.
In all examples I saw on the documentation table names and colum names are hardcoded inside queries..but this could be a potential problem if I re-use the same table multiple times (ie, creating table, inserting records into table, reading data from table, alter table and so on...) because In case of table modification I need to change the hardcoded names in multiple places and this is not a good programming practice..
How can I solve this problem?
I thought creating a class with just constructor method in order to store all this string names..and use it inside the class that will operation on database..but as I'm not an expert python programmer I would like to share my thoughts...</p>
<pre><code>class TableA(object):
def __init__(self):
self.table_name = 'tableA'
self.name_col1 = 'first_column'
self.type_col1='INTEGER'
self.name_col2 = 'second_column'
self.type.col2 = 'TEXT'
self.name_col3 = 'third_column'
self.type_col3 = 'BLOB'
</code></pre>
<p>and then inside the DB classe</p>
<pre><code>table_A = TableA()
def insert_table(self):
conn = sqlite3.connect(self._db_name)
query = 'INSERT INTO ' + table_A.table_name + ..... <SNIP>
conn.execute(query)
</code></pre>
<p>Is this a proper way to proceed?</p>
| 0 | 2016-08-13T03:51:31Z | 38,929,115 | <p>I don't know what's proper but I can tell you that it's not conventional.</p>
<p>If you really want to structure tables as classes, you could consider an object relational mapper like <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>. Otherwise, the way you're going about it, how do you know how many column variables you have? What about storing a list of 2-item lists? Or a list of dictionaries?</p>
<pre><code>self.column_list = []
self.column_list.append({'name':'first','type':'integer'})
</code></pre>
<p>The way you're doing it sounds pretty novel. Check out their code and see how they do it.</p>
| 0 | 2016-08-13T04:13:30Z | [
"python",
"sqlite3"
] |
Python and sqlite3 data structure to store table name and columns for multiple reuse | 38,929,005 | <p>I'm using python sqlite3 api to create a database.
In all examples I saw on the documentation table names and colum names are hardcoded inside queries..but this could be a potential problem if I re-use the same table multiple times (ie, creating table, inserting records into table, reading data from table, alter table and so on...) because In case of table modification I need to change the hardcoded names in multiple places and this is not a good programming practice..
How can I solve this problem?
I thought creating a class with just constructor method in order to store all this string names..and use it inside the class that will operation on database..but as I'm not an expert python programmer I would like to share my thoughts...</p>
<pre><code>class TableA(object):
def __init__(self):
self.table_name = 'tableA'
self.name_col1 = 'first_column'
self.type_col1='INTEGER'
self.name_col2 = 'second_column'
self.type.col2 = 'TEXT'
self.name_col3 = 'third_column'
self.type_col3 = 'BLOB'
</code></pre>
<p>and then inside the DB classe</p>
<pre><code>table_A = TableA()
def insert_table(self):
conn = sqlite3.connect(self._db_name)
query = 'INSERT INTO ' + table_A.table_name + ..... <SNIP>
conn.execute(query)
</code></pre>
<p>Is this a proper way to proceed?</p>
| 0 | 2016-08-13T03:51:31Z | 38,929,352 | <p>I personally don't like to use libraries and frameworks without proper reason. So, if I'd such reason, so will write a thinking wrapper around <code>sqlite</code>.</p>
<pre><code>class Column(object):
def __init__(self, col_name="FOO", col_type="INTEGER"):
# standard initialization
</code></pre>
<p>And then table class that encapsulates operations with database</p>
<pre><code>class Table(object):
def __init__(self, list_of_columns, cursor):
#initialization
#create-update-delete commands
</code></pre>
<p>In table class you can encapsulate all operations with the database you want.</p>
| 0 | 2016-08-13T04:57:04Z | [
"python",
"sqlite3"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.