title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python Changing value of XML | 39,170,181 | <p>Hello im using lxml to try and change the value of a specific xml element. Here is my code.</p>
<pre><code>directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
if f.endswith(".xml"):
xmlfile = directory + '/' + f
tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()
hardwareRevisionNode = root.find(".//hardwareRevision")
if hardwareRevisionNode.text == "5":
print " "
print hardwareRevisionNode.text
str(hardwareRevisionNode.text) == "DVT3"
print hardwareRevisionNode.text
</code></pre>
<p>I want to change the 5 to a DVT3 instead it just prints it out below as 5 and 5. I referenced <a href="http://stackoverflow.com/questions/12728719/change-xml-using-python">Change xml using python</a> . Unfortunately it doesnt work for me.</p>
| 0 | 2016-08-26T15:51:29Z | 39,170,343 | <p>looks like you need assignment <code>=</code> not comparison <code>==</code> and the cast to string <code>str()</code> is unnecessary. once you've assigned the value, you'll want to write the result back out to the file:</p>
<pre><code>hardwareRevisionNode.text = "DVT3"
outfile = open(xmlfile, 'w')
oufile.write(etree.tostring(tree))
outfile.close()
</code></pre>
<p>good luck!</p>
| 2 | 2016-08-26T16:00:04Z | [
"python",
"xml",
"lxml"
] |
How to make a portion of a Kivy screen scrollable | 39,170,283 | <p>I'm looking to make a page in Python using the Kivy library of the following format</p>
<pre><code> ________________________
| |
| title |
|______________________|
>>| Example 1 |<<
|______________________|
| | |
|___________|__________|
| | |
|___________|__________|
| | |
>>|___________|__________|<<
| Home |
|______________________|
| Settings |
|______________________|
</code></pre>
<p>The portion of the screen between the arrows should be scrollable. The code I have for this so far is as follows:</p>
<p>Kv file:</p>
<pre><code><ExampleScreen>:
BoxLayout:
orientation: 'vertical'
Label:
text: 'title'
ScrollView:
GridLayout:
cols: 1
Label:
text: 'Example 1'
GridLayout:
cols: 2
rows: 4
Label:
text: 'Filler'
Label:
text: 'Filler'
Label:
text: 'Filler'
Label:
text: 'Filler'
Label:
text: 'Filler'
Label:
text: 'Filler'
Label:
text: 'Filler'
Label:
text: 'Filler'
Button:
text: 'Home'
size_hint: 1, .1
on_press: root.manager.current = 'home'
Button:
text: 'Settings'
size_hint: 1, .1
on_press: root.manager.current = 'settings'
</code></pre>
<p>Py file:</p>
<pre><code>from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.lang import Builder
Builder.load_file('example.kv')
class ExampleScreen(Screen):
pass
sm = ScreenManager()
sm.add_widget(ExampleScreen(name = 'example'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
</code></pre>
<p>I've tried implementing this several ways and nothing has worked. Does anyone else have experience with this/know if this is possible? Thanks for your help!</p>
| 1 | 2016-08-26T15:57:13Z | 39,176,727 | <p>Yes it is possible, if you get the indentation and size hints right.<br>
<a href="https://kivy.org/docs/api-kivy.uix.scrollview.html" rel="nofollow">ScrollView doc</a> </p>
<p>Try this: </p>
<pre><code><MyLabel@Label>:
size_hint:1,None
<ExampleScreen>:
BoxLayout:
orientation: 'vertical'
Label:
text: 'title'
ScrollView:
size_hint: 1,None
GridLayout:
size_hint: 1,None
height: self.minimum_height
cols: 1
MyLabel:
text: 'Example 1'
GridLayout:
size_hint: 1,None
height: self.minimum_height
cols: 2
rows: 4
MyLabel:
text: 'Filler'
MyLabel:
text: 'Filler'
MyLabel:
text: 'Filler'
MyLabel:
text: 'Filler'
MyLabel:
text: 'Filler'
MyLabel:
text: 'Filler'
MyLabel:
text: 'Filler'
MyLabel:
text: 'Filler'
Button:
text: 'Home'
size_hint: 1, .1
on_press: root.manager.current = 'home'
Button:
text: 'Settings'
size_hint: 1, .1
on_press: root.manager.current = 'settings'
</code></pre>
| 0 | 2016-08-27T01:52:55Z | [
"python",
"kivy",
"kivy-language"
] |
Python Simon Game: I Cannot Make the Command of the Button Work the Way I Need | 39,170,407 | <p>I am working on a Simon Game in Python using Tkinter and I am having problems making work the command of the button.</p>
<p>For the game the activebackground of the button must change from the normal color to another color when clicked and then return to the normal color and I must be able to repeat the action for an indefinite amount of clicks.</p>
<p>The necessary code for this is:</p>
<pre><code>import Tkinter
base = Tkinter.Tk()
fr = Tkinter.Frame(base, bg="black", width="238", height="238")
def yellowClick():
yellow.configure(activebackground="yellow3")
yellow = Tkinter.Button(base, bd="0", highlightthickness="0",
width="7", height="5", activebackground="yellow",
bg="yellow3", command = yellowClick)
yellow.place(x = 30, y = 30)
fr.pack()
base.mainloop()
</code></pre>
<p>Here the actual code in the yellowClick() function makes the activebackground of the button to properly change color to yellow3, but I don't know how to return it after 3 seconds to yellow, and then be able to repeat the action for an indefinite amount of clicks.</p>
<p>I tried with time.sleep() in this way:</p>
<pre><code>def yellowClick():
yellow.configure(activebackground="yellow3")
time.sleep(3)
yellow.configure(activebackground="yellow")
</code></pre>
<p>But it only makes the button to turn yellow and last 3 seconds. Instead of turning yellow3, wait 3 seconds and then return to yellow.</p>
<p>Any help is welcome.</p>
| 1 | 2016-08-26T16:03:43Z | 39,170,502 | <pre><code>import Tkinter
import time
base = Tkinter.Tk()
fr = Tkinter.Frame(base, bg="black", width="238", height="238")
def yellowClick():
yellow.configure(activebackground="yellow")
time.sleep(3)
yellow.configure(activebackground="yellow3")
yellow = Tkinter.Button(base, bd="0", highlightthickness="0",
width="7", height="5", activebackground="yellow",
bg="yellow3", command = yellowClick)
yellow.place(x = 30, y = 30)
fr.pack()
base.mainloop()
</code></pre>
<p>This works for me. What's the result on your machine?</p>
| 0 | 2016-08-26T16:09:52Z | [
"python",
"tkinter"
] |
Python Simon Game: I Cannot Make the Command of the Button Work the Way I Need | 39,170,407 | <p>I am working on a Simon Game in Python using Tkinter and I am having problems making work the command of the button.</p>
<p>For the game the activebackground of the button must change from the normal color to another color when clicked and then return to the normal color and I must be able to repeat the action for an indefinite amount of clicks.</p>
<p>The necessary code for this is:</p>
<pre><code>import Tkinter
base = Tkinter.Tk()
fr = Tkinter.Frame(base, bg="black", width="238", height="238")
def yellowClick():
yellow.configure(activebackground="yellow3")
yellow = Tkinter.Button(base, bd="0", highlightthickness="0",
width="7", height="5", activebackground="yellow",
bg="yellow3", command = yellowClick)
yellow.place(x = 30, y = 30)
fr.pack()
base.mainloop()
</code></pre>
<p>Here the actual code in the yellowClick() function makes the activebackground of the button to properly change color to yellow3, but I don't know how to return it after 3 seconds to yellow, and then be able to repeat the action for an indefinite amount of clicks.</p>
<p>I tried with time.sleep() in this way:</p>
<pre><code>def yellowClick():
yellow.configure(activebackground="yellow3")
time.sleep(3)
yellow.configure(activebackground="yellow")
</code></pre>
<p>But it only makes the button to turn yellow and last 3 seconds. Instead of turning yellow3, wait 3 seconds and then return to yellow.</p>
<p>Any help is welcome.</p>
| 1 | 2016-08-26T16:03:43Z | 39,170,851 | <blockquote>
<p>but I don't know how to return it after 3 seconds to yellow,</p>
</blockquote>
<p>Tkinter widgets have a method named <code>after</code> for precisely this sort of thing. If you want to change it to a different color in three seconds you can do this:</p>
<pre><code> yellow.configure(activebackground="yellow3")
yellow.after(3000, lambda: yellow.configure(activebackground="yellow"))
</code></pre>
<p>This creates an anonymous function that will run approximately three seconds (3000 milliseconds) in the future. </p>
| 2 | 2016-08-26T16:29:39Z | [
"python",
"tkinter"
] |
Seaborn clustermap within subplot | 39,170,455 | <p>I am trying to plot clustermap and box plots for a dataframe as subplots. I am having trouble plotting the clustermap as subplot as it is a figure level plot. Is there a way to achieve this?</p>
<pre><code>import pandas as pd
import seaborn as sns
# initiliaze a dataframe with index and column names
idf = pd.DataFrame.from_items([('A', [1, 2, 3]),
('B', [4, 5, 6]),
('C', [10, 20, 30]),
('D', [14, 15, 16])],
orient='index', columns=['x', 'y','z'])
# Get the figure and two subplots, unpack the axes array immediately
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
# Plot a boxplot in one of the subplot
idf.plot(kind='box', ax=ax1)
# Plot the clustermap in the other subplot
cax = sns.clustermap(idf, col_cluster=False, row_cluster=True)
# I tried to change the axis from the clustermap to subplot axis
# but I don't think this works like this
cax.ax_heatmap=ax2
# Show the plot
plt.show()
</code></pre>
<p>What I am getting right now:</p>
<p>Image 1:</p>
<p><a href="http://i.stack.imgur.com/Czy1Y.png" rel="nofollow"><img src="http://i.stack.imgur.com/Czy1Y.png" alt="enter image description here"></a></p>
<hr>
<p>Image 2:
<a href="http://i.stack.imgur.com/csBOv.png" rel="nofollow"><img src="http://i.stack.imgur.com/csBOv.png" alt="enter image description here"></a></p>
<p>What I need is something like this:</p>
<p><a href="http://i.stack.imgur.com/l1jNM.png" rel="nofollow"><img src="http://i.stack.imgur.com/l1jNM.png" alt="enter image description here"></a></p>
<p>Thanks.</p>
| 1 | 2016-08-26T16:06:42Z | 39,170,714 | <p>You should pass the ax as argument of the clustermap function:</p>
<pre><code>cax = sns.clustermap(idf, col_cluster=False, row_cluster=True, ax = ax2)
</code></pre>
<p>As you can see from the documentation of the function clustermap (<a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.clustermap.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.clustermap.html</a>), the actual function doing the plot is heatmap <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html</a> which accept the ax as parameter.</p>
| -2 | 2016-08-26T16:21:37Z | [
"python",
"matplotlib",
"heatmap",
"seaborn"
] |
Seaborn clustermap within subplot | 39,170,455 | <p>I am trying to plot clustermap and box plots for a dataframe as subplots. I am having trouble plotting the clustermap as subplot as it is a figure level plot. Is there a way to achieve this?</p>
<pre><code>import pandas as pd
import seaborn as sns
# initiliaze a dataframe with index and column names
idf = pd.DataFrame.from_items([('A', [1, 2, 3]),
('B', [4, 5, 6]),
('C', [10, 20, 30]),
('D', [14, 15, 16])],
orient='index', columns=['x', 'y','z'])
# Get the figure and two subplots, unpack the axes array immediately
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
# Plot a boxplot in one of the subplot
idf.plot(kind='box', ax=ax1)
# Plot the clustermap in the other subplot
cax = sns.clustermap(idf, col_cluster=False, row_cluster=True)
# I tried to change the axis from the clustermap to subplot axis
# but I don't think this works like this
cax.ax_heatmap=ax2
# Show the plot
plt.show()
</code></pre>
<p>What I am getting right now:</p>
<p>Image 1:</p>
<p><a href="http://i.stack.imgur.com/Czy1Y.png" rel="nofollow"><img src="http://i.stack.imgur.com/Czy1Y.png" alt="enter image description here"></a></p>
<hr>
<p>Image 2:
<a href="http://i.stack.imgur.com/csBOv.png" rel="nofollow"><img src="http://i.stack.imgur.com/csBOv.png" alt="enter image description here"></a></p>
<p>What I need is something like this:</p>
<p><a href="http://i.stack.imgur.com/l1jNM.png" rel="nofollow"><img src="http://i.stack.imgur.com/l1jNM.png" alt="enter image description here"></a></p>
<p>Thanks.</p>
| 1 | 2016-08-26T16:06:42Z | 39,173,061 | <p>From @mwaskom 's comment, I read more into the clustermap figure function and realized that I can just replace the column dendrogram image with the boxplot image. However, I would try to find how to add another axis instead of replacing the column dendrogram axis just in case I need to show both row and column dendrograms with the box plot. But what I got so far is fine with me. Here is the code:</p>
<pre><code>import pandas as pd
import seaborn as sns
# initiliaze a dataframe with index and column names
idf = pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6]), ('C', [10, 20, 30]), ('D', [14, 15, 16])], orient='index', columns=['x', 'y', 'z'])
# Plot the clustermap which will be a figure by itself
cax = sns.clustermap(idf, col_cluster=False, row_cluster=True)
# Get the column dendrogram axis
cax_col_dend_ax = cax.ax_col_dendrogram.axes
# Plot the boxplot on the column dendrogram axis
# I still need to figure out how to show the axis for this boxplot
idf.plot(kind='box', ax=cax_col_dend_ax)
# Show the plot
plt.show()
</code></pre>
<p>This results in:</p>
<p><a href="http://i.stack.imgur.com/maivA.png" rel="nofollow"><img src="http://i.stack.imgur.com/maivA.png" alt="enter image description here"></a></p>
| 0 | 2016-08-26T18:58:10Z | [
"python",
"matplotlib",
"heatmap",
"seaborn"
] |
Use CharField as a string | 39,170,580 | <p>I want to create a model where I just put in two fields and the rest is generated with API requests, the generation I've got but I can't get the CharField in a usable string format.
So on field is:</p>
<pre><code>name = models.CharField(max_length=250, default='default')
</code></pre>
<p>And I want to run it through:</p>
<pre><code>name = self.name.replace(' ', '+')
movieData = (json.loads(str(urllib2.urlopen('http://www.omdbapi.com/?t=' + name + '&y=&plot=short&r=json').read(),'utf-8')))
movieYear = movieData.get('Year')
</code></pre>
<p>Saving movieYear as a field.
Thanks in advance</p>
| 1 | 2016-08-26T16:14:14Z | 39,171,582 | <p>I think a custom <code>save</code> will help you accomplish what you are looking to do. Here's an example:</p>
<pre><code>class MyModel(models.Model):
name = models.CharField(max_length=250, default='default')
movieData = models.JSONField(blank=True)
movieYear = models.CharField(max_length=250, blank=True)
def save(self, *args, **kwargs):
url = 'http://www.omdbapi.com/?t={}&y=&plot=short&r=json'.format(self.name.replace(' ', '+'))
data = json.loads(str(urllib2.urlopen(url).read(),'utf-8'))
self.movieData = data
self.movieYear = data['Year']
super(MyModel, self).save(*args, **kwargs)
</code></pre>
<p>This will let you make a request to a URL crafted from the <code>self.name</code> attribute (replacing spaces with <code>+</code>), then store the response in the fields you wanted. </p>
<p>If you use this solution, you will want to take care to include some kind of error handling - what happens if an invalid name is supplied? Or the returned data doesn't have a <code>Year</code> key for some reason? Or maybe the API is just down for a few minutes, so your valid request receives no response? </p>
<p>This will also make a request to that API on every save, which may have consequences for the speed of your application. You can force logic in a custom <code>save</code> to execute only when creating a new instance by using <code>if self.pk is None</code>.</p>
| 0 | 2016-08-26T17:17:31Z | [
"python",
"json",
"django",
"web"
] |
Convert complex roots into standard float form without affecting quality of result | 39,170,624 | <p>I have a transformed stress tensor, its principle values are coming in complex form:</p>
<pre><code>#simple roots calculated by characteristic equation
def princ_cherac(sten):
sxx,syy,szz,sxy,syz,szx = sten
H1 = (sxx+syy+szz)/3.
H2 = (syz**2 + szx**2 + sxy**2 - syy*szz - szz*sxx - sxx-syy)/3.
H3 = ( 2*syz*szx*sxy + sxx*syy*szz - sxx*syz*syz - syy*szx*szx - szz*sxy*sxy )/2.
from numpy.polynomial import Polynomial as P
p = P([2*H3,3*H2,3*H1,-1])
S3,S2,S1 = p.roots()
</code></pre>
<p>but it produces complex roots. For my further calculations, the complex form cannot work. How can I convert from the complex form while not losing any information on the results, for example, <code>S3 =-32.894653311352783-28.288180652364915j</code>; how to change it so that the answer represents it but in normal float-like form?</p>
| -1 | 2016-08-26T16:16:09Z | 39,171,366 | <p>There is a mistake in your implementation of <code>H2</code>. You have the last term as <code>sxx-syy</code>, but that should be <code>sxx*syy</code>.</p>
<p>By the way, you'll likely get more accurate results by using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigvalsh.html" rel="nofollow"><code>numpy.linalg.eigvalsh</code></a> to find the values. For example, here's a full 3x3 tensor; <code>coeffs</code> are the values to be passed to <code>princ_cherac</code>:</p>
<pre><code>In [200]: tensor = np.array([[2, 1, 1], [1, 2, 1], [1, 1, 2]])
In [201]: coeffs = tensor.ravel()[[0, 4, 8, 1, 5, 2]]
In [202]: tensor
Out[202]:
array([[2, 1, 1],
[1, 2, 1],
[1, 1, 2]])
In [203]: coeffs
Out[203]: array([2, 2, 2, 1, 1, 1])
</code></pre>
<p>Compute the values using <code>eigvalsh</code>.</p>
<pre><code>In [204]: np.linalg.eigvalsh(tensor)
Out[204]: array([ 1., 1., 4.])
</code></pre>
<p>Compare that to the values produced by the corrected <code>princ_cherac</code>:</p>
<pre><code>In [205]: princ_cherac(coeffs)
Out[205]: (0.9999999619754828, 1.0000000380245182, 4.0)
</code></pre>
| 3 | 2016-08-26T17:03:25Z | [
"python",
"numpy",
"scipy"
] |
how to match two dataFrame in python | 39,170,651 | <p>I have two dataFrame in Python.
The first one is df1:</p>
<pre><code>'ID' 'B'
AA 10
BB 20
CC 30
DD 40
</code></pre>
<p>The second one is df2:</p>
<pre><code> 'ID' 'C' 'D'
BB 30 0
DD 35 0
</code></pre>
<p>What I want to get finally is like df3:</p>
<pre><code>'ID' 'C' 'D'
BB 30 20
DD 35 40
</code></pre>
<p>how to reach this goal?
my code is:</p>
<pre><code>for i in df.ID
if len(df2.ID[df2.ID==i]):
df2.D[df2.ID==i]=df1.B[df2.ID==i]
</code></pre>
<p>but it doesn't work.</p>
| 1 | 2016-08-26T16:17:31Z | 39,171,009 | <p>Following code will replace zero in df1 with value df2</p>
<pre><code>df1=pd.DataFrame(['A','B',0,4,6],columns=['x'])
df2=pd.DataFrame(['A','X',3,0,5],columns=['x'])
df3=df1[df1!=0].fillna(df2)
</code></pre>
| 0 | 2016-08-26T16:40:47Z | [
"python",
"dataframe"
] |
how to match two dataFrame in python | 39,170,651 | <p>I have two dataFrame in Python.
The first one is df1:</p>
<pre><code>'ID' 'B'
AA 10
BB 20
CC 30
DD 40
</code></pre>
<p>The second one is df2:</p>
<pre><code> 'ID' 'C' 'D'
BB 30 0
DD 35 0
</code></pre>
<p>What I want to get finally is like df3:</p>
<pre><code>'ID' 'C' 'D'
BB 30 20
DD 35 40
</code></pre>
<p>how to reach this goal?
my code is:</p>
<pre><code>for i in df.ID
if len(df2.ID[df2.ID==i]):
df2.D[df2.ID==i]=df1.B[df2.ID==i]
</code></pre>
<p>but it doesn't work.</p>
| 1 | 2016-08-26T16:17:31Z | 39,171,884 | <p>So first of all, I've interpreted the question differently, since your description is rather ambiguous. Mine boils down to this:</p>
<p>df1 is this data structure:</p>
<pre><code>ID B <- column names
AA 10
BB 20
CC 30
DD 40
</code></pre>
<p>df2 is this data structure:</p>
<pre><code>ID C D <- column names
BB 30 0
DD 35 0
</code></pre>
<p>Dataframes have a merge option, if you wanted to merge based on index the following code would work:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame(
[
['AA', 10],
['BB', 20],
['CC', 30],
['DD', 40],
],
columns=['ID','B'],
)
df2 = pd.DataFrame(
[
['BB', 30, 0],
['DD', 35, 0],
], columns=['ID', 'C', 'D']
)
df3 = pd.merge(df1, df2, on='ID')
</code></pre>
<p>Now df3 only contains rows with ID's in both df1 and df2:</p>
<pre><code>ID B C D <- column names
BB 20 30 0
DD 40 35 0
</code></pre>
<p>Now you were trying to remove D, and fill it in with column B, a.k.a</p>
<pre><code>ID C D
BB 30 20
DD 35 40
</code></pre>
<p>Something that can be done with these simple steps:</p>
<pre><code>df3 = pd.merge(df1, df2, on='ID') # merge them
df3.D = df3['B'] # set D to B's values
del df3['B'] # remove B from df3
</code></pre>
<p>Or to summarize:</p>
<pre><code>def match(df1, df2):
df3 = pd.merge(df1, df2, on='ID') # merge them
df3.D = df3['B'] # set D to B's values
del df3['B'] # remove B from df3
return df3
</code></pre>
| 0 | 2016-08-26T17:38:11Z | [
"python",
"dataframe"
] |
Finding twin primes in a list and recording the order they appear in | 39,170,731 | <p>I am working on a program right now that has the goal of analyzing twin primes in a certain way(twin primes are primes in the form of(p,p+2)). Right now I have a code that counts the twin primes remainders in % 10 form. </p>
<p>This is that code:</p>
<pre><code>def twin_prime_counter_type10(n):
not_prime = []
prime = []
A = range(n + 1)
B = range(n + 1)
for i in xrange(2, n+1):
if i not in not_prime:
prime.append(i)
for j in xrange(i*i, n+1, i):
not_prime.append(j)
for n,i in enumerate(prime):
if not A[n] == prime[n]:
A[i] = 1
count1_3 = 0
count7_9 = 0
count9_1 = 0
for i in B:
if B[i] % 10 == 3 and B[i - 2] % 10 == 1:
if A[i] * A[i-2] == 1:
count1_3 += 1
elif B[i] % 10 == 9 and B[i - 2] % 10 == 7:
if A[i] * A[i-2] == 1:
count7_9 += 1
elif B[i] % 10 == 1 and B[i - 2] % 10 == 9:
if A[i] * A[i-2] == 1:
count9_1 += 1
print count1_3
print count7_9
print count9_1
</code></pre>
<p>print sieve(10000)</p>
<p>This part of the code works fine but I was wondering if anyone knows of a way that when I am finding the pairs of (1)'s(the twin primes) I could also record the order they appear in the list. I don't need anyone to actually write the code that does this, I am just asking if anyone knows of a built in tool in python that I could use to preform this task.</p>
<p>Thanks for the help. </p>
| 2 | 2016-08-26T16:22:34Z | 39,301,617 | <p>assuming that <code>sieve</code> is the <a href="http://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python">Sieve of Eratosthenes</a>, or <a href="http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python">similar</a>, then you can use the <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow"><code>pairwise</code></a> recipe in the <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow">itertools</a> module to obtain only the twin primes with a generator expression </p>
<pre><code>from itertools import tee #, izip # <-- for python 2
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b) #izip(a, b) # <-- for python 2
def twin_primes(n):
return ( (p1,p2) for p1,p2 in pairwise(sieve(n)) if p1+2 == p2 )
# or use list comprehension, but I prefer generator as they use
# less memory and can be infinite, as sieve can be made to be
# infinite as well
</code></pre>
<p>for example</p>
<pre><code>>>> print( list(twin_primes(100)) )
[(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61), (71, 73)]
>>>
</code></pre>
<p>likewise you can use it alongside enumerate to get the index of the first prime in the pair in relation to a list of primes, for example</p>
<pre><code>>>> primes=list(sieve(100))
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> twins=[ (i,pair) for i,pair in enumerate( pairwise(primes) ) if pair[0]+2 == pair[1] ]
>>> twins
[(1, (3, 5)), (2, (5, 7)), (4, (11, 13)), (6, (17, 19)), (9, (29, 31)), (12, (41, 43)), (16, (59, 61)), (19, (71, 73))]
>>> primes[1]
3
>>> primes[4]
11
>>> primes[9]
29
>>>
</code></pre>
| -1 | 2016-09-02T22:52:23Z | [
"python"
] |
Python ElementTree won't update new file after parsing | 39,170,748 | <p>Using <code>ElementTree</code> to parse attribute's value in an <strong>XML</strong> and writing a new <strong>XML</strong> file. It will console the new updated value and write a new file. But won't update any changes in the new file. Please help me understand what I am doing wrong. Here is <strong>XML</strong> & <strong>Python</strong> code:</p>
<p><strong>XML</strong></p>
<pre><code><?xml version="1.0"?>
<!--
-->
<req action="get" msg="1" rank="1" rnklst="1" runuf="0" status="1" subtype="list" type="60" univ="IL" version="fhf.12.000.00" lang="ENU" chunklimit="1000" Times="1">
<flds>
<f i="bond(long) hff" aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fgg" start="2016-02-29"/>
<f i="bond(short) ggg" aggregationtype="WeightedAverage" end="2016-02-29" freq="m" sid="fhf" start="2016-02-29"/>
</flds>
<dat>
<r i="hello" CalculationType="3" Calculate="1" />
</dat>
</req>
</code></pre>
<p><strong>Python</strong></p>
<pre><code>import xml.etree.ElementTree as ET
with open('test.xml', 'rt') as f:
tree = ET.parse(f)
for node in tree.iter('r'):
port_id = node.attrib.get('i')
new_port_id = port_id.replace(port_id, "new")
print node
tree.write('./new_test.xml')
</code></pre>
| 1 | 2016-08-26T16:23:31Z | 39,170,960 | <p>When you get the attribute <code>i</code>, and assign it to <code>port_id</code>, you just have a regular Python string. Calling replace on it is just the Python string <code>.replace()</code> method. </p>
<p>You want to use the <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set" rel="nofollow"><code>.set()</code></a> method of the etree node:</p>
<pre><code>for node in tree.iter('r'):
node.set('i', "new")
print node
</code></pre>
| 1 | 2016-08-26T16:37:12Z | [
"python",
"xml",
"xml-parsing",
"elementtree"
] |
Transpostion decryption is not working with some keys? | 39,170,837 | <p>Why is this transposition decryption code not working with some keys?</p>
<pre><code>def transencrypt(word,key):
'''Traspositon encryption function. This function is used to encrypt a line
using the transposition encryption method. To know how transpositon encryption
works you can visit here https://en.wikipedia.org/wiki/Transposition_cipher.'''
count1=0
count2=0
encrypted=''
encryptbox=['']*key
while count1<key:
count2=count1
while count2<len(word):
encryptbox[count1]+=word[count2]
count2+=key
encrypted+=encryptbox[count1]
count1+=1
return encrypted
def transdecrypt(word,key):
'''This Function is for the decrypting the encrypted strings encrypted by
transencrypt().This function only requires the encrypted string and the key
with which it has been decrypted.'''
import math
count1=0
count2=0
decrypted=''
col=int(math.ceil(len(word)/key))
decryptbox=['']*col
while count1<col:
count2=count1
while count2<len(word):
decryptbox[count1]+=word[count2]
count2+=col
decrypted+=decryptbox[count1]
count1+=1
return decrypted
print(transencrypt('hello world',5))
print(transdecrypt('h dewlolrol',5))
</code></pre>
<p><a href="http://pastebin.com/dfx2EWE6" rel="nofollow">OP's original code source</a></p>
<p>I have tried encrypting "hello world" with key 5, but at the time of decrypting I am getting the wrong result. Using other keys works fine.</p>
| 0 | 2016-08-26T16:28:30Z | 39,173,388 | <p>The problem is that the string length (11) doesn't divide evenly into the key (5), so the string <code>"hello world"</code> encodes into the groups <code>h d-ew-lo-lr-ol</code> i.e. <code>"h dewlolrol"</code>. Which is fine, but the decrypt routine chops <code>"h dewlolrol"</code> into <code>h d-ewl-olr-ol</code> and generates the wrong result, <code>"heoo wlldlr"</code>.</p>
<p>A couple of possible ways to fix this:</p>
<p>1) Replace the <code>encryptbox</code> string with an array and pad the encryption units into even width segments: <code>h d-ew -lo -lr -ol</code> i.e. <code>"h dew lo lr ol "</code></p>
<p>This will allow your decrypt routine to work but you'll end up with spaces at the end of the decryption and the encrypted string will be a different size than the original.</p>
<p><strong>OR</strong></p>
<p>2) Dynamically adjust your decryption logic to figure out, based on the length of the remaining string to decode, and remaining number of expected segments, how much the segments must shrink. This means your decrypt routine can't be as similar to the encrypt routine as it is now. But it will allow you to handle the output of the current encrypt routine and the encrypted string can remain the same length as the original.</p>
<p>Below is a rough rework along the lines of approach #2 above -- you can see it allows the encrypt routine to remain simple but the decrypt routine has to be more complex to make up for it:</p>
<pre><code>import math
def transencrypt(string, key):
'''
Transpositon encryption function. This function is used to encrypt a line
using the transposition encryption method. To learn how transpositon encryption
works you can visit here https://en.wikipedia.org/wiki/Transposition_cipher.
'''
encrypted = ''
length = len(string)
for start in range(key):
for offset in range(start, length, key):
encrypted += string[offset]
return encrypted
def transdecrypt(string, key):
'''
This function is for the decrypting the strings encrypted by
transencrypt(). This function only requires the encrypted
string and the key with which it was decrypted.
'''
decrypted = ''
length = len(string)
width = int(math.ceil(length / key))
for start in range(width):
offset = start
remaining_key = key
remaining_length = length
remaining_width = width
while offset < length:
decrypted += string[offset]
offset += remaining_width
remaining_key -= 1
if remaining_key > 0:
remaining_length -= remaining_width
remaining_width = int(math.ceil(remaining_length / remaining_key))
return decrypted[:length]
if __name__ == '__main__':
import sys
string = sys.argv[1]
key = int(sys.argv[2])
print(transencrypt(string, key))
print(transdecrypt(transencrypt(string, key), key))
</code></pre>
<p>**OUTPUT*</p>
<pre><code>> python3 test.py "hello world" 5
h dewlolrol
hello world
>
</code></pre>
| 0 | 2016-08-26T19:21:57Z | [
"python",
"python-3.x",
"encryption"
] |
foreign keys for specific primary key django forms | 39,170,841 | <p>I have class Company, Driver and Car</p>
<pre><code>class Company(models.Model):
title = models.CharField(max_length=256)
...
Class Car(models.Model):
...
company = ForeignKey('Company')
class Driver(models.Model):
...
company = ForeignKey('Company')
company_car = OneToOneField('Car')
</code></pre>
<p>Also I have GenericView for Create and Update driver, and generic form.</p>
<p>I need form where when user select the company, company_car dropdown consist only Foreign Keys car objects for this company. I know about object_set feature and that`s trick possible with AJAX. But I have no idea how it realize</p>
| 1 | 2016-08-26T16:28:46Z | 39,171,612 | <p>On your form field, you can specify a query set for the ModelChoiceField. You haven't given your form, but it could look something like this:</p>
<pre><code>class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
self.fields['car'] = ModelChoiceField(
queryset = Car.objects.filter(company=company)
)
</code></pre>
<p>Documentation is here: <a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield</a></p>
| 0 | 2016-08-26T17:19:38Z | [
"python",
"ajax",
"django",
"django-forms"
] |
Print all matching JSON dictionaries in Python | 39,170,917 | <p>I am currently using the AWS Boto3 to try to get a list of all of my current running EC2 instances. I am at the point where I am able to use describe_instances to list all of my instances, but I am trying to figure out how to pull out all of the instance ID's so I can print them AND use them for another part of the script. Ultimately, I have one script that spins up all of the instance, next I want one that tears them all down. </p>
<p>JSON Tree bellow.</p>
<p>To select a specifc one, I have to do this, </p>
<pre><code>instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
</code></pre>
<p>But I want to be able to select all instances, regardless of how many instances I have, so trying to do [0][1] etc isn't feasable, so not sure how I would go about saying I want every InstanceId that is in the command.</p>
<pre><code>{
u'Reservations': [
{
u'Groups': [
],
u'Instances': [
{
u'AmiLaunchIndex': 0,
u'Architecture': 'i386',
u'EbsOptimized': False,
u'Hypervisor': 'xen',
u'InstanceId': 'i-6fb4ad61',
}
],
u'OwnerId': '',
u'ReservationId': ''
},
{
u'Groups': [
],
u'Instances': [
{
u'AmiLaunchIndex': 0,
u'Architecture': 'i386',
u'EbsOptimized': False,
u'Hypervisor': 'xen',
u'InstanceId': 'i-afe3faa1',
}
],
u'OwnerId': '',
u'ReservationId': ''
}
],
'ResponseMetadata': {
'HTTPHeaders': {
'content-type': 'text/xml;charset=UTF-8',
'date': 'Thu, 25Aug201623: 44: 09GMT',
'server': 'AmazonEC2',
'transfer-encoding': 'chunked',
'vary': 'Accept-Encoding'
},
'HTTPStatusCode': 200,
'RequestId': ''
}
}
</code></pre>
<p>Here is the command I am using to get the instance ID.</p>
<pre><code>launch_instance = ec2.create_instances(ImageId="xxxxxx", MinCount=1, MaxCount=1,SecurityGroupIds=["sg-xxxxxxx"],InstanceType='m3.medium', SubnetId='subnet-xxxxx')
response = ec2client.describe_instances(
InstanceIds=[
launch_instance[0].id],
)
instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
print instance_id
</code></pre>
<p>output is i-6fb4ad61</p>
| 2 | 2016-08-26T16:34:30Z | 39,170,991 | <p>You may achieve is via:</p>
<pre><code>>>> instance_ids = [instance['InstanceId'] for reservations in response['Reservations'] for instance in reservations['Instances']]
>>> instance_ids
['i-6fb4ad61', 'i-afe3faa1']
</code></pre>
<p>where your <code>JSON</code> structure is saved as <code>response</code></p>
| 2 | 2016-08-26T16:39:58Z | [
"python",
"json",
"amazon-web-services",
"amazon-ec2",
"boto3"
] |
Print all matching JSON dictionaries in Python | 39,170,917 | <p>I am currently using the AWS Boto3 to try to get a list of all of my current running EC2 instances. I am at the point where I am able to use describe_instances to list all of my instances, but I am trying to figure out how to pull out all of the instance ID's so I can print them AND use them for another part of the script. Ultimately, I have one script that spins up all of the instance, next I want one that tears them all down. </p>
<p>JSON Tree bellow.</p>
<p>To select a specifc one, I have to do this, </p>
<pre><code>instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
</code></pre>
<p>But I want to be able to select all instances, regardless of how many instances I have, so trying to do [0][1] etc isn't feasable, so not sure how I would go about saying I want every InstanceId that is in the command.</p>
<pre><code>{
u'Reservations': [
{
u'Groups': [
],
u'Instances': [
{
u'AmiLaunchIndex': 0,
u'Architecture': 'i386',
u'EbsOptimized': False,
u'Hypervisor': 'xen',
u'InstanceId': 'i-6fb4ad61',
}
],
u'OwnerId': '',
u'ReservationId': ''
},
{
u'Groups': [
],
u'Instances': [
{
u'AmiLaunchIndex': 0,
u'Architecture': 'i386',
u'EbsOptimized': False,
u'Hypervisor': 'xen',
u'InstanceId': 'i-afe3faa1',
}
],
u'OwnerId': '',
u'ReservationId': ''
}
],
'ResponseMetadata': {
'HTTPHeaders': {
'content-type': 'text/xml;charset=UTF-8',
'date': 'Thu, 25Aug201623: 44: 09GMT',
'server': 'AmazonEC2',
'transfer-encoding': 'chunked',
'vary': 'Accept-Encoding'
},
'HTTPStatusCode': 200,
'RequestId': ''
}
}
</code></pre>
<p>Here is the command I am using to get the instance ID.</p>
<pre><code>launch_instance = ec2.create_instances(ImageId="xxxxxx", MinCount=1, MaxCount=1,SecurityGroupIds=["sg-xxxxxxx"],InstanceType='m3.medium', SubnetId='subnet-xxxxx')
response = ec2client.describe_instances(
InstanceIds=[
launch_instance[0].id],
)
instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
print instance_id
</code></pre>
<p>output is i-6fb4ad61</p>
| 2 | 2016-08-26T16:34:30Z | 39,170,998 | <p>Try this</p>
<pre><code>instance_ids = []
for reservations in response['Reservations']:
for instance in reservations['Instances']:
instance_ids.append(instance['InstanceId'])
</code></pre>
| 2 | 2016-08-26T16:40:15Z | [
"python",
"json",
"amazon-web-services",
"amazon-ec2",
"boto3"
] |
regexp_tokenize and Arabic text | 39,170,944 | <p>I'm using <a href="http://www.nltk.org/_modules/nltk/tokenize/regexp.html" rel="nofollow"><code>regexp_tokenize()</code></a> to return tokens from an Arabic text without any punctuation marks:</p>
<pre><code>import re,string,sys
from nltk.tokenize import regexp_tokenize
def PreProcess_text(Input):
tokens=regexp_tokenize(Input, r'[ØØ!.Ø]\s*', gaps=True)
return tokens
H = raw_input('H:')
Cleand= PreProcess_text(H)
print '\n'.join(Cleand)
</code></pre>
<p>It worked fine, but the problem is when I try to print the text.</p>
<p>The output for the text <code>اÙÙ
Ø§ÙØØ³Ø¹Ø¯</code>:</p>
<pre><code> ?ÙÙ
?Ù
?
?
?
</code></pre>
<p>but if the text is in English, even with an Arabic punctuation marks, it prints the right result.</p>
<p>The output for the text <code>hiØeman</code>:</p>
<pre><code> hi
eman
</code></pre>
| 2 | 2016-08-26T16:35:48Z | 39,234,920 | <p>When you use <code>raw_input</code>, the symbols are coded as bytes.</p>
<p>You need to convert it into a Unicode string with</p>
<pre><code>H.decode('utf8')
</code></pre>
<p>And you may keep your regex:</p>
<pre><code>tokens=regexp_tokenize(Input, r'[ØØ!.Ø]\s*', gaps=True)
</code></pre>
| 1 | 2016-08-30T18:44:38Z | [
"python",
"regex",
"nltk"
] |
Python __init__() how don't override important functionality? | 39,170,964 | <p>I need to add another option in a class, a simple 'edit=False'. Whithout override completely <strong>init</strong>().
I found this piece of code written for kivy:</p>
<pre><code>class TitleBox(BoxLayout):
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
super(TitleBox, self).__init__(**kwargs)
</code></pre>
<p>But when I try to edit for my purposes I receive: "TypeError: <strong>init</strong>() takes at most 2 arguments (3 given)"</p>
<pre><code>class Person_Dialog(tkSimpleDialog.Dialog):
def __init__(self, edit=False, **kwargs):
super(Person_Dialog, self).__init__(**kwargs)
self.edit = edit
</code></pre>
| 1 | 2016-08-26T16:37:27Z | 39,171,358 | <p>Given an <code>__init__</code> signature of:</p>
<pre><code>def __init__(self, edit=False, **kwargs):
</code></pre>
<p>When you do this:</p>
<pre><code>add = Person_Dialog(root, 'Add person')
</code></pre>
<p>Python creates an instance and assigns it to the <code>self</code> argument. Then it assigns <code>root</code> to the <code>edit</code> argument. Then it takes <code>'Add a person'</code> and finds no other <em>positional</em> arguments to assign it to.</p>
<p>To fix this add another argument to <code>__init__</code>:</p>
<pre><code>class Person_Dialog(tkSimpleDialog.Dialog):
def __init__(self, parent, edit=False, **kwargs): # added parent argument
super(Person_Dialog, self).__init__(parent, **kwargs)
self.edit = edit
</code></pre>
<p>Note that we also pass <code>parent</code> to the superclass because <code>tkSimpleDialog.Dialog</code> has this signature <code>__init__(self, parent, title=None)</code>.</p>
<p>Unfortunately, your code now fails with <code>TypeError: must be type, not classobj</code> because <code>tkSimpleDialog.Dialog</code> is an old style class and you can't use <code>super()</code> with old style classes. (Python 3 does away with old style classes, so you won't have this issue there.)</p>
<p>So to fix this replace the call to <code>super()</code> with a direct reference to the superclass:</p>
<pre><code>class Person_Dialog(tkSimpleDialog.Dialog):
def __init__(self, parent, edit=False, **kwargs):
# referencing the superclass directly
tkSimpleDialog.Dialog.__init__(self, parent, **kwargs)
self.edit = edit
</code></pre>
<p>Now your code will work.</p>
| 2 | 2016-08-26T17:03:02Z | [
"python",
"tkinter",
"init",
"super"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find entries in <code>bar</code> that are not in <code>foo</code>. However some names in <code>bar</code> have <code>"-mgmt"</code> or some other string appended that don't occur in <code>foo</code>. The length and number of dashes per list item vary greatly, so I'm not sure how successful using a regex would be. I'm new to programming, so please provide some explanation if possible.</p>
| 0 | 2016-08-26T16:45:49Z | 39,171,261 | <p>You could do this with a list comprehension and <code>all</code>:</p>
<pre><code>>>> out = [i for i in bar if all(j not in i for j in foo)]
>>> out
['some-switch-3-mgmt']
</code></pre>
<p>Meaning, you select every element <code>i</code> in <code>bar</code> if, for every element <code>j</code> in <code>foo</code>, <code>j</code> is not contained in <code>i</code>.</p>
| 0 | 2016-08-26T16:56:52Z | [
"python",
"list"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find entries in <code>bar</code> that are not in <code>foo</code>. However some names in <code>bar</code> have <code>"-mgmt"</code> or some other string appended that don't occur in <code>foo</code>. The length and number of dashes per list item vary greatly, so I'm not sure how successful using a regex would be. I'm new to programming, so please provide some explanation if possible.</p>
| 0 | 2016-08-26T16:45:49Z | 39,171,264 | <p>You may achieve it by using <code>filter</code> as:</p>
<pre><code>>>> filter(lambda x: x if not any(x.startswith(f) for f in foo) else None, bar)
['some-switch-3-mgmt']
</code></pre>
<p>I am using <code>startswith</code> to check whether any element of <code>bar</code> starts with any element of <code>foo</code></p>
| 0 | 2016-08-26T16:57:03Z | [
"python",
"list"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find entries in <code>bar</code> that are not in <code>foo</code>. However some names in <code>bar</code> have <code>"-mgmt"</code> or some other string appended that don't occur in <code>foo</code>. The length and number of dashes per list item vary greatly, so I'm not sure how successful using a regex would be. I'm new to programming, so please provide some explanation if possible.</p>
| 0 | 2016-08-26T16:45:49Z | 39,171,350 | <p>You can use <code>startswith()</code> to see if a string starts with another string. So something like:</p>
<pre><code>out = [bar_string for bar_string in bar if not bar_string.startswith(tuple(foo))]
</code></pre>
| 0 | 2016-08-26T17:02:19Z | [
"python",
"list"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find entries in <code>bar</code> that are not in <code>foo</code>. However some names in <code>bar</code> have <code>"-mgmt"</code> or some other string appended that don't occur in <code>foo</code>. The length and number of dashes per list item vary greatly, so I'm not sure how successful using a regex would be. I'm new to programming, so please provide some explanation if possible.</p>
| 0 | 2016-08-26T16:45:49Z | 39,172,151 | <p>There is some problems with the solutions provided by @Jim and @bbkglb when the elements are repeated in <strong><em>bar</em></strong>. Those solutions should be converted to <strong><em>sets</em></strong>. I tested the solutions and their response times:</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']*1000
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']*10000
</code></pre>
<h3>Using <a href="http://www.python-course.eu/python3_lambda.php" rel="nofollow">filter - lambda</a>:</h3>
<pre><code>%timeit set(filter(lambda x: x if not any(x.startswith(f) for f in foo) else None, bar))
1 loop, best of 3: 7.65 s per loop
</code></pre>
<h3>Using <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow">all</a>:</h3>
<pre><code>%timeit set([i for i in bar if all(j not in i for j in foo)])
1 loop, best of 3: 7.97 s per loop
</code></pre>
<h3>Using <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow">any</a>:</h3>
<pre><code>%timeit set(b for b in bar if not any(b.startswith(f) for f in foo))
1 loop, best of 3: 7.97 s per loop
</code></pre>
| 0 | 2016-08-26T17:57:17Z | [
"python",
"list"
] |
Error on Keras SimpleRNN when input_shape is specified to be 3-d | 39,171,170 | <p>I'm doing trying to train from text on a SimpleRNN on Keras.</p>
<p>In Keras, i specified a very simple parameters for SimpleRNN as below:</p>
<pre><code>model = Sequential()
model.add(SimpleRNN(output_dim=1, input_shape=(1,1,1))
</code></pre>
<p>I understand that input_shape should be (nb_samples, timesteps, input_dim), the same as my train_x.shape</p>
<p>so i was surprised that i received the following error.</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/xxx/xxxx/xxx/xxx.py", line 262, in <module>
model.add(SimpleRNN(output_dim=vocab_size, input_shape=train_x.shape))
File "C:\Anaconda3\envs\py34\lib\site-packages\keras\models.py", line 275, in add
layer.create_input_layer(batch_input_shape, input_dtype)
File "C:\Anaconda3\envs\py34\lib\site-packages\keras\engine\topology.py", line 367, in create_input_layer
self(x)
File "C:\Anaconda3\envs\py34\lib\site-packages\keras\engine\topology.py", line 467, in __call__
self.assert_input_compatibility(x)
File "C:\Anaconda3\envs\py34\lib\site-packages\keras\engine\topology.py", line 408, in assert_input_compatibility
str(K.ndim(x)))
Exception: Input 0 is incompatible with layer simplernn_1: expected ndim=3, found ndim=4
</code></pre>
<p>Not sure why keras "found ndim=4" when only 3 was specified!</p>
<p>for clarity, my </p>
<blockquote>
<p>train_x.shape = (73, 84, 400)</p>
</blockquote>
<p>and </p>
<blockquote>
<p>vocab_size=400</p>
</blockquote>
<p>. As long as input_shape is fed 3d and above, i realised an error will result.</p>
<p>Any help will be greatly appreciated!!! :))</p>
| 2 | 2016-08-26T16:51:00Z | 39,183,717 | <p>You are not supposed to include <code>n_samples</code> in the input shape of the model. So you have to specify a tuple of size 2 for input shape of a your layer (or set the first element of shape to <code>None</code>). Here Keras automatically adds <code>None</code> to your input shape resulting in <code>ndim=4</code>.
More info on this can be found <a href="https://keras.io/getting-started/sequential-model-guide/#specifying-the-input-shape" rel="nofollow">here</a>. </p>
<p>Also it appears that your <code>input_dim=400</code> (assuming you use one-hot coding representation of words in vocabulary) and that your training data consists of <code>73</code> texts (pretty small) each having length of <code>84</code>. So you should probably set <code>input_shape=(84,400).</code></p>
| 0 | 2016-08-27T17:11:12Z | [
"python",
"neural-network",
"theano",
"keras",
"recurrent-neural-network"
] |
Appending data with additional information to text in a file | 39,171,182 | <p>I have a text file containing thousands of lines of code and I would like to replace certain elements as follows:</p>
<p>Text from file1:</p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver foobar2 443
</code></pre>
<p>Text with additional information that I would like to append to original file text (file2):</p>
<pre><code>rserver host foobar1
ip address 1.1.1.1
inservice
rserver host foobar2
ip address 1.1.1.2
inservice
</code></pre>
<p>So we can see that in the original file the <code>rserver</code> line does not capture the IP address but I have this information in the other file. </p>
<p>Before:</p>
<pre><code>rserver foobar1 443
</code></pre>
<p>After (desired output)</p>
<p><code>rserver foobar1 443</code> <--- Keep original text</p>
<p><code>rserver host foobar1</code> <--- This and following two lines should be added below original text</p>
<pre><code>ip address 1.1.1.1
inservice
</code></pre>
<p>There is a direct mapping between the original text string <code>"rserver foobar1 443"</code> (remove 3rd text block) and the first line of the replacement text <code>"rserver host foobar1"</code> (remove 2nd text block = host).</p>
<p>Is it possible to do this with a python dictionary or similar approach? I would appreciate it if someone could show me how to do this in Python and I will then use this approach when doing similar tasks.</p>
| 0 | 2016-08-26T16:52:23Z | 39,171,964 | <p>The idea is to write a custom parser/translator like the following:</p>
<pre><code>replacements = {}
with open('file2.txt') as f:
for l in f:
l = l.strip()
if l.startswith('rserver'):
server_header = l
server = l.split()
server_name = server[2]
elif 'ip address' in l:
ip_address = l
elif 'service' in l:
service = l
replacements[server_name] = (server_header, ip_address, service)
with open('file1.txt') as f, open('out.txt', 'w') as out:
for l in f:
l = l.rstrip()
if 'rserver' in l:
server = l.split()
server_name = server[1]
out.write(l + '\n')
out.write(' ' + replacements[server_name][0] + '\n')
out.write(' ' + replacements[server_name][1] + '\n')
out.write(' ' + replacements[server_name][2] + '\n')
else:
out.write(l + '\n')
</code></pre>
<p><strong>Output</strong> <em>(out.txt)</em></p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver host foobar1
ip address 1.1.1.1
inservice
rserver foobar2 443
rserver host foobar2
ip address 1.1.1.2
inservice
</code></pre>
| 1 | 2016-08-26T17:43:45Z | [
"python"
] |
Appending data with additional information to text in a file | 39,171,182 | <p>I have a text file containing thousands of lines of code and I would like to replace certain elements as follows:</p>
<p>Text from file1:</p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver foobar2 443
</code></pre>
<p>Text with additional information that I would like to append to original file text (file2):</p>
<pre><code>rserver host foobar1
ip address 1.1.1.1
inservice
rserver host foobar2
ip address 1.1.1.2
inservice
</code></pre>
<p>So we can see that in the original file the <code>rserver</code> line does not capture the IP address but I have this information in the other file. </p>
<p>Before:</p>
<pre><code>rserver foobar1 443
</code></pre>
<p>After (desired output)</p>
<p><code>rserver foobar1 443</code> <--- Keep original text</p>
<p><code>rserver host foobar1</code> <--- This and following two lines should be added below original text</p>
<pre><code>ip address 1.1.1.1
inservice
</code></pre>
<p>There is a direct mapping between the original text string <code>"rserver foobar1 443"</code> (remove 3rd text block) and the first line of the replacement text <code>"rserver host foobar1"</code> (remove 2nd text block = host).</p>
<p>Is it possible to do this with a python dictionary or similar approach? I would appreciate it if someone could show me how to do this in Python and I will then use this approach when doing similar tasks.</p>
| 0 | 2016-08-26T16:52:23Z | 39,172,000 | <p>If you are running a Linux distro, then you can use awk command and pipe it with grep.</p>
<p>If you want a solution with python, then the complexity is going to be O(n.m), where n is the number of lines in first file and m is the number of lines in second file.</p>
<p>Algorithm in python:</p>
<pre><code>open a new file, file3
file1 = f.open(path to file 1)
n = number of lines in file1
file2 = f.open(path to file 2)
m = number of lines in file 2
for i in range(n):
r = readline(file1)
copy line into file3
convert r to array and check to see if r[0] is "rserver"
if r[0]=="rserver" then:
for j in range(m):
k = readline(file2)
convert k to array and check to see if k[0] is "rserver"
if k[0]=="rserver" then:
merge required number of lines from file2 into file3
increment j by x
close all files
</code></pre>
<p>Hope this helps!</p>
| 0 | 2016-08-26T17:46:01Z | [
"python"
] |
Appending data with additional information to text in a file | 39,171,182 | <p>I have a text file containing thousands of lines of code and I would like to replace certain elements as follows:</p>
<p>Text from file1:</p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver foobar2 443
</code></pre>
<p>Text with additional information that I would like to append to original file text (file2):</p>
<pre><code>rserver host foobar1
ip address 1.1.1.1
inservice
rserver host foobar2
ip address 1.1.1.2
inservice
</code></pre>
<p>So we can see that in the original file the <code>rserver</code> line does not capture the IP address but I have this information in the other file. </p>
<p>Before:</p>
<pre><code>rserver foobar1 443
</code></pre>
<p>After (desired output)</p>
<p><code>rserver foobar1 443</code> <--- Keep original text</p>
<p><code>rserver host foobar1</code> <--- This and following two lines should be added below original text</p>
<pre><code>ip address 1.1.1.1
inservice
</code></pre>
<p>There is a direct mapping between the original text string <code>"rserver foobar1 443"</code> (remove 3rd text block) and the first line of the replacement text <code>"rserver host foobar1"</code> (remove 2nd text block = host).</p>
<p>Is it possible to do this with a python dictionary or similar approach? I would appreciate it if someone could show me how to do this in Python and I will then use this approach when doing similar tasks.</p>
| 0 | 2016-08-26T16:52:23Z | 39,172,007 | <p>Yes, you can use a dictionary or <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> to map server names from the second file and their list of details (ip and service status) and insert these details while writing into a new file:</p>
<pre><code>from collections import defaultdict
import re
d = defaultdict(list)
with open('file1.txt') as f1, open('file2.txt') as f2, open('output.txt', 'w') as f3:
for line in f2:
if 'host' in line:
key = line.strip().replace('host ', '')
d[key].append(' ' + line) # match indentation in file1 with leading spaces
for line in f1:
f3.write(line if '\n' in line else line+'\n')
if 'rserver' in line:
f3.writelines(d[re.sub(r'\s\d+', '', line.strip())])
</code></pre>
<hr>
<p><em>output.txt</em>:</p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver host foobar1
ip address 1.1.1.1
inservice
rserver foobar2 443
rserver host foobar2
ip address 1.1.1.2
inservice
</code></pre>
| 1 | 2016-08-26T17:46:23Z | [
"python"
] |
FileNotFoundError: [Errno 2] No such file or directory: 'userDetails' | 39,171,257 | <p>My program needs to read an external Notepad (.txt) file which has usernames and passwords. (Both the program and the document are on my desktop.) I used this code to read it.</p>
<pre><code>file = open ("userDetails.txt", "r")
userDetails = file.readlines()
file.close()
</code></pre>
<p>But I keep getting this error:</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'userDetails'
</code></pre>
<p>I tried putting them in a folder together, but still got the same error. Any ideas?</p>
| 0 | 2016-08-26T16:56:39Z | 39,171,293 | <p>Try and specify the full file path to the text file when you open it:</p>
<p>i.e <code>/full/path/to/file.txt</code> such as <code>/Users/Harrison/Desktop/file.txt</code></p>
<p>Right now it's likely that Python is looking for the file in the default Python working directory.</p>
<p>Also, it's a better practice when working with files to open it like this:</p>
<pre><code>with open('/path/to/userDetails.txt') as file:
file_contents = file.readlines()
# or whatever else you'd like to do
</code></pre>
<p>... and <a href="http://docs.quantifiedcode.com/python-anti-patterns/maintainability/not_using_with_to_open_files.html" rel="nofollow">here</a> is an explanation as to why it's good to do it this way.</p>
<p>If you're having trouble locating the full file path, here's how you can do it for <a href="http://www.cnet.com/how-to/how-to-copy-a-file-path-in-os-x/" rel="nofollow">Mac</a> and <a href="http://www.pcworld.com/article/251406/windows_tips_copy_a_file_path_show_or_hide_extensions.html" rel="nofollow">Windows</a>.</p>
| 1 | 2016-08-26T16:58:56Z | [
"python"
] |
FileNotFoundError: [Errno 2] No such file or directory: 'userDetails' | 39,171,257 | <p>My program needs to read an external Notepad (.txt) file which has usernames and passwords. (Both the program and the document are on my desktop.) I used this code to read it.</p>
<pre><code>file = open ("userDetails.txt", "r")
userDetails = file.readlines()
file.close()
</code></pre>
<p>But I keep getting this error:</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'userDetails'
</code></pre>
<p>I tried putting them in a folder together, but still got the same error. Any ideas?</p>
| 0 | 2016-08-26T16:56:39Z | 39,171,605 | <p>I think your userDetails.txt does not reside in the python script working directory. So you have to specify your file names for input and output like e.g.:</p>
<pre><code># ----------------------------------------
# open file and select coordinates
# ----------------------------------------
pathnameIn = "D:/local/python/data"
filenameIn = "910-details.txt"
pathIn = pathnameIn + "/" + filenameIn
pathnameOut = "D:/local/python/data"
filenameOut = "910-details-reduced.txt"
pathOut = pathnameOut + "/" + filenameOut
fileIn = open(pathIn,'r')
fileOut = open(pathOut,'w')
</code></pre>
| 0 | 2016-08-26T17:19:17Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary. So I came up with this</p>
<pre><code>def odd_sum_n(n):
sum = 0;
for i in range(1,2*n):
if i % 2 != 0:
sum = sum + i;
print (sum)
print(odd_sum_n(5))
</code></pre>
<p>But this code gives me the solution</p>
<pre><code>25
None
</code></pre>
<p>I kept trying to adjusting this code but I don't see why the "None" appears. I'm new to python so any help would be appreciated!</p>
| 2 | 2016-08-26T16:58:06Z | 39,171,309 | <p>Python considers that the return code is <code>None</code> for functions not returning anything</p>
<p>You actually have to RETURN sum not print it in your function </p>
<pre><code>def odd_sum_n(n):
sum = 0;
for i in range(1,2*n):
if i % 2 != 0:
sum += i;
return (sum)
print(odd_sum_n(5))
</code></pre>
<p>BTW I would suggest to avoid using <code>sum</code> as it is a predefined function...</p>
<p>Note: another solution, shorter where we use prefedined <code>sum</code></p>
<pre><code>def odd_sum_n(n):
return sum(range(1,2*n,2))
print(odd_sum_n(5))
</code></pre>
<p>for laughs: hjpotter92 comment is even better for this particular problem</p>
<pre><code>def odd_sum_n(n):
return n*n
</code></pre>
<p>another classic serie: sum of all integers from 1 to n => <code>sum(range(n))</code> but also <code>n*(n+1)//2</code></p>
| 5 | 2016-08-26T16:59:57Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary. So I came up with this</p>
<pre><code>def odd_sum_n(n):
sum = 0;
for i in range(1,2*n):
if i % 2 != 0:
sum = sum + i;
print (sum)
print(odd_sum_n(5))
</code></pre>
<p>But this code gives me the solution</p>
<pre><code>25
None
</code></pre>
<p>I kept trying to adjusting this code but I don't see why the "None" appears. I'm new to python so any help would be appreciated!</p>
| 2 | 2016-08-26T16:58:06Z | 39,171,360 | <p>You are not returning any value from your odd_sum(n) function that's why it print None.</p>
| 0 | 2016-08-26T17:03:08Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary. So I came up with this</p>
<pre><code>def odd_sum_n(n):
sum = 0;
for i in range(1,2*n):
if i % 2 != 0:
sum = sum + i;
print (sum)
print(odd_sum_n(5))
</code></pre>
<p>But this code gives me the solution</p>
<pre><code>25
None
</code></pre>
<p>I kept trying to adjusting this code but I don't see why the "None" appears. I'm new to python so any help would be appreciated!</p>
| 2 | 2016-08-26T16:58:06Z | 39,171,394 | <p>This program illustrates why you get <code>2500</code> printed</p>
<pre><code>def print2500():
print(2500)
print2500()
</code></pre>
<p>And this one why you get <code>None</code> printed</p>
<pre><code>def doNotReturnAnything():
n = 2500
print(doNotReturnAnything())
</code></pre>
<p>Combine both and you get exactly the same result as in the Opening Question :</p>
<pre><code>def print2500():
print(2500)
print(print2500())
</code></pre>
<p>And finally the correct way to do it, have the function return a value.</p>
<pre><code>def return2500():
return 2500
print(return2500())
</code></pre>
<p>Try them yourself!</p>
| 0 | 2016-08-26T17:05:49Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary. So I came up with this</p>
<pre><code>def odd_sum_n(n):
sum = 0;
for i in range(1,2*n):
if i % 2 != 0:
sum = sum + i;
print (sum)
print(odd_sum_n(5))
</code></pre>
<p>But this code gives me the solution</p>
<pre><code>25
None
</code></pre>
<p>I kept trying to adjusting this code but I don't see why the "None" appears. I'm new to python so any help would be appreciated!</p>
| 2 | 2016-08-26T16:58:06Z | 39,172,447 | <p>you want to get the value from your <code>def odd_sum_n(n)</code> for that you need to <code>return(sum)</code> and then just <code>print(odd_sum_n(n))</code> this will only print your answer.
you are getting <code>none</code> because you are trying to print two times one time in <code>def</code> and other time in when you calling the <code>function</code> it self. hope this helps you why you were getting <code>none</code> in your result.</p>
| 1 | 2016-08-26T18:17:16Z | [
"python"
] |
writing pandas series into tab separated file | 39,171,396 | <p>I have a pandas series y which I generated by group by and looks like </p>
<pre><code>Item Attribute Feature
aaaa x1 f1,f2
x2 f3,f4
bbbb x3 f5
x4 f6
</code></pre>
<p>I want to generate a tab delimted output that looks exactly as above. When I try</p>
<pre><code>y.to_csv('out',sep = "\t")
</code></pre>
<p>I get </p>
<pre><code>Item Attribute Feature
aaaa x1 f1,f2
aaaa x2 f3,f4
bbbb x3 f5
bbbb x4 f6
</code></pre>
<p>I want to avoid repetition of elements in the "Item" column. Can you help</p>
| 2 | 2016-08-26T17:05:56Z | 39,171,557 | <p>The text you want isn't <code>csv</code>.</p>
<p>Assume <code>df</code> is your dataframe or series:</p>
<pre><code>with open('out.txt', 'w') as f:
f.write(df.__repr__())
</code></pre>
<hr>
<h3><code>to_txt</code> function</h3>
<pre><code>import pandas as pd
def to_txt(df, fn=None):
x, c, r = ['expand_frame_repr', 'max_columns', 'max_rows']
current_max_col = pd.get_option(c)
current_max_row = pd.get_option(r)
current_xpd_frm = pd.get_option(x)
pd.set_option(x, False)
pd.set_option(c, df.shape[1])
pd.set_option(r, df.shape[0])
if fn is not None:
with open(fn, 'w') as f:
f.write(df.__repr__())
else:
return df.__repr__()
pd.set_option(x, current_xpd_frm)
pd.set_option(c, current_max_col)
pd.set_option(r, current_max_row)
</code></pre>
<h3>Demonstration</h3>
<pre><code>to_text(df, 'test_file.txt')
</code></pre>
| 1 | 2016-08-26T17:16:13Z | [
"python",
"pandas"
] |
Apply a split and take second element of result in Pandas column that sometimes contains None and sometimes does not split into more than 1 component | 39,171,399 | <p>I am looking at an email sender data column that looks like this:</p>
<pre><code>from_name
----------
Joe Smith, VP at Corp
Alice Brown
None
Helpdesk, McRay's Store
</code></pre>
<p>From this, I'd like to generate a column like this:</p>
<pre><code>title_if_any
-------------
VP at Corp
None
None
McRay's Store
</code></pre>
<p>I've tried the following:</p>
<pre><code>email_data['title_email_sender'] = email_data[email_data.from_name.isnull() == False][email_data.from_name.apply(lambda x: ',' in x)].from_name.apply(lambda x: x.split(',')[1])
</code></pre>
<p>But this generates the following error:</p>
<pre><code>----> 2 email_data['title_email_sender'] = email_data[email_data.from_name.isnull() == False][email_data.from_name.apply(lambda x: ',' in x)].from_name.apply(lambda x: x.split(',')[1])
TypeError: argument of type 'NoneType' is not iterable
</code></pre>
<p>Shouldn't my first selection remove all NoneTypes? How can I achieve what I want and fix the above?</p>
<p>Thanks!</p>
| 3 | 2016-08-26T17:06:03Z | 39,171,519 | <p>you can do <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow">str.split()</a>:</p>
<pre><code>In[53]:df['title_if_any']=df.from_name.str.split(',',expand=True)[1]
In[54]:df
Out[54]:
0 VP at Corp
1 None
2 None
3 McRays Store
Name: 1, dtype: object
</code></pre>
| 3 | 2016-08-26T17:13:31Z | [
"python",
"pandas"
] |
Python scraping: 403 and 503 Errors | 39,171,510 | <p>I am trying to crawl some public information(apple app's info) on a website. </p>
<p>This website requires log-in in order to perform actions such as "search app/developer". Although there are many website provide similar information, but I consider this particular website provides the most complete and detailed info for each app. </p>
<p>I, as a valid user, am able to perform the task.</p>
<p>However, when I try to access the info via python code, I have the encountered 403 Error when sending POST request, and 504 Error when sending Get request. </p>
<p>I have tried using </p>
<ol>
<li><p>real userAgent header </p></li>
<li><p>fake-useragent" package</p></li>
<li><p>FancyOpener[/sth like that, shown depreciated for python 3.4]</p></li>
<li><p>HttpAuthM..[/sth like that, for authentication, still doesn't work]</p></li>
</ol>
<p>I guess the website is highly against automate access, but the detailed info there is highly useful. Is there any way I could workaround this issue? </p>
<p>Thanks!!</p>
<p>I tried this header:</p>
<pre><code>ua = {#'User-Agent':'Mozilla/5.0 (compatible; Googlebot/2.1; +Googlebot - Webmaster Tools Help)',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36',
'Connection':'Keep-Alive',
'Accept-Language':'zh-CN,zh;q=0.8',
'Accept-Encoding':'gzip,deflate,sdch',
'Accept':'*/*',
'Accept-Charset':'GBK,utf-8;q=0.7,*;q=0.3',
'Cache-Control':'max-age=0'
}
</code></pre>
<p><a href="http://i.stack.imgur.com/LUcfv.jpg" rel="nofollow">503 Error</a></p>
<p><a href="http://i.stack.imgur.com/4zTDM.jpg" rel="nofollow">403 Error</a></p>
<pre><code>------------------------------------------------ HTTPError
Traceback (most recent call last) <ipython-input-43-421b27c5194e> in <module>()
68 data= data.encode('utf-8')
69 request = urq.Request(url, data, headers = ua)
---> 70 response = urq.urlopen(request)
71 the_page = response.read()
72 print(the_page)
c:\python34\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
159 else:
160 opener = _opener
--> 161 return opener.open(url, data, timeout)
162
163 def install_opener(opener):
c:\python34\lib\urllib\request.py in open(self, fullurl, data, timeout)
468 for processor in self.process_response.get(protocol, []):
469 meth = getattr(processor, meth_name)
--> 470 response = meth(req, response)
471
472 return response
c:\python34\lib\urllib\request.py in http_response(self, request, response)
578 if not (200 <= code < 300):
579 response = self.parent.error(
--> 580 'http', request, response, code, msg, hdrs)
581
582 return response
c:\python34\lib\urllib\request.py in error(self, proto, *args)
506 if http_err:
507 args = (dict, 'default', 'http_error_default') + orig_args
--> 508 return self._call_chain(*args)
509
510 # XXX probably also want an abstract factory that knows when it makes
c:\python34\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
440 for handler in handlers:
441 func = getattr(handler, meth_name)
--> 442 result = func(*args)
443 if result is not None:
444 return result
c:\python34\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
586 class HTTPDefaultErrorHandler(BaseHandler):
587 def http_error_default(self, req, fp, code, msg, hdrs):
--> 588 raise HTTPError(req.full_url, code, msg, hdrs, fp)
589
590 class HTTPRedirectHandler(BaseHandler):
HTTPError: HTTP Error 403: FORBIDDEN
----------------------------------------------
</code></pre>
<p>The below result I obtained by using "Advanced REST client", which is a chrome extension to send request. Notice how on a page that doesn't require log in, the code is 200; the other one was 403 at login page.See link in comment below</p>
<p>[access success][3]</p>
<p>[access fail][4]</p>
| 1 | 2016-08-26T17:13:05Z | 39,171,938 | <p>plain python requests package is enough, you shouldn't need other packages.</p>
<p>I'm sure your problem is just you're not perfectly emulating a browser request.
On Google Chrome and Mozilla Firefox you should be able to see requests headers from a developer panel.</p>
<p>Be sure you always use the <strong>same</strong> session object.</p>
<p>Be sure not to forget to set proper headers:</p>
<ul>
<li>User-Agent</li>
<li>Accept</li>
<li>Accept-Language</li>
<li>Accept-Encoding</li>
<li><strong>Referer</strong> (url of previous GET request)</li>
<li>Connection (keep-alive)</li>
<li><strong>Host</strong> ( abc.website.com )</li>
</ul>
<p>.</p>
<pre><code>session.headers = {
'User-Agent' : 'real one',
...
}
</code></pre>
<p>Be sure to respect redirects:</p>
<pre><code>session.get(url, allow_redirects=True, timeout=x_secs)
</code></pre>
<p>In post requests be sure you send all the required fields, there may be some hidden ones (like the csfr token).</p>
| 0 | 2016-08-26T17:42:24Z | [
"python",
"web-crawler",
"http-error"
] |
Ubuntu , Apache2 , Django ) Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' | 39,171,616 | <p>I'm trying to set up my <strong>django(1.8)</strong> application with <strong>AWS EC2</strong> having <strong>Ubuntu 14.04 , Apache2 , python 3.4.</strong></p>
<p>When I run 'sudo service apache2 start' , the page keeps re-loading and the same error message is stacking at '/var/log/apache2/error.log'.</p>
<p>The error message is</p>
<blockquote>
<p>[Fri Aug 26 2016] [mpm_event:notice] [pid n:tid m] AH00489: Apache/2.4.7 (Ubuntu) mod_wsgi/4.5.5 Python/3.4.3 configured -- resuming normal operations
[Fri Aug 26 2016] [core:notice] [pid n:tid m] AH00094: Command line: '/usr/sbin/apache2'
<strong>Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'</strong></p>
</blockquote>
<p>My configuration is below :</p>
<p>I added one line: <code>'Include /etc/apache2/httpd.conf'</code> at the bottom of <code>'/etc/apache2/apache2.conf'</code>.</p>
<blockquote>
<p>'/etc/apache2/httpd.conf'
:</p>
</blockquote>
<pre><code>WSGIScriptAlias / /home/ubuntu/project/project/project/wsgi.py
WSGIDaemonProcess project python-path=/home/ubuntu/project/project
WSGIProcessGroup project
WSGIPythonHome /usr/bin/python3.4
<Directory /home/ubuntu/project/project/project>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Alias /static/ /home/ubuntu/project/project/deploy_to_server/
<Directory /home/ubuntu/project/project/deploy_to_server>
Require all granted
</Directory>
</code></pre>
<p>I think I did it all done without something wrong.</p>
<p>But it keeps logging with the same error.
Is there anything I'm missing?</p>
<p>I did change <code>mod_wsgi/3.x Python/2.7 configured</code> --> <code>mod_wsgi/4.5.5 Python/3.4.3 configured</code> for synchronizing the python version ALREADY</p>
| 0 | 2016-08-26T17:19:59Z | 39,172,342 | <p>It was because of the line 'WSGIPythonHome /usr/bin/pytyon3.4' in /etc/apache2/httpd.conf.</p>
<p>Without this line, it runs without error thank you</p>
| 0 | 2016-08-26T18:09:59Z | [
"python",
"django",
"apache",
"ubuntu",
"mod-wsgi"
] |
Adding docstring to __slots__ descriptor? | 39,171,672 | <p>I'm writing a storage automation module that provisions volumes. Instead of passing the half dozen or more arguments needed to actually create a volume on the storage controller, I created a parameter class using <code>__slots__</code> that is passed into the create method like this:</p>
<pre><code>from mock import Mock
from six import with_metaclass
class VolumeParameterMeta(type):
def __new__(mcs, name, bases, dct):
# set __slots__ docstrings here?
return super(VolumeParameterMeta, mcs).__new__(mcs, name, bases, dct)
class VolumeParameter(with_metaclass(VolumeParameterMeta, object)):
__slots__ = ('name', 'size', 'junctionPath', 'svmName', 'securityStyle'
'spaceReserve')
def __init__(self, name):
self.name = name
class Volume(object):
def __init__(self, driver, name):
self.driver = driver
self.name = name
@classmethod
def create(cls, driver, param):
# do sanity check on param (volume not too large, etc)
driver.provision(param)
return cls(driver, param.name)
if __name__ == '__main__':
param = VolumeParameter('volume1')
param.svmName = 'vserver1'
param.junctionPath = '/some/path'
param.size = 2 ** 30
param.spaceReserve = param.size * 0.1
param.securityStyle = 'mixed'
volume = Volume.create(driver=Mock(), param=param)
</code></pre>
<p>The above example works great with one small exception. It's not obvious how to add docstrings to the descriptors in the parameter class. It <em>seems</em> like it should be possible with a metaclass, but the descriptors aren't defined when the metaclass is instantiated.</p>
<p>I'm keenly aware that some may disagree with my using a side-effect of <code>__slots__</code>, but I like that it helps eliminate typos. Try to set a parameter that doesn't exist and boom, <code>AttributeError</code> is raised. All without any boilerplate code. It's arguably more Pythonic to let it fail at volume creation time, but the result would be that a default is used instead of an incorrectly spelled parameter. It would effectively be a silent failure.</p>
<p>I realize it's possible to simply expand the parameter class docstring, but the result of <code>pydoc</code> and other documentation building scripts is a large free-form docstring for the class and <em>empty</em> docstrings for each of the descriptors.</p>
<p><strong>Surely there must be a way to define docstrings for the descriptors created by <code>__slots__</code>? Perhaps there's another way apart from slots? A mutable <code>namedtuple</code> or similar?</strong></p>
| 2 | 2016-08-26T17:23:46Z | 39,171,830 | <p>No, there is no option to add docstrings to the descriptor objects that are generated for names defined in <code>__slots__</code>. They are like regular non-descriptor attributes in that regard.</p>
<p>On a regular object without slots, you can, at most, add comments and set default values:</p>
<pre><code>class VolumeParameter(object):
# the name of the volume (str)
name = ''
# volume size in bytes (int)
size = 0
# ...
</code></pre>
<p>The same still applies even if you declared all those attributes as <code>__slots__</code>.</p>
<p>You could 'wrap' each slot in another descriptor in the form of a <code>property</code> object:</p>
<pre><code>class VolumeParameterMeta(type):
@staticmethod
def _property_for_name(name, docstring):
newname = '_' + name
def getter(self):
return getattr(self, newname)
def setter(self, value):
setattr(self, newname, value)
def deleter(self):
delattr(self, newname)
return newname, property(getter, setter, deleter, docstring)
def __new__(mcs, name, bases, dct):
newslots = []
clsslots = dct.pop('__slots__', ())
slotdocs = dct.pop('__slot_docs__', {})
if isinstance(clsslots, str):
clsslots = clsslots.split()
for name in clsslots:
newname, prop = mcs._property_for_name(name, slotdocs.get(name))
newslots.append(newname)
dct[name] = prop
if newslots:
dct['__slots__'] = tuple(newslots)
return super(VolumeParameterMeta, mcs).__new__(mcs, name, bases, dct)
class VolumeParameter(with_metaclass(VolumeParameterMeta, object)):
__slots__ = ('name', 'size', 'junctionPath', 'svmName', 'securityStyle'
'spaceReserve')
__slot_docs__ = {
'name': 'the name of the volume (str)',
# ...
}
</code></pre>
<p>Note that this almost doubles the number of descriptors on the class:</p>
<pre><code>>>> pprint(VolumeParameter.__dict__)
mappingproxy({'__doc__': None,
'__module__': '__main__',
'__slots__': ('_name',
'_size',
'_junctionPath',
'_svmName',
'_securityStylespaceReserve'),
'_junctionPath': <member '_junctionPath' of 'securityStylespaceReserve' objects>,
'_name': <member '_name' of 'securityStylespaceReserve' objects>,
'_securityStylespaceReserve': <member '_securityStylespaceReserve' of 'securityStylespaceReserve' objects>,
'_size': <member '_size' of 'securityStylespaceReserve' objects>,
'_svmName': <member '_svmName' of 'securityStylespaceReserve' objects>,
'junctionPath': <property object at 0x105edbe08>,
'name': <property object at 0x105edbd68>,
'securityStylespaceReserve': <property object at 0x105edb098>,
'size': <property object at 0x105edbdb8>,
'svmName': <property object at 0x105edb048>})
</code></pre>
<p>but now your properties at least have docstrings:</p>
<pre><code>>>> VolumeParameter.name.__doc__
'the name of the volume (str)'
</code></pre>
| 3 | 2016-08-26T17:33:48Z | [
"python"
] |
django: is it possible to keep a model field updated with a model method? | 39,171,685 | <p>So basically I have a model Equipment that has foreign key calibration. I would like to have a field in Equipment as 'latest_calibrated_date' which get the 'cal_date' from the newest created calibration. Here is what I have now:</p>
<pre><code>def latest_calibration_date(self):
return Calibration.objects.filter(cal_asset__id = self.id).order_by('-id')[0].cal_date
</code></pre>
<p>However, for the purpose of some other apps, I would like to make this not a method but a field. So I am thinking about use a latest_calibration_date = models.DateField() and update it every time a new Calibration is added. How could I do this?</p>
| 0 | 2016-08-26T17:24:20Z | 39,172,567 | <p>As <em>Daniel Roseman</em> pointed out, you can override <code>save</code> method on <code>Calibration</code> model. For example:</p>
<pre><code>class Calibration(model.Model):
# your fields
def save(self, *args, **kwargs):
super(Calibration, self).save(*args, **kwargs)
# update latest calibration date
</code></pre>
<p>You can store your parameter in many ways, for example by creating <code>Parameter</code> model for storing your variables.</p>
<pre><code>class Parameter(models.Model):
key = models.CharField(max_length=255, unique=True)
value = models.IntegerField()
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.key
</code></pre>
<p>and then again in <code>save</code>:</p>
<pre><code>import time
p = Parameter.objects.get(key='LATEST_CALIBRATION_DATE')
p.value = time.time() # save in UNIX timestamp
p.save()
</code></pre>
<p>or whatever format you like.</p>
| 1 | 2016-08-26T18:24:13Z | [
"python",
"django"
] |
How to add each item in a list to the previous one in Python? | 39,171,764 | <p>I have a list and I want to add each element in the list to the previous one. For example if I have the list <code>(1,1,3,3,4)</code>, I want the program to output <code>(1,2,5,8,12)</code>. </p>
| 1 | 2016-08-26T17:29:10Z | 39,171,796 | <pre><code>[sum(a[:i]) for i in range(1,len(a)+1)]
</code></pre>
<p>is probably the easiest way ... I guess ...</p>
<pre><code>numpy.cumsum(a)
</code></pre>
<p>would also work i think</p>
| 2 | 2016-08-26T17:31:54Z | [
"python",
"list"
] |
How to add each item in a list to the previous one in Python? | 39,171,764 | <p>I have a list and I want to add each element in the list to the previous one. For example if I have the list <code>(1,1,3,3,4)</code>, I want the program to output <code>(1,2,5,8,12)</code>. </p>
| 1 | 2016-08-26T17:29:10Z | 39,171,876 | <pre><code>for i in range(1, len(arr)):
arr[i] += arr[i - 1]
</code></pre>
<p>more efficient than Joran Beasley loop</p>
| 1 | 2016-08-26T17:37:00Z | [
"python",
"list"
] |
How to add each item in a list to the previous one in Python? | 39,171,764 | <p>I have a list and I want to add each element in the list to the previous one. For example if I have the list <code>(1,1,3,3,4)</code>, I want the program to output <code>(1,2,5,8,12)</code>. </p>
| 1 | 2016-08-26T17:29:10Z | 39,171,897 | <p>using <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate</code></a></p>
<pre><code>>>> import itertools
>>> list(itertools.accumulate([1,1,3,3,4], lambda total,el: total+el))
[1, 2, 5, 8, 12]
</code></pre>
<p><em>disclaimer</em>: added in python 3.2</p>
| 2 | 2016-08-26T17:38:57Z | [
"python",
"list"
] |
How do I properly avoid the usage of a delimiter in a custom string? | 39,171,765 | <p>I am currently working on a Discord Bot that interacts with my gameserver through rcon and came across a problem.</p>
<p>I have two functions. This is for the bot to recognize a command (e.g. '.say Hello World')</p>
<pre><code>@bot.command(pass_context=True, aliases=[])
@asyncio.coroutine
def say(context, *, msg):
yield from bot.say("```{0}```".format(rcon.rcon_say(msg)))
</code></pre>
<p>The second function sends it to my gameserver. In this case 'say Hello World' wich will make the server say 'Hello World' into the chat.</p>
<pre><code>def rcon_say(_msg : str):
with RCON(SERVER_ADDRESS, PASSWORD) as rcon:
return rcon("say {0}".format(_msg))
</code></pre>
<p>The problem: .say "test; kick user1" will send two commands to the server:</p>
<pre><code> say test
kick user1
</code></pre>
<p>so its abusable with any other rcon command. So how to avoid this from beeing abused?</p>
<p>What I did to avoid abusage:</p>
<p>I added following function:</p>
<pre><code>def checkMsg(checkThis : str):
if ";" in checkThis:
raise errors.SemicolonError()
return
else:
return checkThis
</code></pre>
<p>And added </p>
<pre><code> _msg = checkMsg(_msg)
</code></pre>
<p>So this will remove any semicolons from the users input but I somehow don't feel like it's the right way to do this. Is it still possible to send a semicolon (maybe decoded/ in unicode etc.)</p>
<p>Am I safe or is there a way of abusing it?</p>
| 0 | 2016-08-26T17:29:15Z | 39,171,841 | <p>you should instead make your delimiter an unprintable character like <code>'\x00'</code> ... that would easily solve the issue ...</p>
| 0 | 2016-08-26T17:34:35Z | [
"python",
"security",
"python-3.5"
] |
Fastest way to convert a URI into a scheme relative URI (in python) | 39,171,815 | <p>In python, whats the <em>fastest</em> way to convert a url of the type <code>scheme://netloc/path;parameters?query#fragment</code> into a "scheme relative" or "protocol relative" URI?</p>
<hr>
<p>Currently, I'm doing a version of <a href="http://stackoverflow.com/a/21687728/4936905">this</a>, but was thinking there might be a more concise/faster way to accomplish this. The input always has <code>https://</code> or <code>http://</code> appended to it.</p>
| 0 | 2016-08-26T17:32:43Z | 39,171,886 | <pre><code>from urlparse import urlparse
o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
print o.scheme
print o.netloc
print o.path
</code></pre>
<p>is how i would probably do it ...</p>
| 0 | 2016-08-26T17:38:12Z | [
"python"
] |
Fastest way to convert a URI into a scheme relative URI (in python) | 39,171,815 | <p>In python, whats the <em>fastest</em> way to convert a url of the type <code>scheme://netloc/path;parameters?query#fragment</code> into a "scheme relative" or "protocol relative" URI?</p>
<hr>
<p>Currently, I'm doing a version of <a href="http://stackoverflow.com/a/21687728/4936905">this</a>, but was thinking there might be a more concise/faster way to accomplish this. The input always has <code>https://</code> or <code>http://</code> appended to it.</p>
| 0 | 2016-08-26T17:32:43Z | 39,172,526 | <p>The fastest way that I could find is with <code>str.partition</code>:</p>
<pre><code>In [1]: url = 'https://netloc/path;parameters?query#fragment'
In [2]: %timeit url.partition('://')[2]
The slowest run took 6.70 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 251 ns per loop
In [3]: %timeit url.split('://', 1)[1]
The slowest run took 5.20 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 407 ns per loop
In [4]: %timeit url.replace('http', '', 1).replace('s://', '', 1)
The slowest run took 4.24 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 589 ns per loop
</code></pre>
<p>Since all you're doing is stripping off text ending in a fixed string, there doesn't seem to be much benefit in parsing the URL.</p>
| 1 | 2016-08-26T18:21:35Z | [
"python"
] |
In Python, how to get a localized timestamp with only the datetime package? | 39,171,908 | <p>I have a unix timestamp in seconds (such as <code>1294778181</code>) that I can convert to UTC using </p>
<pre><code>from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)
</code></pre>
<p>Problem is, I would like to get the corresponding time in <code>'US/Eastern'</code> (considering any DST) and I cannot use <code>pypz</code> and other utilities. </p>
<p>Only <code>datetime</code> is available to me. </p>
<p>Is that possible?
Thanks!</p>
| 1 | 2016-08-26T17:39:28Z | 39,174,019 | <p>Easiest, but not supersmart solution is using timedelta</p>
<pre><code>import datetime
>>> now = datetime.datetime.utcnow()
</code></pre>
<p>US/Eastern is 5 hours behind UTC, so let's just create thouse five hours as a timedelta object and make it negative, so that when reading back our code we can see that the offset is -5 and that there's no magic to deciding when to add and when to subtract timezone offset</p>
<pre><code>>>> eastern_offset = -(datetime.timedelta(hours=5))
>>> eastern = now + eastern_offset
>>> now
datetime.datetime(2016, 8, 26, 20, 7, 12, 375841)
>>> eastern
datetime.datetime(2016, 8, 26, 15, 7, 12, 375841)
</code></pre>
<p>If we wanted to fix DST, we'd run the datetime through smoething like this (not entirely accurate, timezones are not my expertise (googling a bit now it changes each year, yuck)) </p>
<pre><code>if now.month > 2 and now.month < 12:
if (now.month == 3 and now.day > 12) or (now.month == 11 and now.day < 5):
eastern.offset(datetime.timedelta(hours=5))
</code></pre>
<p>You could go even into more detail, add hours, find out how exactly it changes each year... I'm not going to go through all that :)</p>
| 1 | 2016-08-26T20:12:12Z | [
"python",
"datetime",
"epoch",
"python-datetime"
] |
Python Script to filter arrays containing a specific value in JSON object | 39,171,919 | <p>I have a json object that consists of one object with key 'data', that has values listed in a set of arrays. I need to return all arrays that contain the value x, but the arrays themselves do not have keys. I'm trying to write a script to enter a source file (inFile) an define an export file (outFile). Here is my data structure:</p>
<pre><code>{ "data": [
["x", 1, 4, 6, 2, 7],
["y", 3, 2, 5, 8, 4],
["z", 5, 2, 5, 9, 9],
["x", 3, 7, 2, 6, 8]
]
}
</code></pre>
<p>And here is my current script:</p>
<pre><code>import json
def jsonFilter( inFile, outFile ):
out = None;
with open( inFile, 'r') as jsonFile:
d = json.loads(json_data)
a = d['data']
b = [b for b in a if b != 'x' ]
del b
out = a
if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );
else:
print "Error creating new jsonFile!"
</code></pre>
<p><strong>SOLUTION</strong></p>
<p>Thanks to Rob and everyone for your help! Here's the final working command-line tool. This takes two arguments: inFile and Outfile. ~$ python jsonFilter.py inFile.json outFile.json</p>
<pre><code>import json
def jsonFilter( inFile, outFile ):
# make a dictionary.
out = {};
with open( inFile, 'r') as jsonFile:
json_data = jsonFile.read()
d = json.loads(json_data)
# build the data you want to save to look like the original
# by taking the data in the d['data'] element filtering what you want
# elements where b[0] is 'x'
out['data'] = [b for b in d['data'] if b[0] == 'x' ]
if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );
else:
print "Error creating new JSON file!"
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('inFile', nargs=1, help="Choose the in file to use")
parser.add_argument('outFile', nargs=1, help="Choose the out file to use")
args = parser.parse_args()
jsonFilter( args.inFile[0] , args.outFile[0] );
</code></pre>
| 1 | 2016-08-26T17:40:08Z | 39,172,228 | <p>First problem the query string will be true for everything (aka return the whole data set back since you are comparing b (a list) to 'x' a string</p>
<pre><code> b = [b for b in a if b != 'x' ]
</code></pre>
<p>What you wanted to do was:</p>
<pre><code> b = [b for b in a if b[0] != 'x' ]
</code></pre>
<p>The second problem is you are trying to delete the data by querying and deleting the results. Since the results contain a copy that will not delete anything from the original container. <br/>
Instead build the new data with only the elements you want, and save those. Also you were not recreating the 'data' element in your out data, so the json so the output have the same structure as the input data.</p>
<pre><code>import json
def jsonFilter( inFile, outFile ):
# make a dictionary instead.
out = {};
with open( inFile, 'r') as jsonFile:
json_data = jsonFile.read()
d = json.loads(json_data)
# build the data you want to save to look like the original
# by taking the data in the d['data'] element filtering what you want
# elements where b[0] is 'x'
out['data'] = [b for b in d['data'] if b[0] == 'x' ]
if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );
else:
print "Error creating new jsonFile!"
</code></pre>
<p>output json data looks like:</p>
<pre><code> '{"data": [["x", 1, 4, 6, 2, 7], ["x", 3, 7, 2, 6, 8]]}'
</code></pre>
<p>If you did not want the output to have the 'data' root element but just the array of data that matched your filter then change the line:</p>
<pre><code> out['data'] = [b for b in d['data'] if b[0] == 'x' ]
</code></pre>
<p>to </p>
<pre><code> out = [b for b in d['data'] if b[0] == 'x' ]
</code></pre>
<p>with this change the output json data looks like:</p>
<pre><code> '[["x", 1, 4, 6, 2, 7], ["x", 3, 7, 2, 6, 8]]'
</code></pre>
| 1 | 2016-08-26T18:02:10Z | [
"python",
"arrays",
"json"
] |
Python Script to filter arrays containing a specific value in JSON object | 39,171,919 | <p>I have a json object that consists of one object with key 'data', that has values listed in a set of arrays. I need to return all arrays that contain the value x, but the arrays themselves do not have keys. I'm trying to write a script to enter a source file (inFile) an define an export file (outFile). Here is my data structure:</p>
<pre><code>{ "data": [
["x", 1, 4, 6, 2, 7],
["y", 3, 2, 5, 8, 4],
["z", 5, 2, 5, 9, 9],
["x", 3, 7, 2, 6, 8]
]
}
</code></pre>
<p>And here is my current script:</p>
<pre><code>import json
def jsonFilter( inFile, outFile ):
out = None;
with open( inFile, 'r') as jsonFile:
d = json.loads(json_data)
a = d['data']
b = [b for b in a if b != 'x' ]
del b
out = a
if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );
else:
print "Error creating new jsonFile!"
</code></pre>
<p><strong>SOLUTION</strong></p>
<p>Thanks to Rob and everyone for your help! Here's the final working command-line tool. This takes two arguments: inFile and Outfile. ~$ python jsonFilter.py inFile.json outFile.json</p>
<pre><code>import json
def jsonFilter( inFile, outFile ):
# make a dictionary.
out = {};
with open( inFile, 'r') as jsonFile:
json_data = jsonFile.read()
d = json.loads(json_data)
# build the data you want to save to look like the original
# by taking the data in the d['data'] element filtering what you want
# elements where b[0] is 'x'
out['data'] = [b for b in d['data'] if b[0] == 'x' ]
if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );
else:
print "Error creating new JSON file!"
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('inFile', nargs=1, help="Choose the in file to use")
parser.add_argument('outFile', nargs=1, help="Choose the out file to use")
args = parser.parse_args()
jsonFilter( args.inFile[0] , args.outFile[0] );
</code></pre>
| 1 | 2016-08-26T17:40:08Z | 39,172,394 | <p>So, basically you want to filter out your input data containing arrays whose first element is 'x', maybe something like this will do:</p>
<pre><code>import json
def jsonFilter(inFile, outFile):
with open(inFile, 'r') as jsonFile:
d = json.loads(json_data)
out = {
'data': filter(lambda x: x[0] == 'x', d['data'])
}
if out['data']:
with open(outFile, 'w') as jsonFile:
jsonFile.write(json.dumps(out))
else:
print "Error creating new jsonFile!"
</code></pre>
| 1 | 2016-08-26T18:14:00Z | [
"python",
"arrays",
"json"
] |
Cannot connect to MySql in Docker. Access Denied Error thrown. Flask-SqlAlchemy | 39,171,970 | <p>Alright so been trying for a while to get this to work. Here is the line of commands I run from start to finish and I get an <code>Access denied...</code> error shown below.</p>
<pre><code>$ docker-compose up --build -d
$ docker exec -it flaskdocker_mysql_1 mysql -u root -p
mysql> CREATE DATABASE flask_docker;
mysql> CREATE USER `flask-docker`@`localhost` IDENTIFIED BY 'pass';
mysql> GRANT ALL PRIVILEGES ON flask_docker.* TO 'flask-docker'@'localhost';
mysql> exit
Bye
$ docker exec -it flaskdocker_web_1 python /usr/src/app/manage.py createdb
# rest of traceback
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1045, u"Access denied for user 'flask-docker'@'flaskdocker_web_1.flaskdocker_default' (using password: YES)")
</code></pre>
<p>Here is the repo <a href="https://github.com/Amertz08/flask-docker" rel="nofollow">https://github.com/Amertz08/flask-docker</a></p>
<p>It looks like the SqlAlchemy engine is not looking at the right container. <code>'flask-docker'@'flaskdocker_web_1.flaskdocker_default'</code> is what shows up in the error.</p>
<p>Maybe I am not understanding it right but I linked <code>mysql:mysql</code> in my <code>docker-compose.yml</code> file</p>
<pre><code>web:
restart: always
build: ./app
volumes:
- /usr/src/app/static
expose:
- "5000"
environment:
FLASK_CONFIG: 'production'
links:
- mysql:mysql
command: /usr/local/bin/uwsgi --ini uwsgi.ini
</code></pre>
<p>Then in my config object in <code>config.py</code> I have the following...</p>
<pre><code>MYSQL_USER = 'flask-docker'
MYSQL_PASS = 'pass'
MYSQL_HOST = 'mysql'
MYSQL_DB = 'flask_docker'
# Database info
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{usr}:{passwd}@{host}/{db}'.format(
usr=MYSQL_USER, passwd=MYSQL_PASS, host=MYSQL_HOST, db=MYSQL_DB
)
</code></pre>
<p>Any help on this would be greatly appreciated.</p>
| 3 | 2016-08-26T17:44:07Z | 39,172,183 | <p>It seems the problem there:</p>
<p><code>mysql> GRANT ALL PRIVILEGES ON flask_docker.* TO 'flask-docker'@'localhost';</code>
You grant privileges for <strong>localhost</strong> user</p>
<p>But you use mysql as <code>flask-docker'@'flaskdocker_web_1.flaskdocker_default</code> user.</p>
<p>To solve this grant user privileges for flask-docker'@'<strong>flaskdocker_web_1.flaskdocker_default</strong> user</p>
| 3 | 2016-08-26T17:59:37Z | [
"python",
"docker",
"flask",
"flask-sqlalchemy",
"docker-compose"
] |
Pandas Python - get value counts by grouped values | 39,172,047 | <p>I have a situation where multiple customer ids can be belong to the same account, and all records are grouped in to one of two groups:</p>
<pre><code>CUSTOMER_ACCOUNT_ID CUSTOMER_ID GROUP
123 555 A
123 556 A
124 557 B
124 558 B
125 559 A
</code></pre>
<p>What I want to do is get the count of unique CUSTOMER_ACCOUNT_IDs belonging to each group. That is, I don't care how many customer_ids belong to an account, I just want to see how many accounts is in each group. I'm looking for this output</p>
<pre><code>GROUP COUNT
A 2
B 1
</code></pre>
<p>That is, number of unique accounts by group. One way of thinking of it is that I want to collapse or remove the CUSTOMER_ID dimension, so I'm left with</p>
<pre><code>CUSTOMER_ACCOUNT_ID GROUP
123 A
124 B
125 A
</code></pre>
<p>and then do a value count of GROUP, but I'm unsure of how to approach this. I did find an ugly way to do this, but I'm new to pandas from using R so I'm guessing there's a more straightforward way that I don't know yet...</p>
| 2 | 2016-08-26T17:49:06Z | 39,172,127 | <p>You can use the <code>nunique()</code> method after the grouping:</p>
<pre><code>df.groupby('GROUP')['CUSTOMER_ACCOUNT_ID'].nunique().reset_index()
# GROUP CUSTOMER_ACCOUNT_ID
# 0 A 2
# 1 B 1
</code></pre>
| 3 | 2016-08-26T17:55:07Z | [
"python",
"pandas",
"group-by"
] |
Pandas Python - get value counts by grouped values | 39,172,047 | <p>I have a situation where multiple customer ids can be belong to the same account, and all records are grouped in to one of two groups:</p>
<pre><code>CUSTOMER_ACCOUNT_ID CUSTOMER_ID GROUP
123 555 A
123 556 A
124 557 B
124 558 B
125 559 A
</code></pre>
<p>What I want to do is get the count of unique CUSTOMER_ACCOUNT_IDs belonging to each group. That is, I don't care how many customer_ids belong to an account, I just want to see how many accounts is in each group. I'm looking for this output</p>
<pre><code>GROUP COUNT
A 2
B 1
</code></pre>
<p>That is, number of unique accounts by group. One way of thinking of it is that I want to collapse or remove the CUSTOMER_ID dimension, so I'm left with</p>
<pre><code>CUSTOMER_ACCOUNT_ID GROUP
123 A
124 B
125 A
</code></pre>
<p>and then do a value count of GROUP, but I'm unsure of how to approach this. I did find an ugly way to do this, but I'm new to pandas from using R so I'm guessing there's a more straightforward way that I don't know yet...</p>
| 2 | 2016-08-26T17:49:06Z | 39,172,386 | <p>Is this what you want to achieve? </p>
<pre><code>In [103]: df.drop_duplicates(['CUSTOMER_ACCOUNT_ID', 'GROUP']).drop('CUSTOMER_ID', 1)
Out[103]:
CUSTOMER_ACCOUNT_ID GROUP
0 123 A
2 124 B
4 125 A
</code></pre>
| 2 | 2016-08-26T18:13:30Z | [
"python",
"pandas",
"group-by"
] |
Pandas dataframe replace | 39,172,068 | <p>New to Pandas and python and have a question on replacing multiple unicode characters within an entire data frame. Using python 2.7 and importing from an excel sheet. My desire is to replace all non-ascii characters with their ascii equivalent or nothing.</p>
<p>examples:<br>
u'SHOGUN JAPANESE \u2013 GRAND'<br>
u'COMFORT INN & SUITES\xa0STONE MOUNTAIN'</p>
<p>This works, but is cumbersome: </p>
<pre><code>rawdf = rawdf["Account_Name"].str.upper().str.replace(u'\u2013', ' ').str.replace(u'\xa0', '-') + "|" + rawdf["COID"].str.upper()
</code></pre>
<p>This did not work:</p>
<pre><code>rawdf = rawdf.replace(u'\u2013', ' ')
</code></pre>
| 2 | 2016-08-26T17:50:43Z | 39,172,455 | <p>You can do an encode/decode cycle like so:</p>
<pre><code>rawdf["Account_Name"].str..encode('ascii', 'ignore').str.decode('ascii')
</code></pre>
<p>The use of 'ignore' makes characters that cannot be represented in ascii be dropped. The intermediate representation is bytes, so we need to encode it back to strings again.</p>
| 1 | 2016-08-26T18:17:47Z | [
"python"
] |
Python writing to an xml file | 39,172,079 | <p>I am trying to write to an xml file. I have changed a specific element in my code, and am able to get it to print successfully. I need to have it written to the file, without changing the structure of the file.<br>
My code:</p>
<p>import os
from lxml import etree</p>
<pre><code>directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
if f.endswith(".xml"):
xmlfile = directory + '/' + f
tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()
hardwareRevisionNode = root.find(".//hardwareRevision")
if hardwareRevisionNode.text == "5":
print " "
print "Old Tag: " + hardwareRevisionNode.text
x = hardwareRevisionNode.text = "DVT2"
print "New Tag " + hardwareRevisionNode.text
</code></pre>
<p>When I try various methods of opening and closing the file, it just deletes all the data in the xml file. Using this method </p>
<pre><code>outfile = open(xmlfile, 'w')
oufile.write(etree.tostring(tree))
outfile.close()
</code></pre>
<p>Changed the code structure of my file to be one long line.</p>
| 1 | 2016-08-26T17:51:24Z | 39,172,181 | <p>To get newlines in the output file, it looks like you need to pass <a href="http://lxml.de/tutorial.html#serialisation" rel="nofollow"><code>pretty_print=True</code></a> to your sterilization (<code>write</code> or <code>tostring</code>) call.</p>
<p>Side note; Normally, when you open files with python you open them like this:</p>
<pre><code>with open('filename.ext', 'mode') as myfile:
myfile.write(mydata)
</code></pre>
<p>This way there is less risk of file descriptor leaks. The <a href="http://stackoverflow.com/a/3605831/1342445"><code>tree.write("filename.xml")</code></a> method looks like a nice and easy way to avoid dealing with the file entirely.</p>
| 1 | 2016-08-26T17:59:35Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
Python writing to an xml file | 39,172,079 | <p>I am trying to write to an xml file. I have changed a specific element in my code, and am able to get it to print successfully. I need to have it written to the file, without changing the structure of the file.<br>
My code:</p>
<p>import os
from lxml import etree</p>
<pre><code>directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
if f.endswith(".xml"):
xmlfile = directory + '/' + f
tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()
hardwareRevisionNode = root.find(".//hardwareRevision")
if hardwareRevisionNode.text == "5":
print " "
print "Old Tag: " + hardwareRevisionNode.text
x = hardwareRevisionNode.text = "DVT2"
print "New Tag " + hardwareRevisionNode.text
</code></pre>
<p>When I try various methods of opening and closing the file, it just deletes all the data in the xml file. Using this method </p>
<pre><code>outfile = open(xmlfile, 'w')
oufile.write(etree.tostring(tree))
outfile.close()
</code></pre>
<p>Changed the code structure of my file to be one long line.</p>
| 1 | 2016-08-26T17:51:24Z | 39,172,361 | <p>If you are wanting to replace a value within an existing XML file then use:</p>
<pre><code>tree.write(xmlfile)
</code></pre>
<p>Currently you are simply overwriting your file entirely and using the incorrect method (<code>open()</code>). <code>tree.write()</code> is normally what you would want to use. It might look something like this:</p>
<pre><code>tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()
hardwareRevisionNode = root.find(".//hardwareRevision")
if hardwareRevisionNode.text == "5":
print "Old Tag: " + hardwareRevisionNode.text
hardwareRevisionNode.text = "DVT2"
print "New Tag: " + hardwareRevisionNode.text
tree.write(xmlfile)
</code></pre>
<p>â³ <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">https://docs.python.org/2/library/xml.etree.elementtree.html</a></p>
| 1 | 2016-08-26T18:11:46Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
How can I dynamically create ttk widgets depending on the value entered in a ttk.entry box? | 39,172,143 | <p>I am trying to make a GUI where as soon as the user inputs an integer into a <code>ttk.entry</code> field, that many checkbuttons need to appear below it. For example, if they put "5" into the entry widget, 5 check buttons need to appear below the entry field.</p>
<p>Edit:</p>
<p>What I ended up using:</p>
<pre><code>self.number_of_stages = tk.IntVar()
self.check_box_dict={}
self.num_of_stages={}
self.stagetempvar={}
self.equipment_widgets={}
def centrifugal_compressor_widgets(self):
self.equipment_widgets.clear()
self.equipment_widgets["NumOfStagesLabelCentComp"]=tk.Label(self.parent, text="Number of Stages:", bg="white")
self.equipment_widgets["NumOfStagesLabelCentComp"].place(relx=0.5, y=260, anchor="center")
self.equipment_widgets["NumOfStagesEntryCentComp"]=ttk.Entry(self.parent, textvariable=self.number_of_stages)
self.equipment_widgets["NumOfStagesEntryCentComp"].place(relx=0.5, y=290, anchor="center")
def OnTraceCentComp(self, varname, elementname, mode):
for key in self.check_box_dict:
self.check_box_dict[key].destroy()
try:
if self.number_of_stages.get() <=15 :
i=1
self.stagetempvar.clear()
while i <= self.number_of_stages.get():
self.stagetempvar[i]=tk.StringVar()
self.stagetempvar[i].set("Closed")
self.check_box_dict[i]=ttk.Checkbutton(self.parent, text=i, offvalue="Closed", onvalue="Open",variable=self.stagetempvar[i])
self.check_box_dict[i].place(relx=(i*(1/(self.number_of_stages.get()+1))), y=360, anchor="center")
i+=1
except:
pass
</code></pre>
| -2 | 2016-08-26T17:56:27Z | 39,230,126 | <p>take a look at the below and let me know what you think...</p>
<p>A very ugly, super basic example:</p>
<pre><code>from Tkinter import *
root = Tk()
root.geometry('200x200')
root.grid_rowconfigure(0, weight = 1)
root.grid_columnconfigure(0, weight = 1)
win1 = Frame(root, bg= 'blue')
win1.grid(row=0, column=0, sticky='news')
number = IntVar()
entry = Entry(win1, textvariable = number)
entry.pack()
confirm = Button(win1, text = 'Press to create widgets...', command = lambda:create_widgets(number.get()))
confirm.pack()
def create_widgets(number):
for n in range(0,number):
Checkbutton(win1, text = 'Checkbutton number : %s' % n).pack()
root.mainloop()
</code></pre>
| 1 | 2016-08-30T14:22:33Z | [
"python",
"python-2.7",
"tkinter"
] |
Python: lxml not pretty-printing newly added nodes | 39,172,188 | <p>I'm using a Python script to add nodes (or copy existing nodes) in an XML file. The script uses lxml library. Here is existing snippet:</p>
<pre><code><entitlements>
<bpuiEnabledForSubusers>true</bpuiEnabledForSubusers>
<appCodesAllowedForSubusers>My Accounts,Bill Pay</appCodesAllowedForSubusers>
<enabled>true</enabled>
<monitored>true</monitored>
</entitlements>
</code></pre>
<p>So I use lxml to copy a node in the entitlements node. Then, when I </p>
<pre><code>return etree.tostring(self.root,encoding='unicode', pretty_print=True)
</code></pre>
<p>I get the following xml:</p>
<pre><code><entitlements>
<bpuiEnabledForSubusers>true</bpuiEnabledForSubusers>
<appCodesAllowedForSubusers>My Accounts,Bill Pay</appCodesAllowedForSubusers>
<enabled>true</enabled>
<monitored>true</monitored>
<appCodesAllowedForSubusersCopy>My Accounts,Bill Pay</appCodesAllowedForSubusersCopy></entitlements>
</code></pre>
<p>So the node is properly copied and added to the end of the child nodes, but in the XML it is not indented to the level of its siblings, and the parent's closing tag is on the same line, even though I used the pretty_print option. Although the resulting XML is technically correct, it does not "look good" according to our existing standards.</p>
<p>Any idea why this is happening?</p>
<p>Thanks...</p>
| 0 | 2016-08-26T17:59:50Z | 39,172,248 | <p><code>pretty_print=True</code> only has useful effect when your tree doesn't have trailing whitespace on the nodes already. Thus, you want to look at not just how your emit them, but how you're parsing them in the first place.</p>
<p>Use the <code>remove_blank_text=True</code> parser option:</p>
<pre><code>parser = etree.XMLParser(remove_blank_text=True)
</code></pre>
| 1 | 2016-08-26T18:03:45Z | [
"python",
"xml",
"lxml"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the output from the more nested parts of the code to be more nested. In the same way that this makes code easier to read, it would make the output easier to read. </p>
<p>Of course I could implement this manually, using e.g. <code>.format()</code>, but what I had in mind was a custom print function which would <code>print(i*' ' + string)</code> where <code>i</code> is the indentation level. This would be a quick way to make readable output on my terminal. </p>
<p>Is there a better way to do this which avoids painstaking manual formatting?</p>
| 139 | 2016-08-26T18:07:24Z | 39,172,459 | <pre><code>>>> import inspect
>>> help(inspect.indentsize)
Help on function indentsize in module inspect:
indentsize(line)
Return the indent size, in spaces, at the start of a line of text.
</code></pre>
| 5 | 2016-08-26T18:18:02Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the output from the more nested parts of the code to be more nested. In the same way that this makes code easier to read, it would make the output easier to read. </p>
<p>Of course I could implement this manually, using e.g. <code>.format()</code>, but what I had in mind was a custom print function which would <code>print(i*' ' + string)</code> where <code>i</code> is the indentation level. This would be a quick way to make readable output on my terminal. </p>
<p>Is there a better way to do this which avoids painstaking manual formatting?</p>
| 139 | 2016-08-26T18:07:24Z | 39,172,520 | <p>You can use <code>sys.current_frame.f_lineno</code> in order to get the line number. Then in order to find the number of indentation level you need to find the previous line with zero indentation then be subtracting the current line number from that line's number you'll get the number of indentation:</p>
<pre><code>import sys
current_frame = sys._getframe(0)
def get_ind_num():
with open(__file__) as f:
lines = f.readlines()
current_line_no = current_frame.f_lineno
to_current = lines[:current_line_no]
previous_zoro_ind = len(to_current) - next(i for i, line in enumerate(to_current[::-1]) if not line[0].isspace())
return current_line_no - previous_zoro_ind
</code></pre>
<p>Demo:</p>
<pre><code>if True:
print get_ind_num()
if True:
print(get_ind_num())
if True:
print(get_ind_num())
if True: print(get_ind_num())
# Output
1
3
5
6
</code></pre>
<p>If you want the number of the indentation level based on the previouse lines with <code>:</code> you can just do it with a little change:</p>
<pre><code>def get_ind_num():
with open(__file__) as f:
lines = f.readlines()
current_line_no = current_frame.f_lineno
to_current = lines[:current_line_no]
previous_zoro_ind = len(to_current) - next(i for i, line in enumerate(to_current[::-1]) if not line[0].isspace())
return sum(1 for line in lines[previous_zoro_ind-1:current_line_no] if line.strip().endswith(':'))
</code></pre>
<p>Demo:</p>
<pre><code>if True:
print get_ind_num()
if True:
print(get_ind_num())
if True:
print(get_ind_num())
if True: print(get_ind_num())
# Output
1
2
3
3
</code></pre>
<p>And as an alternative answer here is a function for getting the number of indentation (whitespace):</p>
<pre><code>import sys
from itertools import takewhile
current_frame = sys._getframe(0)
def get_ind_num():
with open(__file__) as f:
lines = f.readlines()
return sum(1 for _ in takewhile(str.isspace, lines[current_frame.f_lineno - 1]))
</code></pre>
| 9 | 2016-08-26T18:21:24Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the output from the more nested parts of the code to be more nested. In the same way that this makes code easier to read, it would make the output easier to read. </p>
<p>Of course I could implement this manually, using e.g. <code>.format()</code>, but what I had in mind was a custom print function which would <code>print(i*' ' + string)</code> where <code>i</code> is the indentation level. This would be a quick way to make readable output on my terminal. </p>
<p>Is there a better way to do this which avoids painstaking manual formatting?</p>
| 139 | 2016-08-26T18:07:24Z | 39,172,552 | <p>Yeah, that's definitely possible, here's a working example:</p>
<pre><code>import inspect
def get_indentation_level():
callerframerecord = inspect.stack()[1]
frame = callerframerecord[0]
info = inspect.getframeinfo(frame)
cc = info.code_context[0]
return len(cc) - len(cc.lstrip())
if 1:
print get_indentation_level()
if 1:
print get_indentation_level()
if 1:
print get_indentation_level()
</code></pre>
| 22 | 2016-08-26T18:23:18Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the output from the more nested parts of the code to be more nested. In the same way that this makes code easier to read, it would make the output easier to read. </p>
<p>Of course I could implement this manually, using e.g. <code>.format()</code>, but what I had in mind was a custom print function which would <code>print(i*' ' + string)</code> where <code>i</code> is the indentation level. This would be a quick way to make readable output on my terminal. </p>
<p>Is there a better way to do this which avoids painstaking manual formatting?</p>
| 139 | 2016-08-26T18:07:24Z | 39,172,845 | <p>If you want indentation in terms of nesting level rather than spaces and tabs, things get tricky. For example, in the following code:</p>
<pre><code>if True:
print(
get_nesting_level())
</code></pre>
<p>the call to <code>get_nesting_level</code> is actually nested one level deep, despite the fact that there is no leading whitespace on the line of the <code>get_nesting_level</code> call. Meanwhile, in the following code:</p>
<pre><code>print(1,
2,
get_nesting_level())
</code></pre>
<p>the call to <code>get_nesting_level</code> is nested zero levels deep, despite the presence of leading whitespace on its line.</p>
<p>In the following code:</p>
<pre><code>if True:
if True:
print(get_nesting_level())
if True:
print(get_nesting_level())
</code></pre>
<p>the two calls to <code>get_nesting_level</code> are at different nesting levels, despite the fact that the leading whitespace is identical.</p>
<p>In the following code:</p>
<pre><code>if True: print(get_nesting_level())
</code></pre>
<p>is that nested zero levels, or one? In terms of <code>INDENT</code> and <code>DEDENT</code> tokens in the formal grammar, it's zero levels deep, but you might not feel the same way.</p>
<hr>
<p>If you want to do this, you're going to have to tokenize the whole file up to the point of the call and count <code>INDENT</code> and <code>DEDENT</code> tokens. The <a href="https://docs.python.org/2/library/tokenize.html"><code>tokenize</code></a> module would be very useful for such a function:</p>
<pre><code>import inspect
import tokenize
def get_nesting_level():
caller_frame = inspect.currentframe().f_back
filename, caller_lineno, _, _, _ = inspect.getframeinfo(caller_frame)
with open(filename) as f:
indentation_level = 0
for token_record in tokenize.generate_tokens(f.readline):
token_type, _, (token_lineno, _), _, _ = token_record
if token_lineno > caller_lineno:
break
elif token_type == tokenize.INDENT:
indentation_level += 1
elif token_type == tokenize.DEDENT:
indentation_level -= 1
return indentation_level
</code></pre>
| 104 | 2016-08-26T18:41:27Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the output from the more nested parts of the code to be more nested. In the same way that this makes code easier to read, it would make the output easier to read. </p>
<p>Of course I could implement this manually, using e.g. <code>.format()</code>, but what I had in mind was a custom print function which would <code>print(i*' ' + string)</code> where <code>i</code> is the indentation level. This would be a quick way to make readable output on my terminal. </p>
<p>Is there a better way to do this which avoids painstaking manual formatting?</p>
| 139 | 2016-08-26T18:07:24Z | 39,191,937 | <p>To solve the ârealâ problem that lead to your question you could implement a contextmanager which keeps track of the indention level and make the <code>with</code> block structure in the code correspond to the indentation levels of the output. This way the code indentation still reflects the output indentation without coupling both too much. It is still possible to refactor the code into different functions and have other indentations based on code structure not messing with the output indentation.</p>
<pre><code>#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function
class IndentedPrinter(object):
def __init__(self, level=0, indent_with=' '):
self.level = level
self.indent_with = indent_with
def __enter__(self):
self.level += 1
return self
def __exit__(self, *_args):
self.level -= 1
def print(self, arg='', *args, **kwargs):
print(self.indent_with * self.level + str(arg), *args, **kwargs)
def main():
indented = IndentedPrinter()
indented.print(indented.level)
with indented:
indented.print(indented.level)
with indented:
indented.print('Hallo', indented.level)
with indented:
indented.print(indented.level)
indented.print('and back one level', indented.level)
if __name__ == '__main__':
main()
</code></pre>
<p>Output:</p>
<pre><code>0
1
Hallo 2
3
and back one level 2
</code></pre>
| 6 | 2016-08-28T13:46:19Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Script to check a page | 39,172,390 | <p>I have a script that alerts me by mail when a phrase changes on a web page. I tried many things, but I can't fix the <strong>isAvailable()</strong> function: the script says "not available" every time, whether or not I give it an available server. Have you any clues?</p>
<pre><code># CONFIG
TARGET_KIMSUFI_ID = "160sk1" # something like 160sk1
TARGET_DESCR = ""
EMAIL_FROM_ADDRS = ""
EMAIL_TO_ADRS = ""
EMAIL_SMTP_LOGIN = EMAIL_FROM_ADDRS
EMAIL_SMTP_PASSWD = ""
EMAIL_SMTP_SERVER = ""
# CODE
import urllib.request
import smtplib
import time
def isAvailable():
rawPageContent = urllib.request.urlopen("https://www.kimsufi.com/en/servers.xml").read()
rawPageContent = str(rawPageContent)
poz = rawPageContent.find(TARGET_KIMSUFI_ID)
row = rawPageContent[poz:]
poz = row.find("</tr>")
row = row[:poz]
searchText = "Currently being replenished"
poz = row.find(searchText)
return poz != -1
def sendEmailWithMessageAvailable():
msg = "From: KIMSUFI HUNTER <"+EMAIL_FROM_ADDRS+">\r\n"+\
"To: "+EMAIL_TO_ADRS+"\r\n"+\
"Subject: [KIMSUFI] "+TARGET_DESCR+" is now AVAILABLE!\r\n"+\
"\r\n"+\
"kimsufi-hunter.py has detected that "+TARGET_DESCR+" is now ["+time.ctime()+"] available!\r\n"+\
"https://www.kimsufi.com/en/\r\n"
server = smtplib.SMTP(EMAIL_SMTP_SERVER)
server.starttls()
server.login(EMAIL_SMTP_LOGIN,EMAIL_SMTP_PASSWD)
server.sendmail(EMAIL_FROM_ADDRS, EMAIL_TO_ADRS, msg)
server.quit()
while True:
if isAvailable():
print(time.ctime() + " -- KIMSUFI "+TARGET_DESCR+" not available")
nextSleep = 5 #5secs
else:
print(time.ctime() + " -- KIMSUFI "+TARGET_DESCR+" AVAILABLE!!! -- sleeping for 5 minutes")
sendEmailWithMessageAvailable()
nextSleep = 5*60 #5mins
time.sleep(nextSleep)
</code></pre>
| -1 | 2016-08-26T18:13:46Z | 39,173,556 | <p>Your <code>isAvailable()</code> function returns <code>True</code> if the website is available, <code>False</code> otherwise. You should change the <code>if</code> statement to:</p>
<pre><code>if not isAvailable():
...
</code></pre>
| 1 | 2016-08-26T19:33:32Z | [
"python"
] |
How to save a pandas dataframe such that there is no delimiter? | 39,172,403 | <p>I have the following pandas dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))
X Y Z
0 1 0 1
1 1 1 0
2 0 0 0
3 0 1 1
4 0 1 1
5 1 1 1
</code></pre>
<p>Let's say I take the transpose and wish to save it</p>
<pre><code>df = df.T
0 1 2 3 4 5
X 1 1 0 0 0 1
Y 0 1 0 1 1 1
Z 1 0 0 1 1 1
</code></pre>
<p>So, there three rows. I would like to save it in this format:</p>
<pre><code>X 110001
Y 010111
Z 100111
</code></pre>
<p>I tried </p>
<pre><code>df.to_csv("filename.txt", header=None, index=None, sep='')
</code></pre>
<p>However, this outputs an error: </p>
<pre><code>TypeError: "delimiter" must be an 1-character string
</code></pre>
<p>Is it possible to save the dataframe in this manner, or is there some what to combine all columns into one? What is the most "pandas" solution?</p>
| 2 | 2016-08-26T18:14:39Z | 39,172,436 | <p>Leave original <code>df</code> alone. Don't transpose.</p>
<pre><code>df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))
df.astype(str).apply(''.join)
X 101100
Y 101001
Z 111110
dtype: object
</code></pre>
| 2 | 2016-08-26T18:16:54Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
How to save a pandas dataframe such that there is no delimiter? | 39,172,403 | <p>I have the following pandas dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))
X Y Z
0 1 0 1
1 1 1 0
2 0 0 0
3 0 1 1
4 0 1 1
5 1 1 1
</code></pre>
<p>Let's say I take the transpose and wish to save it</p>
<pre><code>df = df.T
0 1 2 3 4 5
X 1 1 0 0 0 1
Y 0 1 0 1 1 1
Z 1 0 0 1 1 1
</code></pre>
<p>So, there three rows. I would like to save it in this format:</p>
<pre><code>X 110001
Y 010111
Z 100111
</code></pre>
<p>I tried </p>
<pre><code>df.to_csv("filename.txt", header=None, index=None, sep='')
</code></pre>
<p>However, this outputs an error: </p>
<pre><code>TypeError: "delimiter" must be an 1-character string
</code></pre>
<p>Is it possible to save the dataframe in this manner, or is there some what to combine all columns into one? What is the most "pandas" solution?</p>
| 2 | 2016-08-26T18:14:39Z | 39,172,527 | <p>If you do want to transpose, then you can do something like this:</p>
<pre><code>In [126]: df.T.apply(lambda row: ''.join(map(str, row)), axis=1)
Out[126]:
X 001111
Y 000000
Z 010010
dtype: object
</code></pre>
| 1 | 2016-08-26T18:21:36Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
How to include your hostname in the IPython 5 prompt? | 39,172,421 | <p>In previous version of IPython it was easy to include your hostname in the prompt, by including the following in your config:</p>
<pre><code>c.PromptManager.in_template = '(\H) In [\\#]: '
</code></pre>
<p>(the <code>\H</code> would be substituted with your hostname).</p>
<p>However, the <code>PromptManager</code> config has been removed in IPython 5. I see the following warning when I try to use it:</p>
<pre><code>/env/lib/python2.7/site-packages/IPython/core/interactiveshell.py:448: UserWarning: As of IPython 5.0 `PromptManager` config will have no effect and has been replaced by TerminalInteractiveShell.prompts_class
warn('As of IPython 5.0 `PromptManager` config will have no effect'
</code></pre>
<p>So how do I achieve a similar effect with IPython 5?</p>
| 1 | 2016-08-26T18:15:56Z | 39,172,422 | <p>As the warning indicates, you should use the new <code>TerminalInteractiveShell.prompts_class</code>. So to include your hostname in your prompt you can drop the following in your config:</p>
<pre><code>from IPython.terminal.prompts import Prompts, Token
import socket
class MyPrompt(Prompts):
def __init__(self, *args, **kwargs):
hn = socket.gethostname()
self._in_txt = '({}) In ['.format(hn)
self._out_txt = '({}) Out['.format(hn)
super(MyPrompt, self).__init__(*args, **kwargs)
def in_prompt_tokens(self, cli=None):
return [
(Token.Prompt, self._in_txt),
(Token.PromptNum, str(self.shell.execution_count)),
(Token.Prompt, ']: '),
]
def out_prompt_tokens(self):
return [
(Token.OutPrompt, self._out_txt),
(Token.OutPromptNum, str(self.shell.execution_count)),
(Token.OutPrompt, ']: '),
]
</code></pre>
<p>Results in the following prompt:</p>
<pre><code>(marv) In [1]: 'hello, world'
(marv) Out[1]: 'hello, world'
</code></pre>
| 2 | 2016-08-26T18:15:56Z | [
"python",
"ipython"
] |
Python Update random field choice function from OrderedDict Class | 39,172,467 | <p>I'm trying to do a script that choose a string and update a current field, but for some reason the code doesn't update the last value when calling my <code>changerandom</code> function in the <code>Greeting</code> class.</p>
<pre><code>...[snip]...
class Greeting(Packet):
fields = OrderedDict([
("Morning", "Hi"),
("Afternoon", "Good Afternoon!"),
("Evening", "Good Evening!"),
])
def change(self):
self.fields["Morning"] = "Good morning!"
def changerandom(self, n = 1):
function=[
{self.fields["Morning"]: "Hello!"},
{self.fields["Morning"]: "Bonjorno!"},
{self.fields["Morning"]: "Hola!"},
]
result = {}
for i in range(n):
result.update(choice(function))
print "Updated string:",result
return result
text = Greeting()
print text
text.change()
print text
text.changerandom()
print text
</code></pre>
<p>My code return the following:</p>
<pre><code>Hi
Good morning!
Updated string: {'Good morning!': 'Hola!'}
Good morning!
</code></pre>
<p>While it should have returned:</p>
<pre><code>Hi
Good morning!
Hola!
</code></pre>
<p>I'm not sure what i'm missing here, I don't see why I cannot update the last field.
Any help would be greatly appreciated!</p>
| 0 | 2016-08-26T18:18:25Z | 39,172,687 | <p>The problem is that you're <code>return</code>ing a result, without assigning it anywhere.</p>
<p>You also use the <em>value</em> of <code>fields</code>, rather than the <em>key</em>. So, your code should be something like </p>
<pre><code>def changerandom(self, n = 1):
function=[
{"Morning": "Hello!"},
{"Morning": "Bonjorno!"},
{"Morning": "Hola!"},
]
for i in range(n):
result = choice(function)
self.fields.update(result)
print "Updated string:",result
return result
</code></pre>
<p>Note that we're using <code>self.fields.update</code>, and we're no longer <code>return</code>ing anything.</p>
<p>Generally, it's good practice for your functions and methods to <em>return</em> something, or <em>change something</em>, but never both.</p>
| 0 | 2016-08-26T18:30:25Z | [
"python",
"string",
"function"
] |
Python: How to interpolate errors using scipy interpolate.interp1d | 39,172,559 | <p>I have a number of data sets, each containing <em>x, y</em>, and <em>y_error</em> values, and I'm simply trying to calculate the average value of <em>y</em> at each <em>x</em> across these data sets. However the data sets are not quite the same length. I thought the best way to get them to an equal length would be to use scipy's <code>interoplate.interp1d</code> for each data set. However, I still need to be able to calculate the error on each of these averaged values, and I'm quite lost on how to accomplish that after doing an interpolation.</p>
<p>I'm pretty new to Python and coding in general, so I appreciate your help!</p>
| 0 | 2016-08-26T18:23:45Z | 39,174,418 | <p>As long as you can assume that your errors represent one-sigma intervals of normal distributions, you can always generate synthetic datasets, resample and interpolate those, and compute the 1-sigma errors of the results.</p>
<p>Or just interpolate values+err and values-err, if all you need is a quick and dirty rough estimate.</p>
| 0 | 2016-08-26T20:47:17Z | [
"python",
"scipy",
"interpolation"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at the same item in memory that <code>l</code> was pointing at. So why is it that in the last 3 lines, <code>h</code> and <code>l</code> don't give the same results?</p>
| 6 | 2016-08-26T18:24:03Z | 39,172,629 | <p>That's quite simple to check, run this simple test:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
print id(h), id(l)
h = h * 2
print id(h), id(l)
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>As you can see because of the line <code>h = h * 2</code>, the h's id has been changed</p>
<p>Why is this? When you're using <code>*</code> operator it will be created a new list (new memory space). In your case this new list is being assigned to the old h reference, that's why you can see the id is different after <code>h = h * 2</code></p>
<p>If you want to know more about this subject, make sure you look at <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow">Data Model</a> link.</p>
| 6 | 2016-08-26T18:27:01Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at the same item in memory that <code>l</code> was pointing at. So why is it that in the last 3 lines, <code>h</code> and <code>l</code> don't give the same results?</p>
| 6 | 2016-08-26T18:24:03Z | 39,172,678 | <p>Anytime you assign to a variable, its identity (memory address) generally changes - the only reason why it wouldn't change is that you happened to assign it the value that it already held. So, your statement <code>h = h * 2</code> caused h to become an entirely new object - one whose value happened to be based on the previous value of h, but that's not actually relevant to its identity.</p>
| 1 | 2016-08-26T18:29:55Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at the same item in memory that <code>l</code> was pointing at. So why is it that in the last 3 lines, <code>h</code> and <code>l</code> don't give the same results?</p>
| 6 | 2016-08-26T18:24:03Z | 39,172,680 | <p>The assignment does make <strong>h</strong> point to the same item as <strong>l</strong>. However, it does not permanently weld the two. When you change <strong>h</strong> with <strong>h = h * 2</strong>, you tell Python to build a doubled version elsewhere in memory, and then make <strong>h</strong> point to the doubled version. You haven't given any instructions to change <strong>l</strong>; that still points to the original item.</p>
| 2 | 2016-08-26T18:29:56Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at the same item in memory that <code>l</code> was pointing at. So why is it that in the last 3 lines, <code>h</code> and <code>l</code> don't give the same results?</p>
| 6 | 2016-08-26T18:24:03Z | 39,172,773 | <p><code>h = h * 2</code> assigns <code>h</code> to a new list object.</p>
<p>You probably want to modify <code>h</code> <em>in-place</em>: </p>
<pre><code>h *= 2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3, 9, 5, 1, 3]
</code></pre>
| 4 | 2016-08-26T18:35:55Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at the same item in memory that <code>l</code> was pointing at. So why is it that in the last 3 lines, <code>h</code> and <code>l</code> don't give the same results?</p>
| 6 | 2016-08-26T18:24:03Z | 39,172,841 | <p>It's tricky, but when you multiply a list, you are creating a new list.</p>
<pre><code>l = [1, 5, 9, 3]
h = l
</code></pre>
<p>'l' and 'h' are now referring to the same list in memory.</p>
<pre><code>h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>You swapped the values in <code>h</code>, so the values are changed in <code>l</code>. This makes sense when you think about them as different names for <em>the same object</em></p>
<pre><code>h = h * 2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>When multiplying <code>h * 2</code>, you are creating a <em>new list</em>, so now only <code>l</code> will be the original list object.</p>
<pre><code>>>> l = [1, 5, 9, 3]
>>> h = l
>>> id(h) == id(l)
True
>>> id(h)
139753623282464
>>> h = h * 2
>>> id(h) == id(l)
False
>>> id(h)
139753624022264
</code></pre>
<p>See how the <code>id</code> of <code>h</code> changes after the multiplication? The <code>*</code> operator creates a new list, unlike other list operation, such as <code>append()</code> which alter the current list.</p>
<pre><code>>>> h.append(1000)
>>> id(h)
139753623282464 # same as above!
</code></pre>
<p>Hope this helps!</p>
| 1 | 2016-08-26T18:41:04Z | [
"python",
"pointers"
] |
Pandas concatenation of multiple dataframes returns null values | 39,172,575 | <p>I have a dataframe (<code>df</code>), that I break down into 4 new dfs (<code>media</code>, <code>client</code>, <code>code_type</code>, and <code>date</code>). <code>media</code> has one column of null values, while the other three are only 1-dim dfs, each consisting of nulls. After replacing the nulls in each dataframe, I try to <code>pd.concat</code>to get a single df and get the result below.</p>
<pre><code> code_type
0 P
1 P
2 P
3 P
4 P
5 P
code_name media_type acq. revenue
0 RASH NaN 50.0 34004.0
1 100 NaN 10.0 1035.0
2 NEWS NaN 61.0 3475.0
3 DR NaN 53.0 4307.0
4 SPORTS NaN 45.0 6503.0
5 DOUBL NaN 13.0 4205.0
client_id
0 2.0
1 2.0
2 2.0
3 2.0
4 2.0
5 2.0
date
0 2016-08-15
1 2016-08-15
2 2016-08-15
3 2016-08-15
4 2016-08-15
5 2016-08-15
</code></pre>
<p>I <code>pd.merge</code> <code>media</code> with another a separate df to replace the NaNs under <code>media.media_type</code>, which appends a new <code>media_type_y</code></p>
<pre><code>code_name media_type_x acq. revenue media_type_y
0 RASH NaN 282 34004.0 Radio
1 100 NaN 119 1035.0 NaN
2 NEWS NaN 81 3475.0 SiriusXM
3 DR NaN 33 4307.0 SiriusXM
4 SPORTS NaN 25 6503.0 SiriusXM
5 DOUBL NaN 23 4205.0 Podcast
</code></pre>
<p>I then drop <code>media_type_x</code> and rename <code>media_type_y</code> to just <code>media_type</code></p>
<pre><code>final = m.loc[:,('code_name','media_type_y', 'acquisition', 'revenue')]
final = final.rename(columns={'media_type_y': 'media_type'})
</code></pre>
<p>So that when I concatenate, I have a complete df.</p>
<pre><code>clean = pd.concat([media, client, code_type, date], axis=1)
code media acq. revenue client code_type date
0 RASH Radio 50.0 34004.0 NaN NaN NaT
1 100 NaN 10.0 1035.0 NaN NaN NaT
2 NEWS SiriusXM 61.0 3475.0 NaN NaN NaT
3 DR SiriusXM 53.0 4307.0 NaN NaN NaT
4 SPORTS SiriusXM 45.0 6503.0 NaN NaN NaT
5 DOUBL Podcast 13.0 4205.0 NaN NaN NaT
</code></pre>
<p><br><code>clean.client</code> is supposed to be all <code>2</code>
<br><code>clean.code_type</code> should be all <code>P</code>
<br><code>clean.date</code> should be all <code>08/15/2016</code> </p>
<p>The dfs by themselves show the data, it's only when I concatenate that I lose the information. I think it may be something with the indexes, but I'm not sure. Could also be something to do with the fact that I have a column with both <code>str</code> and <code>int</code> (see <code>clean.code</code> above) which might be why I get the runtime error listed below.</p>
<blockquote>
<p>//anaconda/lib/python3.5/site-packages/pandas/indexes/api.py:71: RuntimeWarning: unorderable types: int() < str(), sort order is undefined for incomparable objects
result = result.union(other)</p>
</blockquote>
| 1 | 2016-08-26T18:24:40Z | 39,172,992 | <p>Starting with this:</p>
<pre><code> code_name media_type acq. revenue
0 RASH Radio 50.0 34004.0
1 100 NaN 10.0 1035.0
2 NEWS SiriusXM 61.0 3475.0
3 DR SiriusXM 53.0 4307.0
4 SPORTS SiriusXM 45.0 6503.0
5 DOUBL Podcast 13.0 4205.0
</code></pre>
<p>Try this: </p>
<pre><code>df['client_id'] = 2
df['date'] = '08/15/2016'
df['code_type'] = 'P'
df
code_name media_type acq. revenue client_id date code_type
0 RASH Radio 50.0 34004.0 2 08/15/2016 P
1 100 NaN 10.0 1035.0 2 08/15/2016 P
2 NEWS SiriusXM 61.0 3475.0 2 08/15/2016 P
3 DR SiriusXM 53.0 4307.0 2 08/15/2016 P
4 SPORTS SiriusXM 45.0 6503.0 2 08/15/2016 P
5 DOUBL Podcast 13.0 4205.0 2 08/15/2016 P
</code></pre>
| 0 | 2016-08-26T18:53:03Z | [
"python",
"pandas",
"concatenation"
] |
Xlxswriter - Change Date format from str to date | 39,172,576 | <p>I am having trouble changing the date format of date column in the dataframe i created using Xlsxwriter. The current format is 3/31/2016 12:00:00 AM, which i thought python is reading a date and adding a time to it. I would like the format to simply be dd/mm/yyyy with know time associate with it for all of column A. </p>
<p>Here is my code:</p>
<pre><code>date_format= workbook.add_format({'num_format': 'mmm d yyyy'})
date_time= dt.datetime.strftime("%m/%d/%Y")
worksheet.write_datetime(0,0, date_time, date_format)
</code></pre>
<p>The error message i get is : TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'</p>
| 2 | 2016-08-26T18:24:41Z | 39,173,220 | <h2><code>datetime.strftime</code> is for converting datetimes into strings</h2>
<p>You are not giving it a datetime object to convert.</p>
<pre><code>from datetime import datetime
today = datetime.today() # this returns a datetime object
today.strftime("%m/%d/%Y") # this returns a string
datetime.strftime(today, "%m/%d/%Y") # alternative way to call it
</code></pre>
<h2>However, you actually need to pass a datetime object to <code>worksheet.write_datetime</code></h2>
<p>So in my example it would be like this</p>
<pre><code>today = datetime.today()
date_format= workbook.add_format({'num_format': 'mmm d yyyy'})
worksheet.write_datetime(0, 0, today, date_format)
</code></pre>
<h2>To parse a date from a string use date time.strptime</h2>
<pre><code>dateobj = date time.strptime(datestr)
</code></pre>
| 1 | 2016-08-26T19:08:57Z | [
"python",
"datetime",
"xlsxwriter"
] |
SQLAlchemy table property takes exactly 2 arguments (1 given) | 39,172,703 | <p>I have the following SQLAlchemy class:</p>
<pre><code>class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
password = db.Column(db.String(100))
@property
def encrypt_password(self, password):
self.password = hash_password(password)
</code></pre>
<p>When I use the property I get the error <code>encrypt_password() takes exactly 2 arguments (1 given)</code>.</p>
<pre><code>user = db.session.query(User).filter_by(id=id).one()
user.encrypt_password('mypassword')
</code></pre>
<p>Why doesn't this work? How do I implement a property for setting the password?</p>
| -1 | 2016-08-26T18:31:27Z | 39,172,788 | <p>You defined the <code>getter</code> for the property as the <code>setter</code>. Either remove the <a href="https://docs.python.org/3/library/functions.html#property" rel="nofollow"><code>property</code></a> because this is a function, or define the property correctly.</p>
<p>If you're going the property route, rename the <code>password</code> attribute and access it through the property for the getter. Use a <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/hybrid.html" rel="nofollow"><code>hybrid_property</code></a> so that the column is still queryable directly.</p>
<pre><code>from sqlalchemy.ext.hybrid import hybrid_property
_password = db.Column('password', db.String)
@hybrid_property
def password(self):
return self._password
@password.setter
def password(self, value):
self._password = hash_password(value)
</code></pre>
<pre><code>user.password = 'stack overflow' # gets hashed
user.password # hashed value
session.query(User).filter(User.password.is_(None)) # query for users without passwords
</code></pre>
| 0 | 2016-08-26T18:36:58Z | [
"python",
"sqlalchemy"
] |
Need help ignoring button press. Tkinter | 39,172,727 | <p>I am working on making a stopwatch program. I can't get the start button to do nothing if the timer is already running. </p>
<p>When I search, I see the same <a href="http://code.activestate.com/recipes/124894-stopwatch-in-tkinter/" rel="nofollow">14 year old code</a>. I'd find it hard to believe that all these individuals in the past 14 years have independently arrived at the same solution. </p>
<p>As a beginner, I'd really like to know what I'm doing wrong with what I've written instead of copy/pasting and moving on. </p>
<pre><code>from tkinter import *
import time
import datetime
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title('Stopwatch')
self.pack(fill=BOTH, expand=1)
quit_button = Button(self, text = 'Quit', command = self.client_exit)
quit_button.config(width = 9)
quit_button.place(x=230)
start_button = Button(self, text = 'Start', command = self.timer_start)
start_button.config(width= 10)
start_button.place(x=0, y=0)
stop_button = Button(self, text = 'Stop', command = self.timer_stop)
stop_button.config(width = 10)
stop_button.place(x=80)
reset_button = Button(self, text = 'Reset', command = self.timer_reset)
reset_button.config(width = 10)
reset_button.place(x=160)
self.is_timer_running = False
def client_exit(self):
exit()
def timer_start(self):
global sec1
sec1 = time.time()
if self.is_timer_running == False:
self.is_timer_running = True
def tick():
if self.is_timer_running == True:
sec = time.time()
sec = datetime.timedelta(seconds = sec - sec1)
clock['text'] = sec
clock.after(100, tick)
tick()
def timer_stop(self):
stop_time = time.time()
if self.is_timer_running == True:
self.is_timer_running = False
def tick_stop():
stop = datetime.timedelta(seconds = stop_time - sec1)
clock['text'] = stop
tick_stop()
def timer_reset(self):
self.is_timer_running = False
clock['text'] = '00:00:00'
</code></pre>
| 3 | 2016-08-26T18:32:55Z | 39,172,894 | <p>Set the state of the button to disabled immediately after it's clicked (make sure to update it), and then set it back to normal when the timer stops running.</p>
<pre><code>start_button.config(state = 'disabled')
start_button.update()
# do whatever you need to do i.e run the stop watch
start_button.update()
start_button.config(state = 'normal')
</code></pre>
<p>And thanks to @NickBonne for further clarification :)</p>
<blockquote>
<p>You need to add <code>self.start_button = start_button</code> and <code>self.stop_button = stop_button</code> in <code>init_window()</code>. Then you can use <code>self.start_button.config(state="disabled")</code></p>
</blockquote>
| 4 | 2016-08-26T18:44:45Z | [
"python"
] |
same binary image - different in python & matlab | 39,172,816 | <p>OK. I'm thoroughly confused. I have a binary image. The values are (allegedly) 0 and 1. I read it in Matlab, to verify:</p>
<pre><code>binaryImage = imread('binary.png');
</code></pre>
<p>I get the max and min values, and the values are 1 and 0, respectively.</p>
<pre><code>maxValue = max(binaryImage(:));
minValue = max(binaryImage(:));
</code></pre>
<p>I take the same exact binary image, and read it in Python...</p>
<pre><code>from scipy.misc import imread
</code></pre>
<p>to get the pixel values we flatten it</p>
<pre><code>li = img.flatten()
# check each value
for s in li:
print s
</code></pre>
<p>The values, according to Python, are 0 and <strong>255</strong>.</p>
<p>So... does this mean if I use C++ (ITK) I will get a different value? If I use OpenCV I will get a different value? (Technically the "on" values should only be 1 and 255, but you know what I mean.)</p>
<p>If the pixel is "on" (white), and I set the value to 1 (in a binary image), no matter what language I read it in, I expect to see <strong>1</strong> for that value.</p>
<p>How come it's different?</p>
<p>Thanks!</p>
| 0 | 2016-08-26T18:39:15Z | 39,172,965 | <p>matlab supports logical arrays and scipy converts the image to grayscale. Depending on what you want to do you can convert the grayscale image to logicals</p>
<pre><code>bit_img = img > 127
</code></pre>
<p>or convert the logical array to int8 in matlab</p>
<pre><code>img = int8(binary_image) * 255
</code></pre>
| 0 | 2016-08-26T18:50:54Z | [
"python",
"matlab",
"image-processing"
] |
Django queryset "using()" method for specifying database doesn't work on related_name queries | 39,172,828 | <p>I've noticed something strange in Django that I haven't been able figure out. Let's say I have a Django application (I'm using 1.7) with two models like so:</p>
<pre><code>class Bookstore(models.Model):
name = models.CharField(max_length=50)
class Book(models.Model):
title = models.CharField(max_length=100)
store = models.ForeignKey(Bookstore, on_delete=models.PROTECT, related_name='books')
</code></pre>
<p>And then let's say I have two databases storing the data, perhaps a master-replica setup -- let's say the master is denoted as <code>default</code> in my settings file and the replica is <code>replica</code>. If I do the following query, I get an exception saying</p>
<blockquote>
<p>the current database router prevents this relation</p>
</blockquote>
<pre><code>store = Bookstore.objects.using('default').get(id=1)
first_book = store.books.using('replica').all().order_by('id')[0]
</code></pre>
<p>However, the following, which should be the same query, works just fine:</p>
<pre><code>store = Bookstore.objects.using('default').get(id=1)
first_book = Book.objects.using('replica').filter(store=store).order_by('id')[0]
</code></pre>
<p>What's going on here? Is there anyway to use the related_name lookup like the first example but have it work properly? Thanks!</p>
| 2 | 2016-08-26T18:39:57Z | 39,173,895 | <p>Look at SQL from first example (without <code>using()</code>):</p>
<pre><code>SELECT "book"."id", "book"."title", "book"."store_id"
FROM "book" JOIN "bookstore" ON "book"."store_id" = "bookstore"."id"
WHERE "bookstore"."id" = 1
ORDER BY "book"."id"
LIMIT 1
</code></pre>
<p>Do You see the problem? You cannot do a <code>SELECT</code> on two databases.</p>
<p>And look at SQL from second example:</p>
<pre><code>SELECT "book"."id", "book"."title", "book"."store_id"
FROM "book"
WHERE "book"."store_id" = 1
ORDER BY "book"."id"
LIMIT 1
</code></pre>
<p>Select data from one table.</p>
| 0 | 2016-08-26T20:00:58Z | [
"python",
"django"
] |
Why don't work linkClicked, and works linkHovered PyQt4? | 39,172,849 | <p>Here is some code. I created modal window, set easy html, and then I want to connect some method on click link. Signal "linkClicked" dont works , but link are loaded. And signal <strong>linkHovered</strong> works. Where is mistake? And how to include some method to "linkClicked"?</p>
<pre><code># -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtWebKit
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(1000, 500)
self.menu_bar = self.menuBar()
self.menuEngine()
def menuEngine(self):
self.podmenu2 = self.menu_bar.addMenu("Help")
self.about = QtGui.QAction("About", self )
self.about.setIconVisibleInMenu(True)
self.podmenu2.addAction(self.about)
self.about.triggered.connect(self.aboutView)
def aboutView(self):
def clicks(url):
print("DDD")
print(url)
mod_window = QtGui.QWidget(self, QtCore.Qt.Window)
mod_window.setWindowTitle("About")
mod_window.resize(500, 332)
horLayout = QtGui.QHBoxLayout(mod_window)
localHtmls = QtWebKit.QWebView()
localHtmls.setHtml("""
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div>
<br/>
Home page <a href="https://google.com">LINK</a>
</div>
</body>
</html>
""")
horLayout.addWidget(localHtmls)
localHtmls.linkClicked.connect(clicks)
#localHtmls.page().linkHovered.connect(clicks)
mod_window.show()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
windows = MainWindow()
windows.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-08-26T18:41:33Z | 39,173,826 | <p>From the documentation for <a href="http://doc.qt.io/qt-4.8/qwebview.html#linkClicked" rel="nofollow">linkClicked</a>:</p>
<blockquote>
<p>This signal is emitted whenever the user clicks on a link and the
page's linkDelegationPolicy property is set to delegate the link
handling for the specified url.</p>
</blockquote>
<p>So try:</p>
<pre><code>localHtmls.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
</code></pre>
<p>But note that this completely bypasses the normal link-click handling, so you will have to implement that yourself (e.g. call <code>load(url)</code>).</p>
| 1 | 2016-08-26T19:55:06Z | [
"python",
"pyqt4",
"qtwebkit",
"qwebview"
] |
Python Openpyxl, copy and paste cell range | 39,172,937 | <p>I know how to select a cell range in Openpyxl:</p>
<pre><code>cell_range = sheet['A1':'C3']
</code></pre>
<p>How can I paste cell_range above to another range, like <code>sheet['A11':'C13']</code>?</p>
| 0 | 2016-08-26T18:48:32Z | 39,173,627 | <p>I don't think there is a slicing notation exactly as described in your example, mostly because <code>openpyxl</code> uses lists of <code>Cell</code>s rather than lists of plain values.</p>
<p>Here is the basic flow I would use to grab just a part of a sheet.</p>
<pre><code>>>> wb = openpyxl.load_workbook(file_name)
>>> sheet = wb.worksheets[0]
>>> rows = sheet.rows[1:3] # slice rows
>>> foobar = [cell.value for row in rows for cell in row[3:10]] # slice row
</code></pre>
<p><strong><em>EDIT:</em></strong> From <a href="http://stackoverflow.com/questions/3680262/how-to-slice-a-2d-python-array-fails-with-typeerror-list-indices-must-be-int">this question</a> it looks like you can do something like this:</p>
<pre><code>foo = [row[start_col:end_col] for row in sheet.rows[start_row:end_row]]
</code></pre>
<p>Which will give you a list of lists <em>of cells</em>. Remember to use <code>foo[i][j].value</code> to get the contents of a <code>cell</code>.</p>
| 1 | 2016-08-26T19:38:36Z | [
"python",
"excel",
"openpyxl"
] |
Python Openpyxl, copy and paste cell range | 39,172,937 | <p>I know how to select a cell range in Openpyxl:</p>
<pre><code>cell_range = sheet['A1':'C3']
</code></pre>
<p>How can I paste cell_range above to another range, like <code>sheet['A11':'C13']</code>?</p>
| 0 | 2016-08-26T18:48:32Z | 39,174,143 | <p>You might want to look at <a href="https://bitbucket.org/snippets/openpyxl/qyzKn" rel="nofollow">this snippet</a> for some ideas. Please note it is <strong>entirely</strong> unsupported.</p>
| 0 | 2016-08-26T20:22:12Z | [
"python",
"excel",
"openpyxl"
] |
Absolute path in Python requiring an extra leading forward slash? | 39,172,944 | <p>I am trying to open a resource via an absolute path on my Macbook with <code>open(file[,mode])</code>. The resource I am trying to access is not in the same folder as the script that is running. If I use something like <code>/Users/myname/Dev/project/resource</code> I get an <code>IOError: No such file or directory</code>. Whats confusing me is that if i add and extra forward slash to the beginning so it starts with <code>//Users/...</code> it finds the resource without a problem.</p>
<p>What is going on here?</p>
| 0 | 2016-08-26T18:49:00Z | 39,173,233 | <p>The best way to deal with this is to avoid constructing the path yourself altogether. Let os.path.join() do it for you.</p>
| 0 | 2016-08-26T19:10:05Z | [
"python",
"python-2.7",
"file-io",
"path"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
elif "Measure Y:" in line:
measure_list.append(line)
final=''.join(measure_list).replace("Measure","\nMeasure")
print(final)
</code></pre>
<p>(This last part just helps organize the output)</p>
<p>So this part of the code opens a group of files and scans each one to see if it is "Part: ABCD", and if it is, it will pull the lines for "Measure X:" and "Measure Y:" and add them to the measure_list. My problem is that I have a lot of files and there will be multiple "Part: ABCD" files. And after joining the list with .join() the output will then look like:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>My question is if anybody knows a way to organize the output so that it looks like so:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure X: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>Any help is appreciated.</p>
| 0 | 2016-08-26T18:50:55Z | 39,173,046 | <p>Make two arrays of outputs and sort the input into each using a for loop with an if statement inside. Then join the two outputs.</p>
| 1 | 2016-08-26T18:57:12Z | [
"python",
"python-3.x"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
elif "Measure Y:" in line:
measure_list.append(line)
final=''.join(measure_list).replace("Measure","\nMeasure")
print(final)
</code></pre>
<p>(This last part just helps organize the output)</p>
<p>So this part of the code opens a group of files and scans each one to see if it is "Part: ABCD", and if it is, it will pull the lines for "Measure X:" and "Measure Y:" and add them to the measure_list. My problem is that I have a lot of files and there will be multiple "Part: ABCD" files. And after joining the list with .join() the output will then look like:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>My question is if anybody knows a way to organize the output so that it looks like so:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure X: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>Any help is appreciated.</p>
| 0 | 2016-08-26T18:50:55Z | 39,173,121 | <p>I don't have python up in front of me so there might be a slight syntax edit needed. This should sort the list by the X and Y portion of the "Measure X:..."</p>
<pre><code>sorted(measure_list,key=lambda item: item.split()[1][0])
</code></pre>
| 1 | 2016-08-26T19:02:15Z | [
"python",
"python-3.x"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
elif "Measure Y:" in line:
measure_list.append(line)
final=''.join(measure_list).replace("Measure","\nMeasure")
print(final)
</code></pre>
<p>(This last part just helps organize the output)</p>
<p>So this part of the code opens a group of files and scans each one to see if it is "Part: ABCD", and if it is, it will pull the lines for "Measure X:" and "Measure Y:" and add them to the measure_list. My problem is that I have a lot of files and there will be multiple "Part: ABCD" files. And after joining the list with .join() the output will then look like:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>My question is if anybody knows a way to organize the output so that it looks like so:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure X: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>Any help is appreciated.</p>
| 0 | 2016-08-26T18:50:55Z | 39,173,129 | <p>Why not to use two lists?</p>
<pre><code>if "Measure X:" in line:
listx.append(line)
elif "Measure Y:" in line:
listy.append(line)
</code></pre>
<p>Then simply</p>
<pre><code>final = ''.join(listx + listy)
</code></pre>
| 3 | 2016-08-26T19:02:53Z | [
"python",
"python-3.x"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
elif "Measure Y:" in line:
measure_list.append(line)
final=''.join(measure_list).replace("Measure","\nMeasure")
print(final)
</code></pre>
<p>(This last part just helps organize the output)</p>
<p>So this part of the code opens a group of files and scans each one to see if it is "Part: ABCD", and if it is, it will pull the lines for "Measure X:" and "Measure Y:" and add them to the measure_list. My problem is that I have a lot of files and there will be multiple "Part: ABCD" files. And after joining the list with .join() the output will then look like:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>My question is if anybody knows a way to organize the output so that it looks like so:</p>
<pre><code>Part: ABCD
Measure X: (Numbers)
Measure X: (Numbers)
Measure X: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
Measure Y: (Numbers)
</code></pre>
<p>Any help is appreciated.</p>
| 0 | 2016-08-26T18:50:55Z | 39,173,152 | <p>Your <code>measure_list</code> seems like this:</p>
<pre><code>['Measure X: 1000', 'Measure Y: 2000', 'Measure X: 100' , 'Measure Y: 900']
</code></pre>
<p>If that's right, you can simply sort this <code>measure_list</code>:</p>
<p><code>measure_list.sort()</code></p>
<p>Then you will have:</p>
<pre><code>['Measure X: 100', 'Measure X: 1000', 'Measure Y: 2000', 'Measure Y: 900']
</code></pre>
| 1 | 2016-08-26T19:04:41Z | [
"python",
"python-3.x"
] |
Using Matplotlib to plot over a subset of data | 39,173,034 | <p>I am using matplotlib to plot bar charts of data in my DataFrame. I use this construction to first plot over the whole dataset:</p>
<pre><code>import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CONS'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
df.plot(kind = 'bar', title = '1969-2015 National Temp Bins', legend = False, color = ['r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b','r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g' ] )
</code></pre>
<p>Now I would like to plot the same column of data except I would like to do so over a particular subset of data. For each region in 'region_name' I would like to generate the bar plot. Here is an example of my DataFrame. </p>
<p><a href="http://i.stack.imgur.com/0krvS.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/0krvS.jpg" alt="enter image description here"></a></p>
<p>My attempted solution is to write:</p>
<pre><code>if weatherDFConcat['REGION_NAME'].any() == 'South':
Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CONS'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
df.plot(kind = 'bar', title = '1969-2015 National Temp Bins', legend = False, color = ['r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g', 'b', 'b','r', 'r', 'g', 'g', 'b', 'b', 'r', 'r', 'g', 'g' ] )
plt.show()
</code></pre>
<p>When I run this code it oddly only works for the 'South' region. For 'South' the plot is generated but for any other regions I try the code runs (I get no error message) but the plot never shows up. Running my code for any region other than south produces this result in the console. </p>
<p><a href="http://i.stack.imgur.com/XAGvd.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/XAGvd.jpg" alt="enter image description here"></a></p>
<p>The South region is the first part in my DataFrame, which is 40 million lines long, with other regions being further down. Could the size of the DataFrame I'm trying to plot have anything to do with this?</p>
| 2 | 2016-08-26T18:56:18Z | 39,174,614 | <p>If I'm understanding your question correctly, you are trying to do two things prior to plotting:</p>
<ol>
<li><p>Filter based on <code>REGION_NAME</code>.</p></li>
<li><p>Within that filtered dataframe, count how many times each value in the <code>TEMPBIN_CONS</code> column appears.</p></li>
</ol>
<p>You can do both of those things right within pandas:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'STATE_NAME': ['Alabama', 'Florida', 'Maine', 'Delaware', 'New Jersey'],
'GEOID': [1, 2, 3, 4, 5],
'TEMPBIN_CONS': ['-3 to 0', '-3 to 0', '0 to 3', '-3 to 0', '0 to 3'],
'REGION_NAME': ['South', 'South', 'Northeast', 'Northeast', 'Northeast']},
columns=['STATE_NAME', 'GEOID', 'TEMPBIN_CONS', 'REGION_NAME'])
df_northeast = df[df['REGION_NAME'] == 'Northeast']
northeast_count = df_northeast.groupby('TEMPBIN_CONS').size()
print df
print df_northeast
print northeast_count
northeast_count.plot(kind='bar')
plt.show()
</code></pre>
<p>output:</p>
<pre><code> STATE_NAME GEOID TEMPBIN_CONS REGION_NAME
0 Alabama 1 -3 to 0 South
1 Florida 2 -3 to 0 South
2 Maine 3 0 to 3 Northeast
3 Delaware 4 -3 to 0 Northeast
4 New Jersey 5 0 to 3 Northeast
STATE_NAME GEOID TEMPBIN_CONS REGION_NAME
2 Maine 3 0 to 3 Northeast
3 Delaware 4 -3 to 0 Northeast
4 New Jersey 5 0 to 3 Northeast
TEMPBIN_CONS
-3 to 0 1
0 to 3 2
dtype: int64
</code></pre>
<p><a href="http://i.stack.imgur.com/oZLhY.png" rel="nofollow"><img src="http://i.stack.imgur.com/oZLhY.png" alt="enter image description here"></a></p>
| 1 | 2016-08-26T21:06:05Z | [
"python",
"pandas",
"numpy",
"matplotlib",
"plot"
] |
Pexpect: Read from the last send | 39,173,069 | <p>I am trying to read the output of pexpect.send(cmd) but here's the problem I am facing.</p>
<p>I am sending many commands in a sequence and I want to read/expect after a certain set of commands. Condition is that only the output of last command is to be considered. But <code>expect</code> matches from the point it last read. I have tried different methods such as matching for an EOF before sending the command of which I need the output but EOF means that child has terminated. I have tried reading till timeout and then sending the command but timeout itself causes the child to terminate. </p>
<p>I have looked for ways in which I could read from the end or the last line of output. I am considering reading a fixed bytes to a file or string and then manipulate the output to get the info I want. Here as well the fixed number of bytes is not fixed. There does not seems to be a reliable way to do this.</p>
<p>Could anyone help me sort this out ?</p>
| 0 | 2016-08-26T18:58:50Z | 39,256,145 | <p>There are three ways in which this problem can be handled but none to flush the buffer</p>
<ol>
<li>In Pexpect every <code>send</code> call should be matched with a call to
<code>expect</code>. This ensures that the file pointer has moved ahead of the
previous send.</li>
<li>If there is a series of <code>send</code> before a single <code>expect</code> then we need
to provide a way to move file pointer to the location of last send.
This can be done by an extra <code>send</code> whose <code>expect</code> output is unique.
The uniqueness should be such that none of the <code>send</code> in the series
of <code>send</code> should give that output.</li>
<li>Third method is to use set <code>logfile_read</code> to a file. All the output
will be logged to this file. Before the <code>send</code> for which the
<code>expect</code> is used, get the position of file pointer. Now get the
position of file pointer after the send as well. Search for expected
pattern in the file in between first and second pointer.</li>
</ol>
<p>First method is the ideal way it should be done.</p>
| 0 | 2016-08-31T17:57:57Z | [
"python",
"python-2.7",
"pexpect"
] |
Python equivalent of this Curl command | 39,173,107 | <p>I am trying to download a file using python, imitating the same behavior as this curl command:</p>
<pre><code>curl ftp://username:password@example.com \
--retry 999 \
--retry-max-time 0
-o 'target.txt' -C -
</code></pre>
<p>How would this look in python ?</p>
<p>Things I have looked into:</p>
<ul>
<li><p>Requests : no ftp support</p></li>
<li><p>Python-wget: no download resume support</p></li>
<li><p>requests-ftp : no download resume support</p></li>
<li><p>fileDownloader : broken(?)</p></li>
</ul>
<p>I am guessing one would need to build this from scratch and go low level with pycurl or urllib2 or something similar.</p>
<p>I am trying to create this script in python and I feel lost.. Should I just call curl from python subprocess ?</p>
<p>Any point to the write direction would be much appreciated</p>
| 0 | 2016-08-26T19:01:30Z | 39,173,753 | <p>there is this library for downloading files from ftp server</p>
<p><a href="https://pypi.python.org/pypi/fileDownloader.py/0.2.1" rel="nofollow">fileDownloader.py</a></p>
<p>to download the file</p>
<pre><code>downloader = fileDownloader.DownloadFile(âhttp://example.com/file.zipâ, âC:UsersusernameDownloadsnewfilename.zipâ, (âusernameâ,âpasswordâ))
downloader.download()
</code></pre>
<p>to resume download</p>
<pre><code>downloader = fileDownloader.DownloadFile(âhttp://example.com/file.zipâ, âC:UsersusernameDownloadsnewfilename.zipâ, (âusernameâ,âpasswordâ))
downloader.resume()
</code></pre>
| 0 | 2016-08-26T19:50:19Z | [
"python",
"curl"
] |
Python equivalent of this Curl command | 39,173,107 | <p>I am trying to download a file using python, imitating the same behavior as this curl command:</p>
<pre><code>curl ftp://username:password@example.com \
--retry 999 \
--retry-max-time 0
-o 'target.txt' -C -
</code></pre>
<p>How would this look in python ?</p>
<p>Things I have looked into:</p>
<ul>
<li><p>Requests : no ftp support</p></li>
<li><p>Python-wget: no download resume support</p></li>
<li><p>requests-ftp : no download resume support</p></li>
<li><p>fileDownloader : broken(?)</p></li>
</ul>
<p>I am guessing one would need to build this from scratch and go low level with pycurl or urllib2 or something similar.</p>
<p>I am trying to create this script in python and I feel lost.. Should I just call curl from python subprocess ?</p>
<p>Any point to the write direction would be much appreciated</p>
| 0 | 2016-08-26T19:01:30Z | 39,174,507 | <p>you can use python's inbuilt ftplib</p>
<p>Here is the code:</p>
<pre><code>from ftplib import FTP
ftp = FTP('example.com', 'username', 'password') #logs in
ftp.retrlines() # to see the list of files and directories ftp.cwd('to change to any directory')
ftp.retrbinary('RETR filename', open('Desktop\filename', 'wb').write) # start downloading
ftp.close() # close the connection
</code></pre>
<p>Auto resume is supported. I even tried turning off my wifi and checked if the download is resuming.</p>
<p>You can refer to /Python27/Lib/ftplib.py for default GLOBAL_TIME_OUT settings.</p>
| 1 | 2016-08-26T20:55:43Z | [
"python",
"curl"
] |
Hybrid Naive Bayes: How to train Naive Bayes Classifer with numeric and category variable together(sklearn) | 39,173,169 | <p>Basicly, skelarn have naive bayes with Gaussian kernal which can class numeric variables.</p>
<p>However, how to deal with data set containing numeric variables and category variables together.</p>
<p>For an example, give a dataset below, how use sklearn train mixed data type together without discreting numeric variables?</p>
<p>Index Gender Age Product_Reviews</p>
<p>A Female 20 Good</p>
<p>B Male 21 Bad</p>
<p>C Female 25 Bad</p>
<p>I mean , for Bayes classication, P(A|B)= P(B|A)*P(A)/P(B) .</p>
<p>For category variables, P(B|A) is easily to count out,
but for numeric variables, it should follows Gaussian distribution.
And assume we have got P(B|A) with Gaussian distribution.</p>
<p>Is there any package can directly work with these together?</p>
<p>Please be note: this question is not duplicated with <a href="http://stackoverflow.com/questions/38621053/how-can-i-use-sklearn-naive-bayes-with-multiple-categorical-features">How can I use sklearn.naive_bayes with (multiple) categorical features?</a>
and <a href="http://stackoverflow.com/questions/14254203/mixing-categorial-and-continuous-data-in-naive-bayes-classifier-using-scikit-lea?rq=1">Mixing categorial and continuous data in Naive Bayes classifier using scikit-learn</a></p>
<p>Because this question is not wanna to do a naive bayes with dummy variables(1st question) and also do not wanna do a model ensemble(2nd question solution2).</p>
<p>The mathematic algothrim is here <a href="https://tom.host.cs.st-andrews.ac.uk/ID5059/L15-HsuPaper.pdf" rel="nofollow">https://tom.host.cs.st-andrews.ac.uk/ID5059/L15-HsuPaper.pdf</a> , which calculates conditional probabilities with Gaussian distribution instead of counting number with numeric variables. And make classification with all conditional probabilities including category variables(by counting number) and numeric variables(Gaussian distribution)</p>
| 0 | 2016-08-26T19:05:43Z | 39,175,843 | <p>The answer comes directly from the mathematics of Naive Bayes</p>
<ol>
<li><p>Categorical variables provide you with log P(a|cat) ~ SUM_i log P(cat_i|a) + log P(a) (I am omitting division by P(cat), as what NB implementation returns is also ignoring it)</p></li>
<li><p>Continuous variables give you the same thing, log P(a|con) ~ SUM_i log P(con_i|a) + log P(a) (I am omitting division by P(cat), as what NB implementation returns is also ignoring it)</p></li>
</ol>
<p>and since in Naive Bayes features are independent we get that for <code>x</code> which contains both categorical and continuous</p>
<p>P(a|x) ~ SUM_i log(x_i | a) + log P(a) = SUM_i log P(cat_i|a) + log P(a) + SUM_i log P(con_i|a) + log P(a) - log P(a) = log likelihood from categorical model + log likelihood from continuous model - log prior of class a</p>
<p>all these elements you can read out from your two models, independently fitted to each part of the data. Notice that this <strong>is not an ensemble</strong>, you simply fit two models and construct one on your own <strong>due to specific assumptions of naive bayes</strong>, thus you are overcoming implementational limitation this way, yet still efficiently constructing valid NB model on mixed distributions. Note that this works for <strong>any set of mixed distributions</strong>, thus you could do the same given more different NBs (using different distributions).</p>
| 1 | 2016-08-26T23:18:30Z | [
"python",
"statistics",
"scikit-learn",
"naivebayes"
] |
In python does self require any object of its same type? | 39,173,175 | <p>I am reading 9.3.2. Class Objects from the python docs and I was hoping someone can clear up the following:</p>
<p>How come both scenarios return 'hello world'? The first instance I kind of understand (at least I believe I do) because self is referencing the object itself 'MyClass' and I guess passing 'm' to self in the second instance is doing the same? Does the function 'self' just need ANY reference to a 'MyClass' object?</p>
<pre><code>>>> class MyClass:
... """A simple example class"""
... i = 12345
... def f(self):
... return 'hello world'
...
>>> MyClass.f(MyClass)
'hello world'
>>> m = MyClass()
>>> MyClass.f(m)
'hello world'
</code></pre>
| 1 | 2016-08-26T19:05:54Z | 39,173,276 | <p>Python is "duck-typed", meaning it doesn't matter <em>what</em> type <code>self</code> is, as long as it provides the correct interface. Here, <code>self</code> isn't used in the body of the function, so you could pass absolutely <em>anything</em> to <code>MyClass.f</code> and it would work.</p>
<pre><code>>>> MyClass.f(None)
'hello world'
>>> MyClass.f(9)
'hello world'
>>> MyClass.f("foo")
'hello world'
</code></pre>
| 3 | 2016-08-26T19:13:19Z | [
"python",
"class"
] |
In python does self require any object of its same type? | 39,173,175 | <p>I am reading 9.3.2. Class Objects from the python docs and I was hoping someone can clear up the following:</p>
<p>How come both scenarios return 'hello world'? The first instance I kind of understand (at least I believe I do) because self is referencing the object itself 'MyClass' and I guess passing 'm' to self in the second instance is doing the same? Does the function 'self' just need ANY reference to a 'MyClass' object?</p>
<pre><code>>>> class MyClass:
... """A simple example class"""
... i = 12345
... def f(self):
... return 'hello world'
...
>>> MyClass.f(MyClass)
'hello world'
>>> m = MyClass()
>>> MyClass.f(m)
'hello world'
</code></pre>
| 1 | 2016-08-26T19:05:54Z | 39,173,348 | <pre><code>MyClass.f('what the...')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-cca57c03fecc> in <module>()
----> 1 MyClass.f('what the...')
TypeError: unbound method f() must be called with MyClass instance as first argument (got str instance instead)
mc = MyClass()
mc.f('what?')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-bcd3830312d3> in <module>()
----> 1 mc.f('what?')
TypeError: f() takes exactly 1 argument (2 given)
</code></pre>
<p>In the first instance, the function requires an instance of <code>MyClass</code> as the first argument. In the second, the instance is implicitly passed. The string argument <code>What?</code> is thus a second argument to the function which is unexpected.</p>
<p>What you may want:</p>
<pre><code>class MyClass:
@staticmethod
def f():
print('hello world')
>>> MyClass.f()
hello world
mc = MyClass()
>>> mc.f()
hello world
</code></pre>
| 0 | 2016-08-26T19:19:23Z | [
"python",
"class"
] |
Python Compile file(.pyc) generated even after errors in code-why? | 39,173,176 | <p>I have the below code in a file <strong>a1.py</strong></p>
<pre><code>fff
def test(arg):
print 'sid'
print arg
print 'sid2'
test()
</code></pre>
<p>The above code contains 2 errors:</p>
<ol>
<li><p>fff does not exist and is still being asked to print</p></li>
<li><p>Arguments are not passed in test()</p></li>
</ol>
<p>Now i write an another file <strong>b1.py</strong>
In that file the code is:</p>
<pre><code>import a1
print 'b1 execution done'
</code></pre>
<p>Que 1: I executed b1.py and a1.pyc file is generated. Why ? There is a syntax error.pyc file should not have been generated?</p>
<p>Que2: Explain in laymen terms what is pyc file and what role does it play?</p>
<p>Que3: Why is pyc file generated even if a1.py has errors ?(e.g. argument not being passed)</p>
| 0 | 2016-08-26T19:06:00Z | 39,173,286 | <p>Python automatically compiles your script to compiled code, so called byte code, before running it. When a module is imported for the first time, or when the source is more recent than the current compiled file, a .pyc file containing the compiled code will usually be created in the same directory as the .py file.</p>
| 0 | 2016-08-26T19:14:07Z | [
"python",
"python-2.7",
"compilation"
] |
Matplotlib/Openpyxl - Pasting multiple images into different worksheets excel | 39,173,182 | <p>I am having a real problem understanding ow python is reading my code and need some help. I have several worksheets within one excel workbook, all containing one dataframe table and one chart. I have organized my code in a way where i run all the different dataframe, write them to each excel worksheet, plot each chart, save the chart to a png file and then use openpyxl to load the image to each worksheet. </p>
<p>The key here seems to how and where i save the file to the workbook. For example, if i type xfile.save('bikes.xlsx') after the last image is uploaded to to the last worksheet, it displays only the last image and none of the other images in the other worksheets. If is type save after the first image is loaded to its worksheet, excel displays the image for the first worksheet. If i put the save function after each image is loaded to their worksheets, only the last image displays in the last worksheet. </p>
<pre><code>#Plot chart 1
df3.plot(x='Length', y=['types of cats'], figsize=(8,4))
plt.savefig('Typesofcats.png')
#Write PNG file to existing worksheet
from openpyxl import Workbook
from openpyxl.drawing.image import Image
xfile1 = openpyxl.load_workbook('Things.xlsx')
sheet1 = xfile1.get_sheet_by_name('Types of Cats')
img1 = Image('Typesofcats.png')
sheet1.add_image(img1, 'I6')
xfile.save('Things.xlsx')
#Plot chart 2
df5.plot(x='Length', y=['Types of dogs'], figsize=(8,4))
plt.savefig('Typesofdogs.png')
#Write PNG file to existing worksheet
from openpyxl import Workbook
from openpyxl.drawing.image import Image
xfile2 = openpyxl.load_workbook('Things.xlsx')
sheet2 = xfile2.get_sheet_by_name('Types of dogs')
img2 = Image('Typesofdogs.png')
sheet2.add_image(img2, 'I6')
xfile2.save('Things.xlsx')
#Plot chart 3
df6.plot(x='Length', y=['Types of pigs'], figsize=(7,3))
plt.savefig('Typesofpigs.png')
#Write PNG file to existing worksheet
from openpyxl import Workbook
from openpyxl.drawing.image import Image
xfile3 = openpyxl.load_workbook('Things.xlsx')
sheet3 = xfile2.get_sheet_by_name('Types of pigs')
img3 = Image('Typesofpigs.png')
sheet3.add_image(img3, 'F6')
xfile3.save('Things.xlsx')
</code></pre>
| 2 | 2016-08-26T19:06:28Z | 39,206,541 | <p>Ah okay yes! Because I am opening and closing the workbook each time, the images are getting deleted from the previous worksheet. If I simply only open the connection once, paste all images to each of the worksheets, and then close it works.</p>
<pre><code>#Write PNG file to existing worksheet
from openpyxl import Workbook
from openpyxl.drawing.image import Image
xfile = openpyxl.load_workbook('Things.xlsx')
sheet = xfile.get_sheet_by_name('Types of Cats')
img = Image('Typesofcats.png')
sheet.add_image(img, 'L6')
sheet1 = xfile.get_sheet_by_name('Types of Dogs')
img1 = Image('Typesofdogs.png')
sheet1.add_image(img1, 'I6')
sheet2 = xfile.get_sheet_by_name('Types of Pigs')
img2 = Image('Typesofpigs.png')
sheet2.add_image(img2, 'I6')
xfile.save('Things.xlsx')
</code></pre>
<p>Thank you for your help.</p>
| 2 | 2016-08-29T12:37:20Z | [
"python",
"matplotlib",
"openpyxl"
] |
Python requests decode using a different charset | 39,173,203 | <p>I'm using <code>requests</code> to fetch a webpage but the automatically inferred encoding in <code>response.encoding</code> is incorrect. I need to decode the bytes in unicode, but I didn't find an API for this. <code>response.text</code> is Unicode but not the byte array. Any idea?</p>
| -1 | 2016-08-26T19:07:52Z | 39,173,262 | <p>From <a href="http://docs.python-requests.org/en/master/user/quickstart/#response-content" rel="nofollow">the documentation</a> (emphasis added):</p>
<blockquote>
<p>When you make a request, Requests makes educated guesses about the
encoding of the response based on the HTTP headers. The text encoding
guessed by Requests is used when you access <code>r.text</code>. You can find out
what encoding Requests is using, and change it, using the <code>r.encoding</code>
property:</p>
<pre><code>>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
</code></pre>
<p><strong>If you change the encoding, Requests will use the new value of <code>r.encoding</code> whenever you call <code>r.text</code></strong>. You might want to do this
in any situation where you can apply special logic to work out what
the encoding of the content will be. For example, HTTP and XML have
the ability to specify their encoding in their body. In situations
like this, you should use <code>r.content</code> to find the encoding, and then
set <code>r.encoding</code>. This will let you use <code>r.text</code> with the correct
encoding.</p>
</blockquote>
| 1 | 2016-08-26T19:12:06Z | [
"python",
"python-requests"
] |
Scrapy performance improvements and memory consumtion | 39,173,260 | <p>Server</p>
<ul>
<li>6 GB RAM</li>
<li>4 Cores Intel Xeon 2.60GHz</li>
<li>32 CONCURRENT_REQUESTS</li>
<li>1m URLs in CSV</li>
<li>700 Mbit/s downstream</li>
<li>96% Memory Consumtion</li>
</ul>
<p>With debug mode on, the scrape stops after around 400 000 urls, most likely because the server runs out of memory.
Without debug mode it takes up to 5 days which is pretty slow imo and
it takes way to much memory (96%)</p>
<p>any hints are highly welcome :)</p>
<pre><code>import scrapy
import csv
def get_urls_from_csv():
with open('data.csv', newline='') as csv_file:
data = csv.reader(csv_file, delimiter=',')
scrapurls = []
for row in data:
scrapurls.append("http://"+row[2])
return scrapurls
class rssitem(scrapy.Item):
sourceurl = scrapy.Field()
rssurl = scrapy.Field()
class RssparserSpider(scrapy.Spider):
name = "rssspider"
allowed_domains = ["*"]
start_urls = ()
def start_requests(self):
return [scrapy.http.Request(url=start_url) for start_url in get_urls_from_csv()]
def parse(self, response):
res = response.xpath('//link[@type="application/rss+xml"]/@href')
for sel in res:
item = rssitem()
item['sourceurl']=response.url
item['rssurl']=sel.extract()
yield item
pass
</code></pre>
| 1 | 2016-08-26T19:11:59Z | 39,173,498 | <pre><code>import csv
from collections import namedtuple
import scrapy
def get_urls_from_csv():
with open('data.csv', newline='') as csv_file:
data = csv.reader(csv_file, delimiter=',')
for row in data:
yield row[2]
# if you can use something else than scrapy
rssitem = namedtuple('rssitem', 'sourceurl rssurl')
class RssparserSpider(scrapy.Spider):
name = "rssspider"
allowed_domains = ["*"]
start_urls = ()
def start_requests(self): # remember that it returns generator
for start_url in get_urls_from_csv():
yield scrapy.http.Request(url="http://{}".format(start_url))
def parse(self, response):
res = response.xpath('//link[@type="application/rss+xml"]/@href')
for sel in res:
yield rssitem(response.url, sel.extract())
pass
</code></pre>
| 0 | 2016-08-26T19:29:21Z | [
"python",
"scrapy",
"scrapy-spider"
] |
Scrapy performance improvements and memory consumtion | 39,173,260 | <p>Server</p>
<ul>
<li>6 GB RAM</li>
<li>4 Cores Intel Xeon 2.60GHz</li>
<li>32 CONCURRENT_REQUESTS</li>
<li>1m URLs in CSV</li>
<li>700 Mbit/s downstream</li>
<li>96% Memory Consumtion</li>
</ul>
<p>With debug mode on, the scrape stops after around 400 000 urls, most likely because the server runs out of memory.
Without debug mode it takes up to 5 days which is pretty slow imo and
it takes way to much memory (96%)</p>
<p>any hints are highly welcome :)</p>
<pre><code>import scrapy
import csv
def get_urls_from_csv():
with open('data.csv', newline='') as csv_file:
data = csv.reader(csv_file, delimiter=',')
scrapurls = []
for row in data:
scrapurls.append("http://"+row[2])
return scrapurls
class rssitem(scrapy.Item):
sourceurl = scrapy.Field()
rssurl = scrapy.Field()
class RssparserSpider(scrapy.Spider):
name = "rssspider"
allowed_domains = ["*"]
start_urls = ()
def start_requests(self):
return [scrapy.http.Request(url=start_url) for start_url in get_urls_from_csv()]
def parse(self, response):
res = response.xpath('//link[@type="application/rss+xml"]/@href')
for sel in res:
item = rssitem()
item['sourceurl']=response.url
item['rssurl']=sel.extract()
yield item
pass
</code></pre>
| 1 | 2016-08-26T19:11:59Z | 39,173,768 | <p>As I commented you should use <a href="https://wiki.python.org/moin/Generators" rel="nofollow"><em>generators</em></a> to avoid creating lists of objects in memory(<a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">what-does-the-yield-keyword-do-in-python</a>), using generators objects are created lazily so you don't create large lists of objects all in memory at once:</p>
<pre><code>def get_urls_from_csv():
with open('data.csv', newline='') as csv_file:
data = csv.reader(csv_file, delimiter=',')
for row in data:
yield http://"+row[2]) # yield each url lazily
class rssitem(scrapy.Item):
sourceurl = scrapy.Field()
rssurl = scrapy.Field()
class RssparserSpider(scrapy.Spider):
name = "rssspider"
allowed_domains = ["*"]
start_urls = ()
def start_requests(self):
# return a generator expresion.
return (scrapy.http.Request(url=start_url) for start_url in get_urls_from_csv())
def parse(self, response):
res = response.xpath('//link[@type="application/rss+xml"]/@href')
for sel in res:
item = rssitem()
item['sourceurl']=response.url
item['rssurl']=sel.extract()
yield item
</code></pre>
<p>As far as performance goes, what the docs on <a href="http://doc.scrapy.org/en/latest/topics/broad-crawls.htm" rel="nofollow">Broad Crawls</a> suggest is to try to <a href="http://doc.scrapy.org/en/latest/topics/broad-crawls.html#increase-concurrency" rel="nofollow">increase concurrency</a> is:</p>
<p><em>Concurrency is the number of requests that are processed in parallel. There is a global limit and a per-domain limit.
<strong>The default global concurrency limit in Scrapy is not suitable for crawling many different domains in parallel</strong>, so you will want to increase it. How much to increase it will depend on how much CPU you crawler will have available. A good starting point is 100, but the best way to find out is by doing some trials and identifying at what concurrency your Scrapy process gets CPU bounded.</em> <strong>For optimum performance, you should pick a concurrency where CPU usage is at 80-90%.</strong></p>
<p>To increase the global concurrency use:</p>
<pre><code>CONCURRENT_REQUESTS = 100
</code></pre>
<p>emphasis mine.</p>
<p>Also <a href="http://doc.scrapy.org/en/latest/topics/broad-crawls.html#increase-twisted-io-thread-pool-maximum-size" rel="nofollow">Increase Twisted IO thread pool maximum size</a>:</p>
<p><em>Currently Scrapy does DNS resolution in a blocking way with usage of thread pool. With higher concurrency levels the crawling could be slow or even fail hitting DNS resolver timeouts. Possible solution to increase the number of threads handling DNS queries. The DNS queue will be processed faster speeding up establishing of connection and crawling overall.</em></p>
<p>To increase maximum thread pool size use:</p>
<pre><code> REACTOR_THREADPOOL_MAXSIZE = 20
</code></pre>
| 1 | 2016-08-26T19:51:54Z | [
"python",
"scrapy",
"scrapy-spider"
] |
Numpy-like printing for python objects | 39,173,398 | <p>While doing data analysis in Ipython I often have to look at the data by just printing its contents to the shell. Numpy have the facility to show only the <strong>margins</strong> of huge objects when they are too long themselves. I really like this feature of ndarrays but when I print internal python object (eg. dictionary with 15k objects in it) they are dumped to the screen or sometimes truncated in not very friendly fashion.
So for example for a huge dictionary I would like to see in output something like this </p>
<pre><code>{ '39416' : '1397',
'39414' : '1397',
'7629' : '7227',
...,
'31058' : '9606',
'21097' : '4062',
'32040' : '9606' }
</code></pre>
<p>It would be perfect if alignment and nested data structures could be taken care of. Is their a special module which can provide such functionality for python basic classes (list, dict)? Or there are some ipython configuration tricks I know nothing about?</p>
| 5 | 2016-08-26T19:22:49Z | 39,173,441 | <p>There is a good built-in library <a href="https://docs.python.org/3/library/pprint.html" rel="nofollow"><code>pprint</code></a>. Take a look at it.</p>
<pre><code>>>> from pprint import pprint
>>> pprint({x: list(range(x)) for x in range(10)})
{0: [],
1: [0],
2: [0, 1],
3: [0, 1, 2],
4: [0, 1, 2, 3],
5: [0, 1, 2, 3, 4],
6: [0, 1, 2, 3, 4, 5],
7: [0, 1, 2, 3, 4, 5, 6],
8: [0, 1, 2, 3, 4, 5, 6, 7],
9: [0, 1, 2, 3, 4, 5, 6, 7, 8]}
</code></pre>
| 1 | 2016-08-26T19:25:18Z | [
"python",
"printing",
"ipython"
] |
Numpy-like printing for python objects | 39,173,398 | <p>While doing data analysis in Ipython I often have to look at the data by just printing its contents to the shell. Numpy have the facility to show only the <strong>margins</strong> of huge objects when they are too long themselves. I really like this feature of ndarrays but when I print internal python object (eg. dictionary with 15k objects in it) they are dumped to the screen or sometimes truncated in not very friendly fashion.
So for example for a huge dictionary I would like to see in output something like this </p>
<pre><code>{ '39416' : '1397',
'39414' : '1397',
'7629' : '7227',
...,
'31058' : '9606',
'21097' : '4062',
'32040' : '9606' }
</code></pre>
<p>It would be perfect if alignment and nested data structures could be taken care of. Is their a special module which can provide such functionality for python basic classes (list, dict)? Or there are some ipython configuration tricks I know nothing about?</p>
| 5 | 2016-08-26T19:22:49Z | 39,173,528 | <p>If your dictionary is well structured, you could convert it to a Pandas dataframe for viewing.</p>
<pre><code>import numpy as np
import pandas as pd
>>> pd.DataFrame({'random normal': np.random.randn(1000),
'random int': np.random.randint(0, 10, 1000)})
random int random normal
0 6 0.850827
1 7 0.486551
2 4 -0.111008
3 9 -1.319320
4 6 -0.393774
5 1 -0.878507
.. ... ...
995 2 -1.882813
996 3 -0.121003
997 3 0.155835
998 5 0.920318
999 2 0.216229
[1000 rows x 2 columns]
</code></pre>
| 1 | 2016-08-26T19:30:59Z | [
"python",
"printing",
"ipython"
] |
Numpy-like printing for python objects | 39,173,398 | <p>While doing data analysis in Ipython I often have to look at the data by just printing its contents to the shell. Numpy have the facility to show only the <strong>margins</strong> of huge objects when they are too long themselves. I really like this feature of ndarrays but when I print internal python object (eg. dictionary with 15k objects in it) they are dumped to the screen or sometimes truncated in not very friendly fashion.
So for example for a huge dictionary I would like to see in output something like this </p>
<pre><code>{ '39416' : '1397',
'39414' : '1397',
'7629' : '7227',
...,
'31058' : '9606',
'21097' : '4062',
'32040' : '9606' }
</code></pre>
<p>It would be perfect if alignment and nested data structures could be taken care of. Is their a special module which can provide such functionality for python basic classes (list, dict)? Or there are some ipython configuration tricks I know nothing about?</p>
| 5 | 2016-08-26T19:22:49Z | 39,174,588 | <p>The <code>numpy</code> formatter has an ellipsis functionality; as a default it kicks in with 1000+ items. </p>
<p><code>pprint</code> can make the display nicer, but I don't think it has an ellipsis functionality. But you can study its docs.</p>
<p>With a list I may use a slice</p>
<pre><code>list(range(100))[:10]
</code></pre>
<p>to see a limited number of the values.</p>
<p>That's harder to do with a dictionary. With some trial and error, this works tolerably:</p>
<pre><code>{k:dd[k] for k in list(dd.keys())[:10]}
</code></pre>
<p>(I'm on Py3 so need the extra <code>list</code>).</p>
<p>It wouldn't be hard to write your own utility functions if you can't find something in <code>pprint</code>. It's also possible that some package on <code>pypi</code> does this. For example a quick search turned up</p>
<p><a href="https://pypi.python.org/pypi/pprintpp" rel="nofollow">https://pypi.python.org/pypi/pprintpp</a></p>
<p><code>pprintpp</code> which claims to be actually pretty. But like the stock <code>pprint</code> it seems to be more concerned with the nesting depth of lists and dictionaries, and not so much their length.</p>
| 0 | 2016-08-26T21:03:40Z | [
"python",
"printing",
"ipython"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.