title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Replacing values in a column for a subset of rows
40,095,632
<p>I have a <code>dataframe</code> having multiple columns. I would like to replace the value in a column called <code>Discriminant</code>. Now this value needs to only be replaced for a few rows, whenever a condition is met in another column called <code>ids</code>. I tried various methods; The most common method seems to be using the <code>.loc</code> method, but for some reason it doesn't work for me. </p> <p>Here are the variations that I am unsuccessfully trying:</p> <p><code>encodedid</code> - variable used for condition checking</p> <p><code>indices</code> - variable used for subsetting the <code>dataframe</code> (starts from zero)</p> <p><strong>Variation 1:</strong></p> <pre><code>df[df.ids == encodedid].loc[df.ids==encodedid, 'Discriminant'].values[indices] = 'Y' </code></pre> <p><strong>Variation 2:</strong></p> <pre><code>df[df['ids'] == encodedid].iloc[indices,:].set_value('questionid','Discriminant', 'Y') </code></pre> <p><strong>Variation 3:</strong></p> <pre><code>df.loc[df.ids==encodedid, 'Discriminant'][indices] = 'Y' </code></pre> <p><code>Variation 3</code> particularly has been disappointing in that most posts on SO tend to say it should work but it gives me the following error:</p> <pre><code>ValueError: [ 0 1 2 3 5 6 7 8 10 11 12 13 14 16 17 18 19 20 21 22 23] not contained in the index </code></pre> <p>Any pointers will be highly appreciated.</p>
0
2016-10-17T21:04:46Z
40,095,819
<p>Maybe something like this. I don't have a dataframe to test it, but... </p> <pre><code>df['Discriminant'] = np.where(df['ids'] == 'some_condition', 'replace', df['Discriminant']) </code></pre>
1
2016-10-17T21:19:01Z
[ "python", "pandas", "dataframe" ]
Python - insert lines on txt following a sequence without overwriting
40,095,670
<p>I want to insert the name of a file before each file name obtained through glob.glob, so I can concatenate them through FFMPEG by sorting them into INTRO+VIDEO+OUTRO, the files have to follow this order:</p> <p>INSERTED FILE NAME<br> FILE<br> INSERTED FILE NAME<br> INSERTED FILE NAME<br> FILE<br> INSERTED FILE NAME<br> INSERTED FILE NAME<br> FILE<br> INSERTED FILE NAME<br></p> <p>This is this code I'm using:</p> <pre><code>import glob open("Lista.txt", 'w').close() file = open("Lista.txt", "a") list =glob.glob("*.mp4") for item in list: file.write("%s\n" % item) file.close() f = open("Lista.txt", "r") contents = f.readlines() f.close() for x,item in enumerate(list): contents.insert(x, "CTA\n") f = open("Lista.txt", "w") contents = "".join(contents) f.write(contents) print f f.close() </code></pre> <p>But I obtain the values in the wrong order:<br></p> <p>INSERTED FILE NAME<br> INSERTED FILE NAME<br> INSERTED FILE NAME<br> FILE<br> FILE<br> FILE <br></p> <p>How could I solve this? EDIT: As pointed out, maybe the issue is being caused by modifying a list that I'm currently using.</p>
0
2016-10-17T21:07:24Z
40,096,049
<p>You are trying to modify <code>contents</code> list. I think if new list is used to get final output, then it will be simple and more readable as below. And as <strong>Zen of Python</strong> states</p> <p><strong>Simple is always better than complex.</strong> </p> <ol> <li>Consider you got <code>file_list</code> as below after doing <code>glob.glob</code>.</li> </ol> <blockquote> <p>file_list = ["a.mp4","b.mp4","c.mp4"]</p> </blockquote> <ol start="2"> <li>Now you want to add "<code>INSERTFILE</code>" before and after every element of <code>file_list</code> so that final_list will look like </li> </ol> <blockquote> <p>final_list = ['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE', 'b.mp4', 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE']</p> </blockquote> <ol start="3"> <li>This final_list you will write to file.</li> </ol> <p><strong><em>Problem summary is how to achieve step 2.</em></strong></p> <p>Below code will get step 2.</p> <p><strong>Code (with comments inline:</strong></p> <pre><code>#File List from glob.glob file_list = ["a.mp4","b.mp4","c.mp4"] #File to be added i = "INSERTFILE" final_list = [] for x in file_list: #Create temp_list temp_list = [i,x,i] #Extend (not append) to final_list final_list.extend(temp_list) #Clean temp_list for next iteration temp_list = [] print (final_list) </code></pre> <p><strong>Output:</strong></p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py ['INSERTFILE', 'a.mp4', 'INSERTFILE', 'INSERTFILE', 'b.mp4', 'INSERTFILE', 'INSERTFILE', 'c.mp4', 'INSERTFILE'] </code></pre>
1
2016-10-17T21:34:51Z
[ "python", "video", "ffmpeg" ]
Multi-dimensional outer-product in python
40,095,686
<p>I was doing MNIST dataset and trying to get a outer product of my two vectors <code>w_i(ith class)</code> and <code>a_k(kth sample)</code>.</p> <p>The <code>w_i</code>, for <code>i = 0...9</code>, has 784 coordinates.</p> <p>The <code>a_k</code>, for <code>k = 1...n</code>, also has 784 coordinates.</p> <p>I created two arrays <code>w_ij</code> and <code>a_ij</code> which contain all ten classes and k samples. The shape of <code>w_ij</code> is (10, 784) and <code>a_ij</code> is (n, 784).</p> <p>I was trying to get a result something like:</p> <pre><code>[[w_0 dot a_1, w_0 dot a_2, ... , w_0 dot a_n], # (first row) [w_1 dot a_1, w_1 dot a_2, ..., w_1 dot a_n], # (second row) ..., [w_9 dot a_1, ..., w_9 dot a_n]] # (nth row) </code></pre> <p>So the shape of array should be like <code>(10, n)</code>. I tried to use <code>scipy.outer(w_ij, a_k)</code> or <code>scipy.multiply.outer(w_ij, a_k)</code>. However, it led me to a result whose shape is <code>(7840, 784*n)</code>. Could someone direct me to the right path?</p>
2
2016-10-17T21:08:48Z
40,095,793
<p>It looks like you want the following:</p> <pre><code>res = np.einsum('pi,qi-&gt;pq', w, a) </code></pre> <p>Which is shorthand for the following in index notation:</p> <pre><code>res[p,q] = w[p,i]*a[q,i] </code></pre> <p>In this notation, the convention is to sum over all indices which do not appear in the output</p> <hr> <p>However, note that <code>ij,jk-&gt;ik</code> is just the standard matrix product, and <code>ij-&gt;ji</code> is just the matrix transpose. So we can simplify this as follows</p> <pre><code>np.einsum('pi,qi-&gt;pq', w, a) # as before np.einsum('pi,iq-&gt;pq', w, a.T) # transpose and swapping indices cancel out np.einsum('ij,jk-&gt;ik', w, a.T) # index names don't matter w @ a.T # wait a sec, this is just matrix multiplication (python 3.5+) </code></pre>
3
2016-10-17T21:16:38Z
[ "python", "arrays", "numpy", "multidimensional-array", "scipy" ]
When to apply(pd.to_numeric) and when to astype(np.float64) in python?
40,095,712
<p>I have a pandas DataFrame object named <code>xiv</code> which has a column of <code>int64</code> Volume measurements. </p> <pre><code>In[]: xiv['Volume'].head(5) Out[]: 0 252000 1 484000 2 62000 3 168000 4 232000 Name: Volume, dtype: int64 </code></pre> <p>I have read other posts (like <a href="http://stackoverflow.com/questions/21287624/pandas-dataframe-column-type-conversion?rq=1">this</a> and <a href="http://stackoverflow.com/questions/15891038/pandas-change-data-type-of-columns">this</a>) that suggest the following solutions. But when I use either approach, it doesn't appear to change the <code>dtype</code> of the underlying data:</p> <pre><code>In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume']) In[]: xiv['Volume'].dtypes Out[]: dtype('int64') </code></pre> <p>Or...</p> <pre><code>In[]: xiv['Volume'] = pd.to_numeric(xiv['Volume']) Out[]: ###omitted for brevity### In[]: xiv['Volume'].dtypes Out[]: dtype('int64') In[]: xiv['Volume'] = xiv['Volume'].apply(pd.to_numeric) In[]: xiv['Volume'].dtypes Out[]: dtype('int64') </code></pre> <p>I've also tried making a separate pandas <code>Series</code> and using the methods listed above on that Series and reassigning to the <code>x['Volume']</code> obect, which is a <code>pandas.core.series.Series</code> object.</p> <p>I have, however, found a solution to this problem using the <code>numpy</code> package's <code>float64</code> type - <strong><em>this works but I don't know why it's different</em></strong>.</p> <pre><code>In[]: xiv['Volume'] = xiv['Volume'].astype(np.float64) In[]: xiv['Volume'].dtypes Out[]: dtype('float64') </code></pre> <p>Can someone explain how to accomplish with the <code>pandas</code> library what the <code>numpy</code> library seems to do easily with its <code>float64</code> class; that is, convert the column in the <code>xiv</code> DataFrame to a <code>float64</code> in place.</p>
2
2016-10-17T21:10:28Z
40,095,999
<p>If you already have numeric dtypes (<code>int8|16|32|64</code>,<code>float64</code>,<code>boolean</code>) you can convert it to another "numeric" dtype using <strong>Pandas</strong> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow">.astype()</a> method.</p> <p>Demo:</p> <pre><code>In [90]: df = pd.DataFrame(np.random.randint(10**5,10**7,(5,3)),columns=list('abc'), dtype=np.int64) In [91]: df Out[91]: a b c 0 9059440 9590567 2076918 1 5861102 4566089 1947323 2 6636568 162770 2487991 3 6794572 5236903 5628779 4 470121 4044395 4546794 In [92]: df.dtypes Out[92]: a int64 b int64 c int64 dtype: object In [93]: df['a'] = df['a'].astype(float) In [94]: df.dtypes Out[94]: a float64 b int64 c int64 dtype: object </code></pre> <p>It won't work for <code>object</code> (string) dtypes, that <strong>can't</strong> be converted to numbers:</p> <pre><code>In [95]: df.ix[1, 'b'] = 'XXXXXX' In [96]: df Out[96]: a b c 0 9059440.0 9590567 2076918 1 5861102.0 XXXXXX 1947323 2 6636568.0 162770 2487991 3 6794572.0 5236903 5628779 4 470121.0 4044395 4546794 In [97]: df.dtypes Out[97]: a float64 b object c int64 dtype: object In [98]: df['b'].astype(float) ... skipped ... ValueError: could not convert string to float: 'XXXXXX' </code></pre> <p>So here we want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow">pd.to_numeric()</a> method:</p> <pre><code>In [99]: df.b = pd.to_numeric(df['b'], errors='coerse') In [100]: df Out[100]: a b c 0 9059440.0 9590567.0 2076918 1 5861102.0 NaN 1947323 2 6636568.0 162770.0 2487991 3 6794572.0 5236903.0 5628779 4 470121.0 4044395.0 4546794 In [101]: df.dtypes Out[101]: a float64 b float64 c int64 dtype: object </code></pre>
2
2016-10-17T21:31:19Z
[ "python", "pandas", "numpy", "dataframe", "types" ]
Vertica Python Connection
40,095,768
<p>I'm trying to connect to a Vertica database via Python. Here is what I have so far.</p> <p>Using <code>vertica_python</code>:</p> <pre><code>! pip install vertica_python from vertica_python import connect conn_info = {'host': '192.168...', 'port': my_port_number, 'user': 'my_uid', 'password': 'my_pwd', 'database': 'my_dbname', # 10 minutes timeout on queries 'read_timeout': 600, # default throw error on invalid UTF-8 results 'unicode_error': 'strict', # SSL is disabled by default 'ssl': False} connection = vertica_python.connect(**conn_info) </code></pre> <p>Gives the following error:</p> <pre><code>--------------------------------------------------------------------------- ConnectionError Traceback (most recent call last) &lt;ipython-input-3-629986180e1e&gt; in &lt;module&gt;() ----&gt; 1 connection = connect(host = "192.168...", port = my_port_number, user = 'my_uid', password ='my_pwd', database = 'my_dbname') /Users/MyUserName/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/vertica_python/__init__.pyc in connect(**kwargs) 28 def connect(**kwargs): 29 """Opens a new connection to a Vertica database.""" ---&gt; 30 return Connection(kwargs) /Users/MyUserName/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/vertica_python/vertica/connection.pyc in __init__(self, options) 36 self.options.setdefault('port', 5433) 37 self.options.setdefault('read_timeout', 600) ---&gt; 38 self.startup_connection() 39 40 def __enter__(self): /Users/MyUserName/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/vertica_python/vertica/connection.pyc in startup_connection(self) 255 256 while True: --&gt; 257 message = self.read_message() 258 259 if isinstance(message, messages.Authentication): /Users/MyUserName/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/vertica_python/vertica/connection.pyc in read_message(self) 190 "Bad message size: {0}".format(size) 191 ) --&gt; 192 message = BackendMessage.factory(type_, self.read_bytes(size - 4)) 193 logger.debug('&lt;= %s', message) 194 return message /Users/MyUserName/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/vertica_python/vertica/connection.pyc in read_bytes(self, n) 242 bytes_ = self._socket().recv(n - len(results)) 243 if not bytes_: --&gt; 244 raise errors.ConnectionError("Connection closed by Vertica") 245 results = results + bytes_ 246 return results ConnectionError: Connection closed by Vertica </code></pre> <p>Using <code>jaydebeapi</code> gives a different error:</p> <pre><code>! pip install jaydebeapi import jaydebeapi connection = jaydebeapi.connect('com.vertica.Driver', ['jdbc:vertica://...','my_uid','my_pwd'], '/Users/MyUserName/Documents/JAR Files/vertica-jdbc-4.1.14.jar') RuntimeError: Unable to load DLL [/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Libraries/libjvm.dylib], error = dlopen(/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Libraries/libjvm.dylib, 9): no suitable image found. Did find: /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Libraries/libjvm.dylib: mach-o, but wrong architecture at native/common/include/jp_platform_linux.h:45 </code></pre> <p>Lastly, I tried <code>pyodbc</code> but I'm not able to even import it:</p> <pre><code>! pip install pyodbc import pyodbc ImportError: dlopen(/Users/MyUserName/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pyodbc.so, 2): Library not loaded: /usr/local/lib/libodbc.2.dylib Referenced from: /Users/MyUserName/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/pyodbc.so Reason: image not found </code></pre> <p>I'm new to Python so any help is much appreciated</p>
0
2016-10-17T21:15:02Z
40,095,993
<p>You can pass key/value pair like that in Python.</p> <p>Use as follow:</p> <pre><code>from vertica_python import connect connection = connect( host='jdbc:vertica://...', port=my_port_number, user='my_uid', password='my_pwd' ) </code></pre>
0
2016-10-17T21:30:57Z
[ "python", "database-connectivity" ]
Python script for reformatting a text file into a csv using Python
40,095,784
<p>I have been asked to read in a text file containing this:</p> <pre class="lang-none prettyprint-override"><code>1. Wicked Stepmother (1989) as Miranda A couple comes home from vacation to find that their grandfather has … 2. Directed By William Wyler (1988) as Herself During the Golden Age of Hollywood, William Wyler was one of the … 3. Whales of August, The (1987) as Libby Strong Drama revolving around five unusual elderly characters, two of whom … 4. As Summers Die (1986) as Hannah Loftin Set in a sleepy Southern Louisiana town in 1959, a lawyer, searches … </code></pre> <p>and to create a .csv output file that looks like this:</p> <pre class="lang-none prettyprint-override"><code>1,Wicked Stepmother ,1989, as Miranda,A couple comes home from vacation … 2,Directed By William Wyler ,1988, as Herself,During the Golden Age of … 3,"Whales of August, The ",1987, as Libby Strong,Drama revolving around five… </code></pre> <p>I know that if I can slice the lines apart, then I can add them back together again with commas in between them and then write those strings into my output file. My problem is with the format. For the numbers I would only want:</p> <pre><code>line1=stringname[0]+',' line2= stringname[:stringname.find('(')-1]+','+stringname[stringname.find('(')+1:stringname.find(')')-1]+','+stringname[stringname.find(')')+1:] </code></pre> <p>no change to line3 then write into the file</p> <pre><code>result=line1+line2+line3 </code></pre> <p>The problem is I have no idea which line I am parsing at any given time. I was thinking maybe something in a for loop which makes sure I parse the code in groups of 3 lines at a time, but I am not sure how to manage the file handling at the same time. I am also not sure how to prevent the loop from going over the end of the program.</p>
-4
2016-10-17T21:16:02Z
40,107,510
<p>This could be done easily using a regular expression but I am guessing you do not wish to use that. </p> <p>Instead the problem can be solved by reading the file in a line at a time and deciding if the line starts with a number followed by a <code>.</code>. If it does, start you start building up a list of lines until you find the next number.</p> <p>Using Python's <code>int()</code> function will attempt to convert a string into a number. The <code>find('.')</code> function attempts to locate the end of the number.</p> <p>If the returned string is not a number, it causes a <code>ValueError</code> exception to be raised. In this case, add the line to the list of lines.</p> <p>If there was a number, first write any existing entry to the <code>csv</code> file, and then start a new entry.</p> <p>At the end, there will not be a final number line to trigger the next write, so add another call to write the final row to the csv.</p> <p>For example:</p> <pre><code>import csv with open('text.txt') as f_input, open('output.csv', 'wb') as f_output: csv_output = csv.writer(f_output) entry = [] for line in f_input: line = line.strip() # Remove the trailing newline if len(line): # Does the line containing anything? try: number = int(line[:line.find('.')]) if len(entry): csv_output.writerow(entry) entry = [number] except ValueError: entry.append(line) csv_output.writerow(entry) </code></pre> <p>Python's <code>csv</code> library is used to take a list and automatically add the necessary commas between entries when writing to the csv output file. If an entry contains a comma, it will automatically add quotes.</p>
1
2016-10-18T11:52:15Z
[ "python", "string", "csv", "file-handling" ]
SQLAlchemy: order by columns in chain joined relations
40,095,933
<p>In my app I'v got such models: </p> <pre class="lang-python prettyprint-override"><code>class A(Base): id = Column(UUID, primary_key=True) name_a = Column(Text) class B(Base): id = Column(UUID, primary_key=True) name_b = Column(Text) parent_a_id = Column(UUID, ForeignKey(A.id)) parent_a = relationship(A, lazy='joined') class C(Base): id = Column(UUID, primary_key=True) name_c = Column(Text) parent_b_id = Column(UUID, ForeignKey(B.id)) parent_b = relationship(B, lazy='joined') </code></pre> <p>When I do:</p> <pre class="lang-python prettyprint-override"><code>DBSession().query(C).all() </code></pre> <p>It works fine - I get all C names with it's B and A name in one LEFT OUTER JOIN query.</p> <p>But I wonder how to <strong>order by</strong> this query with: <strong>name_a, name_b, name_c</strong>?</p> <p>I'm trying to do something like:</p> <pre class="lang-python prettyprint-override"><code>DBSession().query(C).order_by( C.parent_b.parent_a.name_a, C.parent_b.name_b, C.name_c ).all() </code></pre> <p>Such code doesn't work. How it can be done with sqlalchemy spirit?</p>
0
2016-10-17T21:27:50Z
40,096,141
<p>I played around with your sample and used PostgreSQL for added points. </p> <p>Your query returns a list of C objects, and traditionally in SQL you can only sort by columns that you retrieve. The relations are retrieved behind the scenes so I don't see why it should be possible to sort by them. </p> <p>On the bright side, once your list is retrieved it comes with the entire hierarchy in your memory, so you can sort it in memory super-fast:</p> <pre><code>clist = session.query(C).all() sorted(clist, key=lambda c:(c.b.a.name, c.b.name, c.name)) </code></pre> <p>Another solution I found is to use order_by <code>parameter</code> for <code>relationship</code>:</p> <pre><code>class B(Base): ... a = relationship(A, order_by="A.name", lazy='joined') class C(Base): ... b = relationship(B, order_by="B.name", lazy='joined') </code></pre> <p>End result:</p> <pre><code>print (session.query(C).order_by(C.name) ) </code></pre> <blockquote> <p>ORDER BY tc.name, tb_1.name, ta_1.name</p> </blockquote> <p>This is close to what you wanted but you will need to reverse the list to get it in the <code>A.name, B.name, C.name</code> order.</p> <p><strong>P.S.:</strong> my exact class definitions for reference:</p> <pre><code>#!/usr/bin/env python from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, ForeignKey, create_engine, Text from sqlalchemy.orm import relationship engine_connect_str = "postgresql://postgres@MYSERV/mydb" engine = create_engine(engine_connect_str, echo=False) Session = sessionmaker(engine) session = Session() Base = declarative_base() class A(Base): __tablename__ = 'ta' id = Column('id', Integer, primary_key=True) name = Column(Text) def __repr__(self): return "{}(id={}, name='{}')".format(self.__class__.__name__, self.id, self.name) class B(Base): __tablename__ = 'tb' id = Column('id', Integer,primary_key=True) name = Column(Text) a_id = Column('aid', ForeignKey(A.id), nullable=False) a = relationship(A, order_by="A.name", lazy='joined') def __repr__(self): return "{}(id={}, name='{}', a_id={})".format(self.__class__.__name__, self.id, self.name, self.a_id) class C(Base): __tablename__ = 'tc' id = Column('id', Integer, primary_key=True) name = Column(Text) b_id = Column('bid', ForeignKey(B.id), nullable=False) b = relationship(B, order_by="B.name", lazy='joined') def __repr__(self): return "{}(id={}, name='{}', b_id={})".format(self.__class__.__name__, self.id, self.name, self.b_id) </code></pre>
1
2016-10-17T21:41:25Z
[ "python", "sqlalchemy", "order", "sql-order-by", "relation" ]
Generating random numbers as the value of dictionary in python
40,096,005
<p>Could you please tell me how can I generate a dictionary with 100 rows that have random number between 0 and 1 in each row as the value? For example in data frame, I can have:</p> <pre><code> df['Rand'] = random.sample(random.random(), 100) </code></pre> <p>But I don't know how to do that for a dictionary.</p>
-1
2016-10-17T21:31:44Z
40,096,044
<p>Firstly, it should be <code>list</code> and not <code>dict</code>. Check: <a href="http://stackoverflow.com/questions/3489071/in-python-when-to-use-a-dictionary-list-or-set">In Python, when to use a Dictionary, List or Set?</a></p> <p>In order to get the list of values, you may use <em>list comprehension</em> as: </p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; row_count = 10 &gt;&gt;&gt; my_list = [random.random() for i in range(row_count)] # Value of 'my_list': # [0.9158936600374181, 0.8998648755500501, 0.07002867165493243, 0.6694284854833131, 0.4903966580363698, 0.9462143737260301, 0.8014661448602305, 0.47964245438139297, 0.42326131297319725, 0.77540761767324] </code></pre> <p>In order to fetch 5th item (i.e. 4th index):</p> <pre><code>&gt;&gt;&gt; my_list[4] 0.4903966580363698 </code></pre>
0
2016-10-17T21:34:27Z
[ "python", "dictionary", "random" ]
Generating random numbers as the value of dictionary in python
40,096,005
<p>Could you please tell me how can I generate a dictionary with 100 rows that have random number between 0 and 1 in each row as the value? For example in data frame, I can have:</p> <pre><code> df['Rand'] = random.sample(random.random(), 100) </code></pre> <p>But I don't know how to do that for a dictionary.</p>
-1
2016-10-17T21:31:44Z
40,096,074
<p>I think what you want is something like:</p> <pre><code>{k: random.random() for k in range(100)} </code></pre>
2
2016-10-17T21:36:54Z
[ "python", "dictionary", "random" ]
pandas subset using sliced boolean index
40,096,059
<p>code to make test data:</p> <pre><code>import pandas as pd import numpy as np testdf = {'date': range(10), 'event': ['A', 'A', np.nan, 'B', 'B', 'A', 'B', np.nan, 'A', 'B'], 'id': [1] * 7 + [2] * 3} testdf = pd.DataFrame(testdf) print(testdf) </code></pre> <p>gives </p> <pre><code> date event id 0 0 A 1 1 1 A 1 2 2 NaN 1 3 3 B 1 4 4 B 1 5 5 A 1 6 6 B 1 7 7 NaN 2 8 8 A 2 9 9 B 2 </code></pre> <p>subset testdf</p> <pre><code>df_sub = testdf.loc[testdf.event == 'A',:] print(df_sub) date event id 0 0 A 1 1 1 A 1 5 5 A 1 8 8 A 2 </code></pre> <p><strong>(Note: not re-indexed)</strong></p> <p>create conditional boolean index</p> <pre><code>bool_sliced_idx1 = df_sub.date &lt; 4 bool_sliced_idx2 = (df_sub.date &gt; 4) &amp; (df_sub.date &lt; 6) </code></pre> <p>I want to insert conditional values using this new index in original df, like</p> <pre><code>dftest[ 'new_column'] = np.nan dftest.loc[bool_sliced_idx1, 'new_column'] = 'new_conditional_value' </code></pre> <p>which obviously (now) gives error:</p> <pre><code>pandas.core.indexing.IndexingError: Unalignable boolean Series key provided </code></pre> <p><code>bool_sliced_idx1</code> looks like</p> <pre><code>&gt;&gt;&gt; print(bool_sliced_idx1) 0 True 1 True 5 False 8 False Name: date, dtype: bool </code></pre> <p>I tried <code>testdf.ix[(bool_sliced_idx1==True).index,:]</code>, but that doesn't work because</p> <pre><code>&gt;&gt;&gt; (bool_sliced_idx1==True).index Int64Index([0, 1, 5, 8], dtype='int64') </code></pre>
0
2016-10-17T21:35:46Z
40,096,523
<p>This worked</p> <pre><code>idx = np.where(bool_sliced_idx1==True)[0] ## or # np.ravel(np.where(bool_sliced_idx1==True)) idx_original = df_sub.index[idx] testdf.iloc[idx_original,:] </code></pre>
0
2016-10-17T22:14:07Z
[ "python", "pandas", "indexing", "dataframe", "slice" ]
pandas subset using sliced boolean index
40,096,059
<p>code to make test data:</p> <pre><code>import pandas as pd import numpy as np testdf = {'date': range(10), 'event': ['A', 'A', np.nan, 'B', 'B', 'A', 'B', np.nan, 'A', 'B'], 'id': [1] * 7 + [2] * 3} testdf = pd.DataFrame(testdf) print(testdf) </code></pre> <p>gives </p> <pre><code> date event id 0 0 A 1 1 1 A 1 2 2 NaN 1 3 3 B 1 4 4 B 1 5 5 A 1 6 6 B 1 7 7 NaN 2 8 8 A 2 9 9 B 2 </code></pre> <p>subset testdf</p> <pre><code>df_sub = testdf.loc[testdf.event == 'A',:] print(df_sub) date event id 0 0 A 1 1 1 A 1 5 5 A 1 8 8 A 2 </code></pre> <p><strong>(Note: not re-indexed)</strong></p> <p>create conditional boolean index</p> <pre><code>bool_sliced_idx1 = df_sub.date &lt; 4 bool_sliced_idx2 = (df_sub.date &gt; 4) &amp; (df_sub.date &lt; 6) </code></pre> <p>I want to insert conditional values using this new index in original df, like</p> <pre><code>dftest[ 'new_column'] = np.nan dftest.loc[bool_sliced_idx1, 'new_column'] = 'new_conditional_value' </code></pre> <p>which obviously (now) gives error:</p> <pre><code>pandas.core.indexing.IndexingError: Unalignable boolean Series key provided </code></pre> <p><code>bool_sliced_idx1</code> looks like</p> <pre><code>&gt;&gt;&gt; print(bool_sliced_idx1) 0 True 1 True 5 False 8 False Name: date, dtype: bool </code></pre> <p>I tried <code>testdf.ix[(bool_sliced_idx1==True).index,:]</code>, but that doesn't work because</p> <pre><code>&gt;&gt;&gt; (bool_sliced_idx1==True).index Int64Index([0, 1, 5, 8], dtype='int64') </code></pre>
0
2016-10-17T21:35:46Z
40,096,535
<p>IIUC, you can just combine all of your conditions at once, instead of trying to chain them. For example, <code>df_sub.date &lt; 4</code> is really just <code>(testdf.event == 'A') &amp; (testdf.date &lt; 4)</code>. So, you could do something like:</p> <pre><code># Create the conditions. cond1 = (testdf.event == 'A') &amp; (testdf.date &lt; 4) cond2 = (testdf.event == 'A') &amp; (testdf.date.between(4, 6, inclusive=False)) # Make the assignments. testdf.loc[cond1, 'new_col'] = 'foo' testdf.loc[cond2, 'new_col'] = 'bar' </code></pre> <p>Which would give you:</p> <pre><code> date event id new_col 0 0 A 1 foo 1 1 A 1 foo 2 2 NaN 1 NaN 3 3 B 1 NaN 4 4 B 1 NaN 5 5 A 1 bar 6 6 B 1 NaN 7 7 NaN 2 NaN 8 8 A 2 NaN 9 9 B 2 NaN </code></pre>
3
2016-10-17T22:15:46Z
[ "python", "pandas", "indexing", "dataframe", "slice" ]
The positions of all vowels in the string
40,096,173
<p>I am trying to write programs that reads a line of input as a string and print the positions of all vowels in the string.</p> <pre><code>line = str(input("Enter a line of text: ")) vowels = ('a', 'e', 'i', 'o', 'u') position = "" for i in line : if i.lower() in vowels : position += ("%d ", i) print("Positions of Vowels " + position) </code></pre> <p>Expected: <code>Positions of Vowels 1,3,4,5,</code></p> <p>Gives me: <code>Positions of Vowels</code></p> <p>What can I do?</p>
-3
2016-10-17T21:43:44Z
40,096,207
<p>If you want a list of indexes, the following should work using <code>enumerate</code>:</p> <pre><code>&gt;&gt;&gt; text = 'hello world vowel' &gt;&gt;&gt; vowels = 'aeiou' &gt;&gt;&gt; [i for i, c in enumerate(text.lower()) if c in vowels] [1, 4, 7, 13, 15] </code></pre> <p>For your comma formatting:</p> <pre><code>&gt;&gt;&gt; ', '.join(str(i) for i, c in enumerate(text.lower()) if c in vowels) '1, 4, 7, 13, 15' </code></pre>
4
2016-10-17T21:47:25Z
[ "python", "string", "python-3.x" ]
Find most frequent phone number from given .txt file
40,096,185
<p>For example: me.txt (which conatains data as well as phone numbers)which has below info</p> <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 1.Phone number 1: (999) 999-3333 2.phone number 2: (888) 999 -2212 3.Phone number 3: (111) 222 - 2223 4.Phone number 4: (999)999-3333 5.Phone number 5: (888)222-2222 Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 6.Phone number: (999)999-3333 </code></pre> <p>so the <strong>o/p</strong> should be : (999)999-3333 - 3 times </p> <p>My try:</p> <pre><code>txtFile = urllib.urlopen("http:// me.txt").readlines() txtFile = "".join(char for char in txtFile if char.isdigit()) #removes everything that's not numeric. phone_counter = {} for phone in txtFile.split(" "): # split in every space. if len(phone) &gt; 0 : if phone not in phone_counter: phone_counter[phone] = 1 else: phone_counter[phone] += 1 for i,phone in enumerate(sorted(phone_counter,key=phone_counter.get,reverse=True)[:-1]): print "%s: %s - %s"%(i+1,phone,phone_counter[phone]) </code></pre> <p>This way I can't read numbers .Looking for <strong>python</strong> solution</p>
0
2016-10-17T21:45:14Z
40,096,221
<p>You just need <code>collections.Counter</code></p> <pre><code>from collections import Counter text = '''\ (999) 999-3333 (888) 999-2212 (111) 222-2223 (999) 999-3333 (888) 222-2222 (999) 999-3333 ''' counter = Counter() for phone in text.split('\n'): counter[phone] += 1 print counter.most_common(1) </code></pre>
3
2016-10-17T21:48:27Z
[ "python" ]
Find most frequent phone number from given .txt file
40,096,185
<p>For example: me.txt (which conatains data as well as phone numbers)which has below info</p> <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 1.Phone number 1: (999) 999-3333 2.phone number 2: (888) 999 -2212 3.Phone number 3: (111) 222 - 2223 4.Phone number 4: (999)999-3333 5.Phone number 5: (888)222-2222 Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 6.Phone number: (999)999-3333 </code></pre> <p>so the <strong>o/p</strong> should be : (999)999-3333 - 3 times </p> <p>My try:</p> <pre><code>txtFile = urllib.urlopen("http:// me.txt").readlines() txtFile = "".join(char for char in txtFile if char.isdigit()) #removes everything that's not numeric. phone_counter = {} for phone in txtFile.split(" "): # split in every space. if len(phone) &gt; 0 : if phone not in phone_counter: phone_counter[phone] = 1 else: phone_counter[phone] += 1 for i,phone in enumerate(sorted(phone_counter,key=phone_counter.get,reverse=True)[:-1]): print "%s: %s - %s"%(i+1,phone,phone_counter[phone]) </code></pre> <p>This way I can't read numbers .Looking for <strong>python</strong> solution</p>
0
2016-10-17T21:45:14Z
40,096,378
<p>You have several problems in the code. I fixed the indentation error on the last line. Next, your approach has to iterate through the characters of the file; <strong>readlines</strong> returns a list of strings, one per line. Your second line necessarily returns null, because there's no entire line that will satisfy <strong>isdigit</strong>.</p> <p>Also, note that stripping out all the non-digits would leave you with a string of 60 digits. I don't think this is what you want.</p> <p>I strongly recommend you start over and use incremental programming: write a couple of lines to retrieve the input. Debug those. Do not advance until those work. <em>Then</em> you can write the processing you want for detecting phone numbers.</p> <p>Thanks to the other answer, all you need do from here is to separate the file into phone numbers on separate lines. Be careful: the phone numbers have embedded spaces.</p>
0
2016-10-17T22:00:17Z
[ "python" ]
Find most frequent phone number from given .txt file
40,096,185
<p>For example: me.txt (which conatains data as well as phone numbers)which has below info</p> <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 1.Phone number 1: (999) 999-3333 2.phone number 2: (888) 999 -2212 3.Phone number 3: (111) 222 - 2223 4.Phone number 4: (999)999-3333 5.Phone number 5: (888)222-2222 Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 6.Phone number: (999)999-3333 </code></pre> <p>so the <strong>o/p</strong> should be : (999)999-3333 - 3 times </p> <p>My try:</p> <pre><code>txtFile = urllib.urlopen("http:// me.txt").readlines() txtFile = "".join(char for char in txtFile if char.isdigit()) #removes everything that's not numeric. phone_counter = {} for phone in txtFile.split(" "): # split in every space. if len(phone) &gt; 0 : if phone not in phone_counter: phone_counter[phone] = 1 else: phone_counter[phone] += 1 for i,phone in enumerate(sorted(phone_counter,key=phone_counter.get,reverse=True)[:-1]): print "%s: %s - %s"%(i+1,phone,phone_counter[phone]) </code></pre> <p>This way I can't read numbers .Looking for <strong>python</strong> solution</p>
0
2016-10-17T21:45:14Z
40,096,395
<p>Your text file seems to have some non-related stuff around it. Taking just the numbers will make the numbers unreadable as they are merged with random numbers in the text.</p> <p>Since I can't tell the exact format of the phone numbers on a line, you can use a regex to extract the number from a line.</p> <p>You can also use a <code>collections.Counter</code>, as in the above answer.</p> <pre><code>import re from collections import Counter NUMBER_RE = re.compile(r'\((\d{3})\)\s?(\d{3})\s?-\s?(\d{4})') # \d{3} = 3 digits # \s? = optional space def format_number(re_match): """Makes sure that the spacing is consisten to count them properly""" return '({0[0]}) {0[1]} - {0[2]}'.format(re_match) txtFile = urllib.urlopen("http:// me.txt").readlines() counter = Counter() for line in txtFile: for match in NUMBER_RE.findall(line): counter[format_number(match)] += 1 most_common = counter.most_common(1)[0] print("'{0[0]}' appears {0[1]} times.".format(most_common)) </code></pre>
0
2016-10-17T22:02:13Z
[ "python" ]
What does the Python operater ilshift (<<=)?
40,096,260
<p>What does the Python operator ilshift (&lt;&lt;=) and where can I find infos about it?</p> <p>Thanks</p> <p><a href="https://docs.python.org/2/library/operator.html#operator.ilshift" rel="nofollow">https://docs.python.org/2/library/operator.html#operator.ilshift</a></p> <p><a href="http://www.pythonlake.com/python/operators/operatorilshift" rel="nofollow">http://www.pythonlake.com/python/operators/operatorilshift</a></p> <p>Found no info about what it does in the documentation.</p>
-5
2016-10-17T21:51:30Z
40,096,508
<p>It is an BitwiseOperators (Bitwise Right Shift): <a href="https://wiki.python.org/moin/BitwiseOperators" rel="nofollow">https://wiki.python.org/moin/BitwiseOperators</a></p> <blockquote> <p>All of these operators share something in common -- they are "bitwise" operators. That is, they operate on numbers (normally), but instead of treating that number as if it were a single value, they treat it as if it were a string of bits, written in twos-complement binary.</p> </blockquote> <p>More infos:</p> <p><a href="https://www.tutorialspoint.com/python/bitwise_operators_example.htm" rel="nofollow">https://www.tutorialspoint.com/python/bitwise_operators_example.htm</a></p> <p><a href="http://stackoverflow.com/questions/6385792/what-does-a-bitwise-shift-left-or-right-do-and-what-is-it-used-for">What does a bitwise shift (left or right) do and what is it used for?</a></p>
-1
2016-10-17T22:12:52Z
[ "python" ]
Creating histograms in pandas with columns with equidistant base, not proportional to the range
40,096,278
<p>I am creating an histogram in pandas simply using:</p> <pre><code>train_data.hist("MY_VARIABLE", bins=[0,5, 10,50,100,500,1000,5000,10000,50000,100000]) </code></pre> <p>(train_data is a pandas df).</p> <p>The problem is that, since the range <code>[50000,100000]</code> is so large, I can barely see the small ranges <code>[0,5]</code> or <code>[5,10]</code> etc. I would like the histogram to have equidistant bars on the x-axis, not proportional to the range. Is this possible?</p>
2
2016-10-17T21:52:57Z
40,096,493
<p>You can do it this way:</p> <pre><code>bins = [0, 5, 10,50,100,500,1000,5000,10000,50000,100000] df.groupby(pd.cut(df.a, bins=bins, labels=bins[1:])).size().plot.bar(rot=0) </code></pre> <p>Demo:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,10**5,(10**4,2)),columns=list('ab')) bins = [0, 5, 10,50,100,500,1000,5000,10000,50000,100000] df.groupby(pd.cut(df.a, bins=bins, labels=bins[1:])).size().plot.bar(rot=0) </code></pre> <p><a href="https://i.stack.imgur.com/63Awq.png" rel="nofollow"><img src="https://i.stack.imgur.com/63Awq.png" alt="enter image description here"></a></p> <p>filtering results:</p> <pre><code>threshold = 100 (df.groupby(pd.cut(df.a, bins=bins, labels=bins[1:])) .size() .to_frame('count') .query('count &gt; @threshold') ) Out[84]: count a 5000 396 10000 492 50000 4044 100000 4961 </code></pre> <p>plotting filtered:</p> <pre><code>(df.groupby(pd.cut(df.a, bins=bins, labels=bins[1:])) .size() .to_frame('count') .query('count &gt; @threshold') .plot.bar(rot=0, width=1.0) ) </code></pre> <p><a href="https://i.stack.imgur.com/dL0yM.png" rel="nofollow"><img src="https://i.stack.imgur.com/dL0yM.png" alt="enter image description here"></a></p>
1
2016-10-17T22:11:30Z
[ "python", "pandas", "histogram" ]
Why getting Memory Error? Python
40,096,308
<p>I have a 5gb text file and i am trying to read it line by line. My file is in format-: Reviewerid&lt;\t>pid&lt;\t>date&lt;\t>title&lt;\t>body&lt;\n> This is my code </p> <pre><code>o = open('mproducts.txt','w') with open('reviewsNew.txt','rb') as f1: for line in f1: line = line.strip() line2 = line.split('\t') o.write(str(line)) o.write("\n") </code></pre> <p>But i get Memory error when i try to run it. I have an 8gb ram and 1Tb space then why am i getting this error? I tried to read it in blocks but then also i get that error.</p> <pre><code>MemoryError </code></pre>
3
2016-10-17T21:55:15Z
40,096,817
<p><strong>Update:</strong></p> <p>Installing 64 bit Python solves the issue.</p> <p>OP was using 32 bit Python that's why getting into memory limitation.</p> <hr> <p>Reading whole comments I think this can help you.</p> <ul> <li>You can't read file in chunk (as 1024) since you want to process data.</li> <li>Instead, read file in chunk of lines i.e N lines at a time.</li> <li>You can use <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do">yield</a> keyword and <a href="https://pymotw.com/2/itertools/" rel="nofollow">itertools</a> in Python to achieve above. </li> </ul> <p><strong><em>Summary</strong> : Get N lines at time, process it and then write it.</em></p> <p><strong>Sample Code :</strong></p> <pre><code>from itertools import islice #You can change num_of_lines def get_lines(file_handle,num_of_lines = 10): while True: next_n_lines = list(islice(file_handle, num_of_lines)) if not next_n_lines: break yield next_n_lines o = open('mproducts.txt','w') with open('reviewsNew.txt','r') as f1: for data_lines in get_lines(f1): for line in data_lines: line = line.strip() line2 = line.split('\t') o.write(str(line)) o.write("\n") o.close() </code></pre>
2
2016-10-17T22:44:35Z
[ "python" ]
Lambda function does not return correct value
40,096,323
<p>Im trying to make a variant of the Gillespie algorithm, and to determine the reaction propensities Im trying to automatically generate the propensity vector using lambda expressions. However when creating SSA.P all goes wrong. The last loop in the block of code, PROPLOOP, returns two propensities, where the one generated using P_alternative is the correct one. The question is: how do I get the same values for SSA.P as for SSA.P_alternative?</p> <pre><code>import numpy as np from numpy.random import uniform class Markov: def __init__(self,z0,t0,tf,rates,stoich): self.S=stoich self.z0=z0 self.rates=rates self.P=self.propensities() self.P_alternative=[ lambda z,rate:(0.5*rate[0]*z[0]*(z[0]-1)), lambda z,rate:rate[1]*np.prod(z[0]), lambda z,rate:rate[2]*np.prod(z[1]), lambda z,rate:rate[3]*np.prod(z[1]), lambda z,rate:rate[4]*np.prod(z[np.array([0,1])]), lambda z,rate:rate[5]] self.t0=t0 self.tf=tf def propensities(self): prop=[] for i,reac in enumerate(self.S.T): if all(z&gt;=0 for z in reac): prop.append(lambda z,rate:rate[i]) if any(z==-1 for z in reac): j=np.where(reac==-1)[0] prop.append(lambda z,rate:rate[i]*np.prod(z[j])) if any(z==-2 for z in reac): j=np.where(reac==-2)[0][0] prop.append(lambda z,rate:(0.5*rate[i]*z[j]*(z[j]-1))[0]) return prop stoich=np.array([ [-2, -1, 2, 0, -1, 0], [ 1, 0, -1, -1, -1, 1], [ 0, 0, 0, 1, 1, 0]]) rates=np.array([1.0,0.02,200.0,0.0004,0.9,0.9]) z0=np.array([540,730,0]) SSA=Markov(z0=z0,t0=0,tf=100,rates=rates,stoich=stoich) #PROPLOOP; the values should be equal for both SSA.P and SSA.P_alternative, where SSA.P_alternative is the correct one for i in xrange(len(SSA.P)): print "Inexplicably wrong",SSA.P[i](z0,rates) print "Correct answer",SSA.P_alternative[i](z0,rates), "\n" </code></pre> <p>output is:</p> <pre><code>Inexplicably wrong 130977.0 Correct answer 145530.0 Inexplicably wrong 354780.0 Correct answer 10.8 Inexplicably wrong 354780.0 Correct answer 146000.0 Inexplicably wrong 354780.0 Correct answer 0.292 Correct answer 354780.0 Correct answer 354780.0 Inexplicably wrong 0.9 Correct answer 0.9 </code></pre>
3
2016-10-17T21:56:29Z
40,096,669
<p>The issue is that you're creating your <code>lambda</code> functions in a loop, and they refer to the variables <code>i</code> and <code>j</code> that may change as the loop goes on.</p> <p>The lambda doesn't copy the values of <code>i</code> or <code>j</code> when it is created, it just keeps a reference to the namespace that they are defined in. When it uses the variables when it is called later, it looks them up in that namespace. Since your lambdas get called after the loop (and indeed, the whole function) has ended, they all see the final values the variables were given, which is not what you intended. This explains why the two versions of your code give the same output on the last iteration. The final value of <code>i</code> and <code>j</code> is the expected one for the last <code>lambda</code> function.</p> <p>You can work around this issue by making the <code>lambda</code> keep a copy of the current value of <code>i</code> and <code>j</code> when it is defined. The easiest way to do this is with a default argument:</p> <pre><code>for i,reac in enumerate(self.S.T): if all(z&gt;=0 for z in reac): prop.append(lambda z, rate, i=i: rate[i]) # add i=i here and further down if any(z==-1 for z in reac): j=np.where(reac==-1)[0] prop.append(lambda z, rate, i=i, j=j: rate[i]*np.prod(z[j])) if any(z==-2 for z in reac): j=np.where(reac==-2)[0][0] prop.append(lambda z, rate, i=i, j=j: (0.5*rate[i]*z[j]*(z[j]-1))[0]) </code></pre> <p>The <code>i=i</code> (and <code>j=j</code> where necessary) in the lambda definitions makes the variables arguments of the lambda function with a default value that is the current value of <code>i</code> (and <code>j</code>) in the outer namespace. Since you only pass two arguments when you call the lambda function, the saved default values will be used.</p>
2
2016-10-17T22:27:20Z
[ "python", "numpy", "lambda" ]
ipython 5.1 export interactive session to script
40,096,497
<p>So, I know I can export an ipython session to a notebook, and then convert that notebook to many format using <code>jupyter nbconvert ...</code>. </p> <p>However, the <a href="http://ipython.readthedocs.io/en/stable/interactive/magics.html?highlight=magic#magic-notebook" rel="nofollow">doc</a> also says I should be able to export the session directly to a python script if I give the filename a <code>.py</code> extension. That doesn't work, it still generates a notebook json file. </p> <p>Can I get the desired behavior in some way?</p> <p>Thanks.</p>
0
2016-10-17T22:11:51Z
40,118,328
<p>The answer was, as Thomas K. said, use <code>%history -f ...</code> instead...</p>
0
2016-10-18T21:24:22Z
[ "python", "session", "ipython", "jupyter-notebook", "ipython-magic" ]
Django general and app templates
40,096,516
<p>I want to customize my Django project, I will have a dashboard app and a home site app (you can enter from this home site to the dashboard with a URL). I want to save a template for the HTML and css so both apps can use them.</p> <p>I followed <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial07/#customizing-your-project-s-templates" rel="nofollow">this</a> tutorial on django official site, but I think I missed a setup because. This is the error: <code>Not Found: /css/style.css</code>. </p> <p>At this point, my django project is structured this way, I think that I will add another app (module) to serve the home page:</p> <pre><code>mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py dashboard/ __init__.py admin.py migrations/ __init__.py 0001_initial.py models.py static/ templates/ polls/ index.html tests.py urls.py views.py templates/ css/ style.css </code></pre> <p>And my settings.py is like this:</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'mysite/templates/'), os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] </code></pre>
0
2016-10-17T22:13:15Z
40,115,188
<p>I found a way to do this. The problem isn't with the templates settings, the problem is with the <code>staticfiles_dir</code>.</p> <pre><code>STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), 'var/css/style.css' ] </code></pre> <p>It is important to remark that the templates should have <code>&lt;link rel="stylesheet" href={% static 'css/style.css' %}&gt;</code></p> <p>I also loaded HTML files that are general templates for various apps.</p>
0
2016-10-18T18:11:03Z
[ "python", "django", "django-templates" ]
Getting KeyError : 3
40,096,574
<p>Getting KeyError: 3 when trying to do the following to find the topological sort:</p> <pre><code>def dfs_topsort(graph): # recursive dfs with L = [] # additional list for order of nodes color = { u : "white" for u in graph } found_cycle = [False] for u in graph: if color[u] == "white": dfs_visited(graph, u, color, L, found_cycle) if found_cycle[0]: break if found_cycle[0]: # if there is a cycle, L = [] # then return an empty list L.reverse() # reverse the list return L # L contains the topological sort def dfs_visited(graph, u, color, L, found_cycle): if found_cycle[0]: return color[u] = "gray" for v in graph[u]: if color[v] == "gray": found_cycle[0] = True return if color[v] == "white": dfs_visited(graph, v, color, L, found_cycle) color[u] = "black" # when we're done with u, L.append(u) graph_tasks = {1: [2,11], 2: [3], 11: [12], 12: [13] } order = dfs_topsort(graph_tasks) for task in order: print(task) </code></pre> <p>I'm getting KeyError: 3 for the above example. Why is that so? How can it be fixed?</p>
0
2016-10-17T22:19:33Z
40,096,684
<p>It seems that the <code>dfs_topsort</code> algorithm needs a <code>key</code> for every <code>value</code> that exists in the graph. </p> <p>So we need to include keys for each of the values. The first one that's missing is <code>3</code>, which caused the <code>KeyError: 3</code>, and also <code>13</code>. If we include these keys and give them empty values (because they are not connected to any other nodes) then it fixes the error.</p> <p>Also, the other example you gave in the comment works because every value (right-hand side) ( <code>[2,3], [4, 5, 6], [4, 6], [5, 6], [6], []</code> ) is also in the Key values (left-hand side) [<code>1, 2, 3, 4, 5, 6</code>].</p> <p>So using <code>graph_tasks = { 1: [2, 11], 2: [3], 3: [], 11: [12], 12: [13], 13: [] }</code> gives the output you may be expecting.</p> <p>I hope this helps you.</p>
0
2016-10-17T22:29:45Z
[ "python", "graph", "dfs", "topological-sort" ]
Using print as class method name in Python
40,096,601
<p>Does Python disallow using <code>print</code> (or other reserved words) in class method name?</p> <p><code>$ cat a.py</code></p> <pre><code>import sys class A: def print(self): sys.stdout.write("I'm A\n") a = A() a.print() </code></pre> <p><code>$ python a.py</code></p> <pre><code>File "a.py", line 3 def print(self): ^ SyntaxError: invalid syntax </code></pre> <p>Change <code>print</code> to other name (e.g., <code>aprint</code>) will not produce the error. It is surprising to me if there's such restriction. In C++ or other languages, this won't be a problem:</p> <pre><code>#include&lt;iostream&gt; #include&lt;string&gt; using namespace std; class A { public: void printf(string s) { cout &lt;&lt; s &lt;&lt; endl; } }; int main() { A a; a.printf("I'm A"); } </code></pre>
2
2016-10-17T22:21:41Z
40,096,640
<p>The restriction is gone in Python 3, when print was changed from a statement to a function. Indeed, you can get the new behaviour in Python 2 with a future import:</p> <pre><code>&gt;&gt;&gt; from __future__ import print_function &gt;&gt;&gt; import sys &gt;&gt;&gt; class A(object): ... def print(self): ... sys.stdout.write("I'm A\n") ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.print() I'm A </code></pre> <p>As a style note, it's unusual for a python class to define a <code>print</code> method. More pythonic is <em>return</em> a value from the <code>__str__</code> method, which customises how an instance will display when it is printed. </p> <pre><code>&gt;&gt;&gt; class A(object): ... def __str__(self): ... return "I'm A" ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; print(a) I'm A </code></pre>
2
2016-10-17T22:25:05Z
[ "python", "printing", "reserved" ]
Using print as class method name in Python
40,096,601
<p>Does Python disallow using <code>print</code> (or other reserved words) in class method name?</p> <p><code>$ cat a.py</code></p> <pre><code>import sys class A: def print(self): sys.stdout.write("I'm A\n") a = A() a.print() </code></pre> <p><code>$ python a.py</code></p> <pre><code>File "a.py", line 3 def print(self): ^ SyntaxError: invalid syntax </code></pre> <p>Change <code>print</code> to other name (e.g., <code>aprint</code>) will not produce the error. It is surprising to me if there's such restriction. In C++ or other languages, this won't be a problem:</p> <pre><code>#include&lt;iostream&gt; #include&lt;string&gt; using namespace std; class A { public: void printf(string s) { cout &lt;&lt; s &lt;&lt; endl; } }; int main() { A a; a.printf("I'm A"); } </code></pre>
2
2016-10-17T22:21:41Z
40,096,661
<p><strong>print</strong> is a reserved word in Python 2.x, so you can't use it as an identifier. Here is a list of reserved words in Python: <a href="https://docs.python.org/2.5/ref/keywords.html" rel="nofollow">https://docs.python.org/2.5/ref/keywords.html</a>.</p>
0
2016-10-17T22:26:46Z
[ "python", "printing", "reserved" ]
How do I open a text file in Python?
40,096,612
<p>Currently I am trying to open a text file called "temperature.txt" i have saved on my desktop using file handler, however for some reason i cannot get it to work. Could anyone tell me what im doing wrong.</p> <pre><code>#!/Python34/python from math import * fh = open('temperature.txt') num_list = [] for num in fh: num_list.append(int(num)) fh.close() </code></pre>
2
2016-10-17T22:22:16Z
40,098,340
<p>You simply need to use .readlines() on fh</p> <p>like this:</p> <pre><code>#!/Python34/python from math import * fh = open('temperature.txt') num_list = [] read_lines = fh.readlines() for line in read_lines: num_list.append(int(line)) fh.close() </code></pre>
-1
2016-10-18T01:57:39Z
[ "python", "python-3.x", "filehandler" ]
How do I open a text file in Python?
40,096,612
<p>Currently I am trying to open a text file called "temperature.txt" i have saved on my desktop using file handler, however for some reason i cannot get it to work. Could anyone tell me what im doing wrong.</p> <pre><code>#!/Python34/python from math import * fh = open('temperature.txt') num_list = [] for num in fh: num_list.append(int(num)) fh.close() </code></pre>
2
2016-10-17T22:22:16Z
40,103,074
<p>The pythonic way to do this is </p> <pre><code>#!/Python34/python from math import * num_list = [] with open('temperature.text', 'r') as fh: for line in fh: num_list.append(int(line)) </code></pre> <p>You don't need to use close here because the 'with' statement handles that automatically.</p> <p>If you are comfortable with List comprehensions - this is another method : </p> <pre><code>#!/Python34/python from math import * with open('temperature.text', 'r') as fh: num_list = [int(line) for line in fh] </code></pre> <p>In both cases 'temperature.text' must be in your current directory, and I have left the math module import, although neither piece of code needs it</p>
0
2016-10-18T08:19:12Z
[ "python", "python-3.x", "filehandler" ]
How do I send a DHCP request to find DHCP server IP address? Is this possible?
40,096,621
<p>Is it possible to write a small script that will send out a DHCP broadcast request and find the DHCP server address?</p> <p>I need this for a project, but my research led me to believe that you cannot do this on Windows? I would need a small script for OSX, Linux and Windows. </p>
3
2016-10-17T22:23:09Z
40,096,738
<p>I think you're asking an <a href="http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY Problem</a>: You want to know how to find the DHCP IP address on windows, via python?</p> <p>There is a solution on SuperUser for <a href="http://superuser.com/questions/314145/how-to-find-my-dhcp-server-ip-address-via-a-command-prompt-in-windows/314147">obtaining DHCP server ip from the command line</a>. You can wrap <code>ipconfig /all</code> with <code>subprocess</code> and then parse the output:</p> <pre><code>import subprocess # Runs a command on the cmd line res = subprocess.check_output("ipconfig /all") </code></pre>
0
2016-10-17T22:36:53Z
[ "python", "dhcp" ]
How do I send a DHCP request to find DHCP server IP address? Is this possible?
40,096,621
<p>Is it possible to write a small script that will send out a DHCP broadcast request and find the DHCP server address?</p> <p>I need this for a project, but my research led me to believe that you cannot do this on Windows? I would need a small script for OSX, Linux and Windows. </p>
3
2016-10-17T22:23:09Z
40,097,001
<p>Okay, I'm going to make the assumption that your default gateway is configured to point at your DHCP server. I found the following package and was able to get my default gateway:</p> <pre><code>#!/usr/bin/env python import netifaces gateway_info = netifaces.gateways() print(gateway_info) </code></pre> <p>I of course first had to install the <code>netifaces</code> module via pip:</p> <p>$> pip install --user netifaces</p> <p>Code returns the following:</p> <p>$> ./test3.py </p> <p>{'default': {2: ('192.168.0.1', 'en0')}, 2: [('192.168.0.1', 'en0', True)]}</p> <p>I hope this helps.</p> <p>Best regards,</p> <p>Aaron C.</p>
0
2016-10-17T23:05:22Z
[ "python", "dhcp" ]
How to Make uWSGI die when it encounters an error?
40,096,695
<p>I have my Python app running through uWSGI. Rarely, the app will encounter an error which makes it not be able to load. At that point, if I send requests to uWSGI, I get the error <code>no python application found, check your startup logs for errors</code>. What I would like to happen in this situation is for uWSGI to just die so that the program managing it (Supervisor, in my case) can restart it. Is there a setting or something I can use to force this?</p> <p>More info about my setup: Python 2.7 app being run through uWSGI in a docker container. The docker container is managed by Supervisor, and if it dies, Supervisor will restart it, which is what I want to happen.</p>
0
2016-10-17T22:31:12Z
40,096,953
<p>After an hour of searching, I finally found a way to do this. Just pass the <code>--need-app</code> argument when starting uWSGI, or add <code>need-app = true</code> in your .ini file, if you run things that way. No idea why this is off by default (in what situation would you ever want uWSGI to keep running when your app has died?) but so it goes.</p>
1
2016-10-17T22:59:26Z
[ "python", "uwsgi", "supervisord" ]
Modulus problems
40,096,784
<p>**I'm having problems using modulus for a simple evens and odds game. **Whether for even or odd no matter what, the return is "Odd you win" or "Even you win" even when the player + cpu = 3 % 2 = 1 in function (even) I get a return of "Even you win."</p> <pre><code>import random even_odds = list(range(0,2)) play = random.choice(even_odds) def selection(): which = input('Select O for odds and E for even: ').lower() if which == 'o': odds() elif which == 'e': evens() def odds(): even_odds cpu = random.choice(even_odds) print("YOU CHOSE ODD") player = int(input("Choose a number between 0 and 2: ")) print('cpu chose',cpu) print("You're choice plus the cpu's choice equals",player + cpu) print(" /n ...", player + cpu % 2 ) if player + cpu % 2 != 0: print('Odd you win\n') selection() else: print('Even you lose!\n') selection() def evens(): even_odds cpu = random.choice(even_odds) print("YOU CHOSE EVEN") player = int(input("Choose number between 0 and 2: ")) print('cpu chose',cpu) print("You're choice plus the cpu's choice equals",player + cpu) if player + cpu % 2 == 0: print('Even you win! \n') selection() else: print('Odd you lose! \n') selection() </code></pre> <p>Output</p> <pre><code>**Select O for odds and E for even: o YOU CHOSE ODD Choose a number between 0 and 2: 2 cpu chose 0 You're choice plus the cpu's choice equals 2 ... 2 Odd you win** </code></pre>
0
2016-10-17T22:41:33Z
40,096,808
<p>You need to use parens:</p> <pre><code>if (player + cpu) % 2 != 0: </code></pre> <p>You can see the difference with a simple example:</p> <pre><code>In [10]: 5 + 5 % 2 Out[10]: 6 In [11]: (5 + 5) % 2 Out[11]: 0 </code></pre> <p><code>%</code> has a higher <a href="https://docs.python.org/2/reference/expressions.html#operator-precedence" rel="nofollow">precedence</a> than <code>+</code> so the modulo is performed first, then 5 is added to the result.</p> <pre><code>In [12]: 5 % 2 Out[12]: 1 In [13]: 5 % 2 + 5 Out[13]: 6 </code></pre>
2
2016-10-17T22:44:00Z
[ "python", "math", "modulus" ]
Modulus problems
40,096,784
<p>**I'm having problems using modulus for a simple evens and odds game. **Whether for even or odd no matter what, the return is "Odd you win" or "Even you win" even when the player + cpu = 3 % 2 = 1 in function (even) I get a return of "Even you win."</p> <pre><code>import random even_odds = list(range(0,2)) play = random.choice(even_odds) def selection(): which = input('Select O for odds and E for even: ').lower() if which == 'o': odds() elif which == 'e': evens() def odds(): even_odds cpu = random.choice(even_odds) print("YOU CHOSE ODD") player = int(input("Choose a number between 0 and 2: ")) print('cpu chose',cpu) print("You're choice plus the cpu's choice equals",player + cpu) print(" /n ...", player + cpu % 2 ) if player + cpu % 2 != 0: print('Odd you win\n') selection() else: print('Even you lose!\n') selection() def evens(): even_odds cpu = random.choice(even_odds) print("YOU CHOSE EVEN") player = int(input("Choose number between 0 and 2: ")) print('cpu chose',cpu) print("You're choice plus the cpu's choice equals",player + cpu) if player + cpu % 2 == 0: print('Even you win! \n') selection() else: print('Odd you lose! \n') selection() </code></pre> <p>Output</p> <pre><code>**Select O for odds and E for even: o YOU CHOSE ODD Choose a number between 0 and 2: 2 cpu chose 0 You're choice plus the cpu's choice equals 2 ... 2 Odd you win** </code></pre>
0
2016-10-17T22:41:33Z
40,096,821
<p>The <strong>modulo</strong> applies only for the <code>cpu</code> variable. </p> <p>Use <code>(player + cpu) % 2</code> to apply it for the sum.</p> <pre><code>&gt;&gt;&gt; player = 2 &gt;&gt;&gt; cpu = 1 &gt;&gt;&gt; player + cpu % 2 3 &gt;&gt;&gt; (player + cpu) % 2 1 </code></pre> <hr> <p><code>%</code> evaluates with <code>*</code> and <code>/</code>, so it precedes <code>+</code> in <a href="https://docs.python.org/3.5/reference/expressions.html#operator-precedence" rel="nofollow">operations</a> (calculates before).</p>
1
2016-10-17T22:44:44Z
[ "python", "math", "modulus" ]
Ranking python dictionary by percentile
40,096,826
<p>If i have a dictionary that records the count frequency of random objects:</p> <pre><code>dict = {'oranges': 4 , 'apple': 3 , 'banana': 3 , 'pear' :1, 'strawberry' : 1....} </code></pre> <p>And I want only the keys that are in the top 25th percentile by frequency, how would i do that ? Especially if it's a very long tail list and a lot of records will have the same count. </p>
2
2016-10-17T22:45:24Z
40,096,939
<p>Use a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> object and exploit its <a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common</code></a> method to return the keys with the highest frequency up to the required percentile.</p> <p>For the 25th percentile, divide the length of the dictionary by 4 and pass that value to <code>most_common</code>:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; dct = {'oranges': 4 , 'apple': 3 , 'banana': 3 , 'pear' :1, 'strawberry' : 1} &gt;&gt;&gt; c = Counter(dct) &gt;&gt;&gt; [tup[0] for tup in c.most_common(len(dct)//4)] ['oranges'] </code></pre> <p>Note that potential elements in that percentile with equal frequencies will be selected <em>arbitrarily</em>.</p>
2
2016-10-17T22:58:00Z
[ "python", "numpy", "dictionary" ]
Put list into dict with first row header as keys
40,096,846
<p>I have the following python list:</p> <pre><code>[['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>How can I put it into a dict and use the first sub list as the keys?:</p> <pre><code>{'A': '1', 'B': '2', 'C': '3', 'D': '4'} {'A': '5', 'B': '6', 'C': '7', 'D': '8'} </code></pre> <p>Thanks in advance!</p>
2
2016-10-17T22:47:21Z
40,096,878
<p>You can <code>zip</code> the first element of the list with the remaining elements of the list after splitting the string in each sublist:</p> <pre><code># to split string in the sublists lst = [i[0].split(',') for i in lst] [dict(zip(lst[0], v)) for v in lst[1:]] #[{'A': '1', 'B': '2', 'C': '3', 'D': '4'}, # {'A': '5', 'B': '6', 'C': '7', 'D': '8'}] </code></pre>
1
2016-10-17T22:51:11Z
[ "python" ]
Put list into dict with first row header as keys
40,096,846
<p>I have the following python list:</p> <pre><code>[['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>How can I put it into a dict and use the first sub list as the keys?:</p> <pre><code>{'A': '1', 'B': '2', 'C': '3', 'D': '4'} {'A': '5', 'B': '6', 'C': '7', 'D': '8'} </code></pre> <p>Thanks in advance!</p>
2
2016-10-17T22:47:21Z
40,096,881
<p>Just use a <a href="https://docs.python.org/2/library/csv.html#csv.DictReader" rel="nofollow">DictReader</a> instance. People usually use these with a file object, but actually it doesn't really care what you pass it as long as it can iterate the thing.</p> <pre><code>&gt;&gt;&gt; L = [['A,B,C,D'], ... ['1,2,3,4'], ... ['5,6,7,8']] &gt;&gt;&gt; import csv &gt;&gt;&gt; reader = csv.DictReader((line for [line] in L)) &gt;&gt;&gt; d1, d2 = reader &gt;&gt;&gt; d1 {'A': '1', 'B': '2', 'C': '3', 'D': '4'} &gt;&gt;&gt; d2 {'A': '5', 'B': '6', 'C': '7', 'D': '8'} </code></pre>
1
2016-10-17T22:51:30Z
[ "python" ]
Put list into dict with first row header as keys
40,096,846
<p>I have the following python list:</p> <pre><code>[['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>How can I put it into a dict and use the first sub list as the keys?:</p> <pre><code>{'A': '1', 'B': '2', 'C': '3', 'D': '4'} {'A': '5', 'B': '6', 'C': '7', 'D': '8'} </code></pre> <p>Thanks in advance!</p>
2
2016-10-17T22:47:21Z
40,096,906
<p>Let's start with your data as presented in the question:</p> <pre><code>&gt;&gt;&gt; a = [['A,B,C,D'], ['1,2,3,4'], ['5,6,7,8']] </code></pre> <p>Now, let's convert that to the desired list of dictionaries:</p> <pre><code>&gt;&gt;&gt; [dict(zip(a[0][0].split(','), c[0].split(','))) for c in a[1:]] [{'A': '1', 'C': '3', 'B': '2', 'D': '4'}, {'A': '5', 'C': '7', 'B': '6', 'D': '8'} </code></pre>
1
2016-10-17T22:54:28Z
[ "python" ]
I am using Kivy in Python and only the last button has it's embedded objects appearing
40,096,850
<p>I apologize in advance if my question is stupid or obvious, but I have been researching this over and over and am coming up with nothing. I am currently using Kivy and have multiple buttons in a gridlayout, which is in a scrollview. Withing these buttons I have a label and an image. Only the last of my buttons shows the label and image whenever I run my code. I think it has something to do with the positions, but I can't figure out what it is. Here is my code:</p> <pre><code> Window.clearcolor = (0.937, 0.698, 0.176, 1) class Solis(App): def build(self): b1 = Button(text= "", background_color=(237, 157, 59, 1), size_hint_y= None, background_normal = '', valign = 'middle', font_size=20) lab1 = Label(text= Content1, color= (0.937, 0.698, 0.176, 1), valign= 'middle', pos=(b1.x , b1.height / 2)) b1I = AsyncImage(source = lead1image) def callback1(self): webbrowser.open(lead1) b1.bind(on_press=callback1) b2 = Button(text= "", background_color=(237, 157, 59, 1), size_hint_y= None, background_normal = '', valign = 'middle', font_size=20) lab2 = Label(text= Content2, color= (0.937, 0.698, 0.176, 1), valign= 'middle', halign= 'center', pos=(b2.x + 800, b2.height)) b2I = AsyncImage(source = lead2image) def callback2(self): webbrowser.open(lead2) b2.bind(on_press=callback2) b3 = Button(text= "", background_color=(237, 157, 59, 1), size_hint_y= None, background_normal = '', valign = 'middle', font_size=20) lab3 = Label(text= Content3, color= (0.937, 0.698, 0.176, 1), valign= 'middle', pos=(b3.x + 800, b3.height / 4)) b3I = AsyncImage(source = lead3image) def callback3(self): webbrowser.open(lead3) b3.bind(on_press=callback3) l = GridLayout(cols=1, spacing=10, size_hint_y=None, orientation = 'vertical') l.bind(minimum_height=l.setter('height')) s = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) s.add_widget(l) l.add_widget(b1) l.add_widget(b2) l.add_widget(b3) b1.add_widget(b1I) b1.add_widget(lab1) b2.add_widget(b2I) b2.add_widget(lab2) b3.add_widget(b3I) b3.add_widget(lab3) return s if __name__ == "__main__": Solis().run() </code></pre> <p>And here is my result <a href="https://i.stack.imgur.com/CMkTi.png" rel="nofollow">here</a></p>
0
2016-10-17T22:47:46Z
40,107,645
<p>Here is something that should help you get what you want:</p> <p>A main.py like this:</p> <pre><code>from kivy.app import App import webbrowser class Solis(App): def __init__(self, **kwargs): super(Solis, self).__init__(**kwargs) self.lead1image='https://pbs.twimg.com/profile_images/562300519008333825/6WcGRXLU.png' self.lead2image='https://pbs.twimg.com/profile_images/439154912719413248/pUBY5pVj.png' self.lead3image='https://pbs.twimg.com/profile_images/424495004/GuidoAvatar.jpg' def callback(self,url): webbrowser.open(url) if __name__ == '__main__': Solis().run() </code></pre> <p>And a solis.kv like this:</p> <pre><code>ScrollView: GridLayout: cols:1 size_hint_y:None height: self.minimum_height Button: size_hint_y: None height:'50dp' on_press: app.callback(app.lead1image) AsyncImage: id:im1 size_hint: None, None height: self.parent.height width: '48dp' source: app.lead1image pos: (self.parent.x, self.parent.y) Label: size_hint: None, None height:self.parent.height width: self.parent.width - im1.width text: 'Text for the 1st Label' pos: (self.parent.x, self.parent.y) Button: size_hint_y: None height:'50dp' on_press: app.callback(app.lead2image) AsyncImage: size_hint: None, None height: self.parent.height width: '48dp' source: app.lead2image pos: (self.parent.x, self.parent.y) Label: size_hint: None, None height:self.parent.height width: self.parent.width - im1.width text: 'Text for the 2st Label' pos: (self.parent.x, self.parent.y) Button: size_hint_y: None height:'50dp' on_press: app.callback(app.lead3image) AsyncImage: size_hint: None, None height: self.parent.height width: '48dp' source: app.lead3image pos: (self.parent.x, self.parent.y) Label: size_hint: None, None height:self.parent.height width: self.parent.width - im1.width text: 'Text for the 2st Label' pos: (self.parent.x, self.parent.y) </code></pre> <p>Thus, there is now two files (a ".py" and a ".kv"): This will help you separate the logic of your application from its User Interface. Note that it is possible to reduce the length of the code with some customized widgets. Also, if you want to keep juste one .py file, I would add a "for" loop. Finally, regarding your issue: I guess your labels and images were superimposed. I avoided this by using "pos:".</p>
0
2016-10-18T11:58:00Z
[ "python", "kivy" ]
Getting current build number in jenkins using python
40,097,012
<p>I have a python script from which I am trying to get the current build number of a job in jenkins. Below script gives the last build number and whether the build is success or failure. How can I get the current build number? I mean when I run this script, It will build with new build number and how can I get that current build number?</p> <p>script.py</p> <pre><code>import jenkins import urllib2 import urllib import sys j = jenkins.Jenkins('http://localhost:8080') if not j.job_exists('sample1234'): j.create_job('sample1234', jenkins.EMPTY_CONFIG_XML) j.reconfig_job('sample1234', jenkins.RECONFIG_XML) j.build_job('sample1234') last_build_number = j.get_job_info('sample123')['lastCompletedBuild'] ['number'] print last_build_number build_info=j.get_build_info('sample123',last_build_number) if build_info['result']=='SUCCESS': print "Build Success " else: print " Build Failed " </code></pre>
0
2016-10-17T23:06:19Z
40,098,295
<p>I think the answer you're looking for is within the python-jenkins <a href="http://python-jenkins.readthedocs.io/en/latest/examples.html" rel="nofollow">documentation</a> specifically at Example 9</p> <p>The code snippet below is from their documentation:</p> <pre><code>next_bn = server.get_job_info('job_name')['nextBuildNumber'] server.set_next_build_number('job_name', next_bn + 50) </code></pre> <p>I think you really only need the first line for the current/next build number. The caveat is that you need this <a href="https://wiki.jenkins-ci.org/display/JENKINS/Next+Build+Number+Plugin" rel="nofollow">plugin</a> for your jenkins.</p>
0
2016-10-18T01:51:56Z
[ "python", "jenkins", "jobs", "jenkins-api" ]
What is the most efficient way to compare every value of 2 numpy matrices?
40,097,024
<p>I'd like to more efficiently take every value of 2 matrices(<code>a</code> and <code>b</code>) of the same size and return a third boolean(or 1/ 0 matrix to make things clean) into matrix<code>c</code> containing the results of the conditions.</p> <p>Example:</p> <p>Condition: <code>For a == 0 and b == 3</code></p> <pre><code>a = [[1 0] [0 1]] b = [[3 5] [3 9]] </code></pre> <p>Would return:</p> <pre><code>c = [[0 0] [1 0]] </code></pre> <p><code>[0,1]</code> is the only place where <code>a == 0</code> and <code>b == 3</code> so it is the only place <code>True</code> in c </p> <p>This is the code I have so far:</p> <pre><code>import numpy as np a = np.matrix("1, 0; 0 1") print(a,'\n') b = np.matrix("3, 5; 3 9") print(b,'\n') c = [] for x in range(0,np.shape(a)[1]): row = [] for y in range(0,np.shape(a)[1]): row.append(int(a[x,y] == 0 and b[x,y] == 3)) # the int() is there just to keep things tighty for the 3 prints c.append(row) c = np.matrix(c) print(c) </code></pre> <p>results:</p> <pre><code>[[1 0] [0 1]] [[3 5] [3 9]] [[0 0] [1 0]] </code></pre> <p>I could also use:</p> <pre><code>a=a==0 b=b==3 c=a&amp;b </code></pre> <p>But that would require making a copy of a and b and with big matrices would that still be efficient ?</p> <p>Why can't I just use <code>a == 0 &amp; b == 3</code> ?</p> <p>I need to do a comparison like this for several matrices that are 1000+ size so you could see where iterating thought them would be quite slow.</p> <p>Thank you very much for any help I'm sure the answer is something simple and right in front of me but I'm just dumb.</p>
-1
2016-10-17T23:07:04Z
40,097,139
<p>You <em>can</em> use (pretty) much the expression that you wanted:</p> <pre><code>&gt;&gt;&gt; (a == 0) &amp; (b == 3) matrix([[False, False], [ True, False]], dtype=bool) </code></pre> <p>Beware, you <em>need</em> the parenthesis to make the precendence work out as you'd like -- Normally <code>&amp;</code> will bind tighter than <code>==</code>. If you don't like the extra parenthesis, you can use the more verbose (though arguably more semantically correct) <code>np.logical_and</code> function.</p> <p>Also note that while no <em>copies</em> are being made, there are <em>temporary</em> arrays being created. Specifically, the result of <code>a == 0</code> and <code>b == 3</code> are both going to be allocated and freed in this statement. Generally, that's not such a big deal and numpy's vectorized operations remain fast. However, if that <em>isn't</em> fast enough for you, you <em>can</em> use a library like <a href="https://github.com/pydata/numexpr" rel="nofollow"><code>numexpr</code></a> to remove the temporary arrays:</p> <pre><code>&gt;&gt;&gt; numexpr.evaluate('(a == 0) &amp; (b == 3)') array([[False, False], [ True, False]], dtype=bool) </code></pre> <p>And of course, if you need <code>1</code> and <code>0</code>, you can use <code>result.astype(int)</code> on the output array to make arrays of ints rather than booleans.</p>
0
2016-10-17T23:19:35Z
[ "python", "python-3.x", "oop", "numpy", "matrix" ]
Plotting asymmetric error bars Matplotlib
40,097,086
<p>So I have three sets of data:</p> <pre><code>min_data = np.array([ 0.317, 0.312, 0.305, 0.296, 0.281, 0.264, 0.255, 0.237, 0.222, 0.203, 0.186, 0.17, 0.155, 0.113, 0.08]) avg_data = np.array([ 0.3325, 0.3235, 0.3135, 0.30216667, 0.2905, 0.27433333, 0.26116667, 0.24416667, 0.22833333, 0.20966667, 0.19366667, 0.177, 0.16316667, 0.14016667, 0.097]) max_data = np.array([ 0.346, 0.331, 0.32, 0.31, 0.299, 0.282, 0.266, 0.25, 0.234, 0.218, 0.204, 0.187, 0.175, 0.162, 0.115]) </code></pre> <p>I need to plot this data with error bars. </p> <p>I have attempted:</p> <pre><code>x = np.linspace(0, 100, 15) err = [min_data, max_data] plt.errorbar(x, avg_data, 'bo', yerr=err) TypeError: errorbar() got multiple values for argument 'yerr' </code></pre> <p>The final graph should look like this:</p> <pre><code>plt.plot(x[::-1], avg_data, 'ro') plt.plot(x[::-1], min_data, 'bo') plt.plot(x[::-1], max_data, 'bo') </code></pre> <p><a href="https://i.stack.imgur.com/JTZAK.png" rel="nofollow"><img src="https://i.stack.imgur.com/JTZAK.png" alt="enter image description here"></a></p> <p>Where the blue points represent where the error bars should be located.</p> <p>All the documentation I have been able to find only allows asymmetric errors that is equal in + and - y directions.</p> <p>Thank you</p>
2
2016-10-17T23:13:21Z
40,097,584
<p>Your code is failing because it thinks that <code>'bo'</code> is the <code>yerr</code> argument since the third argument in <code>plt.errorbar</code> is <code>yerr</code>. If you want to pass the format specifier, then you should use the <code>fmt</code> keyword. </p> <pre><code>plt.errorbar(x, avg_data, fmt='bo', yerr=err) </code></pre>
2
2016-10-18T00:14:34Z
[ "python", "numpy", "matplotlib" ]
BS4 get XML tag variables
40,097,088
<p>I am playing around with web scraping using bs4 and trying to get the title and color tag from this line of xml <code>&lt;graph gid="1" color="#000000" balloon_color="#000000" title="Approve"&gt;</code></p> <p>The output result would be a dict something along the lines of <code>{'title':'approve', 'color':'#000000'}</code></p> <p>The page where the xml is <a href="http://charts.realclearpolitics.com/charts/1044.xml" rel="nofollow">here</a></p> <p>I've already written this function which is by no means efficient, but would like the titles of my dataframe to be the result of the <code>title</code> rather than a manually inputted value. So rather than <code>GID1</code> it would read <code>Approve</code> or <code>Obama</code> or whatever the result of title is. </p> <pre><code>def rcp_poll_data(xml): soup=bs(xml,"xml") dates = soup.find('series') datesval = dates.findChildren(string=True) del datesval[-7:] obama = soup.find('graph', { "gid" : "1" }) obamaval = obama.findChildren(string=True) romney = soup.find('graph', { "gid" : "2" }) romneyval = romney.findChildren(string=True) result = pd.DataFrame({'date':pd.to_datetime(datesval), 'GID1':obamaval, 'GID2':romneyval}) return result </code></pre> <p>I'm using bs4 and struggling to find the right terminology that would get me there. Are these tags i'm trying to isolate, or elements, or attributes?</p> <p>This isn't a professional thing i'm just nurdling around for fun. So any help to get me slightly closer would be great. (i'm using python 3)</p>
2
2016-10-17T23:13:40Z
40,097,165
<p>You just need to pull the <em>attributes</em> once you find the <em>graph node</em>:</p> <pre><code>import requests from bs4 import BeautifulSoup soup = BeautifulSoup(requests.get("http://charts.realclearpolitics.com/charts/1044.xml").content,"xml") g = soup.find("graph", gid="1") data = {"title":g["title"], "color": g["color"]} </code></pre> <p>Which will give you:</p> <pre><code>{'color': '#000000', 'title': 'Approve'} </code></pre>
2
2016-10-17T23:22:49Z
[ "python", "xml", "python-3.x", "beautifulsoup" ]
Return code of a bash script being called from a Subprocess
40,097,144
<p>I am writing a script that imports a bunch of data to a couchdb database, the issue is each db takes around 15 minutes, so I do not watch the whole thing as I have on average 20 db to import.</p> <p>The script loops through an array of items, and then calls subprocess on each in order run the import before moving on to the next.</p> <p>What I have tried to do is catch any db's that do not load correctly, by way of failed script. I am trying to catch this when the return code is not 0, the issue is I can only get the return code of the subprocess calling the docker command, not if the script executes correctly. </p> <pre><code>#!/usr/bin/python import sys import subprocess cities = ["x","y", "z"]; uncompletedcities = [] for x in cities: dockerscript = "docker exec -it docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch %s %s" % (x,x) p = subprocess.Popen(dockerscript, shell=True, stderr=subprocess.PIPE) error = p.communicate() if p.returncode != 0: uncompletedcities.append(x) while p.poll() == None: print p.stderr.read() print (uncompletedcities) </code></pre> <p>so the issue is, I recieve the return code of </p> <pre><code>p = subprocess.Popen(dockerscript, shell=True, stderr=subprocess.PIPE) </code></pre> <p>not the return code of the script being called here</p> <pre><code>dockerscript = "docker exec -it docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch %s %s" % (x,x) </code></pre> <p>so in essence, I want to go one deeper into the return code, and get the return code of the docker command that subprocess is calling, no the return code of subprocess. </p> <p>So just to get the return code of this:</p> <pre><code>docker exec -it docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch </code></pre>
3
2016-10-17T23:20:09Z
40,097,515
<p>Note that when you run:</p> <pre><code>docker exec -it </code></pre> <p>your <code>-it</code> flags are doing something contrary to the point of what you are trying. You are trying to open an interactive session. This isn't actually <em>executing</em> the command.</p> <p>You can remove both of these from your command and just run <code>docker exec</code>:</p> <pre><code>dockerscript = "docker exec docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch %s %s" % (x,x) </code></pre> <p>For what it's worth I would probably look into using <a href="https://github.com/docker/docker-py" rel="nofollow">docker-py</a>, too. It's a lot more flexible for running docker commands if you end up with more than just a few command line docker commands. It also lets you avoid <code>shell=true</code>.</p>
0
2016-10-18T00:06:09Z
[ "python", "bash", "docker" ]
Python loop through Dataframe 'Series' object has no attribute
40,097,194
<p>Using pandas version 0.19.0, I have a dataframe with compiled regular expressions inside. I want to loop over the dataframe and see if any of the regular expressions match a value. I can do it with two for loops, but I can't figure out how to do it so that it'll return a same sized dataframe.</p> <pre><code>import pandas as pd import re inp = [{'c1':re.compile('a'), 'c2':re.compile('b')}, {'c1':re.compile('c'),'c2':re.compile('d')}, {'c1':re.compile('e'),'c2':re.compile('f')}] df = pd.DataFrame(inp) for i,v in df.items(): for a in v: if (a.match('a')): print("matched") else: print("failed") </code></pre> <p>This fails:</p> <pre><code>[a.match('a') for a in [v for i,v in df.items()]] </code></pre> <blockquote> <p>AttributeError: 'Series' object has no attribute 'match'</p> </blockquote> <p>What I want:</p> <pre><code>[a.match('a') for a in [v for i,v in df.items()]] c1 c2 0 &lt;_sre.SRE_Match object; span=(0, 1), match='a'&gt; None 1 None None 2 None None </code></pre>
2
2016-10-17T23:25:41Z
40,097,973
<p>It looks like you need to use the <code>applymap</code> method. See the docs <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html?highlight=applymap" rel="nofollow">here</a> for more info. </p> <pre><code>df.applymap(lambda x: x.match('a')) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/J5twk.png" rel="nofollow"><img src="https://i.stack.imgur.com/J5twk.png" alt="enter image description here"></a></p>
0
2016-10-18T01:12:51Z
[ "python", "pandas", "dataframe" ]
How do I median bin a 2D image in python?
40,097,213
<p>I have a 2D numarray, of size WIDTHxHEIGHT. I would like to bin the array by finding the median of each bin so that the resultant array is WIDTH/binsize x HEIGHT/binsize. Assume that both WIDTH and HEIGHT are divisible by binsize. </p> <p>I have found solutions where the binned array values are the sum or average of the individual elements in each bin: <a href="http://stackoverflow.com/questions/36063658/how-to-bin-a-2d-array-in-numpy">How to bin a 2D array in numpy?</a></p> <p>However, if I want to do a median combine of elements in each bin, I haven't been able to figure out a solution. Your help would be much appreciated!</p>
0
2016-10-17T23:27:38Z
40,109,865
<p>Is this what you are looking for? </p> <pre><code>import numpy as np a = np.arange(24).reshape(4,6) def median_binner(a,bin_x,bin_y): m,n = np.shape(a) return np.array([np.median(col) for row in a.reshape(bin_x,bin_y,m//bin_x,n//bin_y) for col in row]).reshape(bin_x,bin_y) print "Original Matrix:" print a print "\n" bin_tester1 = median_binner(a,2,3) print "2x3 median bin :" print bin_tester1 print "\n" bin_tester2 = median_binner(a,2,2) print "2x2 median bin :" print bin_tester2 </code></pre> <p>result: </p> <pre><code>Original Matrix: [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23]] 2x3 median bin : [[ 1.5 5.5 9.5] [ 13.5 17.5 21.5]] 2x2 median bin : [[ 2.5 8.5] [ 14.5 20.5]] </code></pre>
0
2016-10-18T13:38:46Z
[ "python", "arrays", "numpy" ]
How do I add list in xlsxwriter?
40,097,255
<p>I'm having hard time outputting my format in spreadsheet using xlsxwriter. I have four keys.</p> <pre><code>worksheet.write('A1', 'Provider Name', bold) worksheet.write('A2', 'Description', bold) worksheet.write('A3', 'Number of Store', bold) worksheet.write('A4', 'City', bold) </code></pre> <p>I want to be able to write multiple provider names that's in my for loop to next column. Something like this.</p> <p>I'm scraping these values; and here is how I'm doing it.</p> <pre><code>for td in mainWrapper: provider_name = td.findAll('td')[0].find('h4').text.strip() description = td.findAll('td')[0].find('p', attrs={'class':'desc'}).text.strip() number_of_store = td.findAll('td')[2].text city = td.findAll('td')[-1].text </code></pre> <p>How do I set each of these items to my xlsxwriter. I want my output to look something like this. So I want to be able to add multiple provider names, description, number_of_store and city in each new column.</p> <p><a href="https://i.stack.imgur.com/Hu7Oh.png" rel="nofollow"><img src="https://i.stack.imgur.com/Hu7Oh.png" alt="Example output format"></a></p>
1
2016-10-17T23:32:35Z
40,103,882
<p>You can use <a href="https://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-row" rel="nofollow"><code>write_row()</code></a> (or <a href="https://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-column" rel="nofollow"><code>write_column()</code></a>) to write lists in one go: </p> <pre><code># Some sample data. data = ('Foo', 'Bar', 'Baz') # Write the data to a sequence of cells. worksheet.write_row('A1', data) # The above example is equivalent to: worksheet.write('A1', data[0]) worksheet.write('B1', data[1]) worksheet.write('C1', data[2]) </code></pre>
0
2016-10-18T09:01:10Z
[ "python", "xlsxwriter" ]
Python 3.5 dictionary comparison
40,097,366
<p>I am trying to compare all elements of one dictionary to make sure they are in a second with the correct number. I am new at Python so I know there is something simple I am probably missing and I have been working on this one problem for hours so my code is likely very ugly and wrong. Here is an example of what I have so far.</p> <pre><code>try: for key in dict_one: if dict_two.get(key, 0) == dict_one[key]: del dict_one[key] if dict_one[key] &lt; 0 : return False else: return True except KeyError: pass </code></pre> <p>I have tried <code>all(dict_two.get(key,0))</code> as well and it didn't work. The final output should check that you can spell a word from <code>dict_two</code> using the words in <code>dict_one</code> <code>True</code> if you can, <code>False</code> if you can't so if <code>dict_two</code> word requires three Es then <code>dict_one</code> should have 3 Es or return false. Or two Ns if you were spelling bunny ex <code>dict_one = {b: 1, u: 1, n:1, y:1, x: 3}</code> and <code>dict_two ={b: 1, u: 1. n: 2, y:1}</code> <code>False</code> because you need 2 Ns in the word and <code>dict_one</code> only has one. </p> <p>I can get <code>dict_two</code> to populate correctly when I enter a word and <code>dict_one</code> properly pulls random numbers and amounts of those numbers. And I can get them to compare properly for letters included in each, I just can't get it to produce right answer of <code>True</code> or <code>False</code> for the number of letters needed. I feel I am close to an answer, but then just make it worse when I try new things and dig my hole deeper. </p> <p>Thank you! </p>
2
2016-10-17T23:47:22Z
40,097,707
<p>So you want to check to see that every letter in <code>dict2</code> has at mapping in <code>dict1</code> least as large as that letters mapping in <code>dict2</code>? That's accomplished fairly easily.</p> <pre><code>def can_spell(dict1, dict2): try: return all(dict1[k] &gt;= v for k, v in dict2.items()) except KeyError: return False </code></pre> <p>This gets every (key, value) pair in <code>dict2</code> and then compares <code>v</code> with the mapping of that key in <code>dict1</code>. <code>all</code> returns <code>True</code> iff every expression in that generator comprehension is true.</p>
2
2016-10-18T00:31:09Z
[ "python", "python-3.x", "dictionary" ]
Python sorting a nested list with conditional comparison
40,097,372
<p>I am trying to sort a nested list <code>A</code>. <code>len(A) = n</code> and <code>len(A[i]) = d</code> for all <code>i</code>. I would like to sort using the first element of <code>A[i]</code>. But if <code>A[i][0] == A[j][0]</code> then I want to sort using the next element, i.e., <code>A[i][1]</code>. If <code>A[i][1] == A[j][1]</code> then use the next element, <code>A[i][2]</code>, and so on. </p> <p>Here is an example with <code>n = 4</code> and <code>d = 2</code>. Because <code>[3,6]</code> and <code>[3,7]</code> have the same first element, they are compared based on the second element.</p> <pre><code>A = [[3,7], [4,5], [3, 6], [5,1]] A_sorted = [[3,6], [3,7], [4,5], [5,1]] </code></pre> <p>In Python 2.7 I used custom comparison function. <code>A.sort(cmp=comp_func)</code>. But I am trying to do this in Python 3 which does not have the <code>cmp</code> argument option. So I need to use <code>key</code> argument instead. How do I implement this custom sorting in Python 3?</p>
-1
2016-10-17T23:47:53Z
40,097,651
<p>This is the default Python sorting behavior. Have you tried doing this and it hasn't worked?</p>
1
2016-10-18T00:24:04Z
[ "python", "python-3.x", "sorting", "key" ]
How to use Multiprocessing in Python within a class
40,097,485
<p>What I'd like to do is use multiprocessing on one of my class methods. I have tried to follow the example in the Python help file but am not getting the result expected. Here is my class file:</p> <pre><code>import os import telnetlib class PowerSupply(): # ---------------------------------- # def __init__(self,port_no,my_name): self.Status = "Off" self.Port = port_no self.Name = my_name self.tn = None self.HOST = "192" self.P = Process(target=self.print_time, args=('tname','delay') self.P.start() self.P.join() # ---------------------------------- # def TurnOn(self): onCommand = "OUT 1\r" if self.Status == "ON": print "I'm already on" else: self.tn = telnetlib.Telnet(self.HOST,self.Port) self.tn.write(onCommand) self.Status = "ON" print "I am now on" # ---------------------------------- # def TurnOff(self): offCommand = "OUT 0\r" self.tn.write(offCommand) self.tn.close() print "I am now off" # ---------------------------------- # def SetVoltage(self,volts): voltageCommand = "PV" + " " + str(volts) + "\r" self.tn.write(voltageCommand) # ---------------------------------- # def GetAllData(self): while(self.Status == "ON"): self.tn.write("DVC?\r") all_data = self.tn.read_some() vdc = all_data.split(',') vdc = vdc[0] print vdc # ---------------------------------- # def print_time(self, tname, delay): count = 0 while count &lt; 5: time.sleep(delay) count += 1 print "%s: %s"%(tname, time.ctime(time.time())) </code></pre> <p>Here is how I try to use the implementation:</p> <pre><code>ps1 = PowerSuppy(8000,'L1') ps1.print_time('thread1',2) ps1.print_time('thread2',3) </code></pre> <p>When I try to use it as above, it still uses a procedural approach and doesn't call the thread2 until thread1 is complete. What is it exactly that I am doing wrong and how can I fix it?</p>
0
2016-10-18T00:02:36Z
40,098,160
<p>Ok, here's what I suppose the program will do:</p> <ol> <li>At <code>PowerSuppy(8000,'L1')</code>, it starts a subprocess and calls <code>self.print_time('tname','delay')</code>. Since <code>'delay'</code> is not a number it immediately raises a <code>TypeError</code> in the subprocess and end (so <code>self.P.join()</code> didn't block at all).</li> <li>At <code>ps1.print_time('thread1',2)</code>, it runs the method in main process and is blocked until it end.</li> <li><code>ps1.print_time('thread2',3)</code> does the same thing as the previous line did in main process.</li> </ol> <p>How to fix it:</p> <ol> <li>Do not initialize the subprocess in <code>__init__</code> method, instead, initialize it in <code>print_time</code> method.</li> <li>Implemented a internal method for <code>target</code> function for subprocess.</li> <li>Do not run <code>Process.join</code> unless you want to run the subprocess in sequence.</li> </ol> <p>Here's the code:</p> <pre><code>import os import telnetlib class PowerSupply(): # ---------------------------------- # def __init__(self,port_no,my_name): self.Status = "Off" self.Port = port_no self.Name = my_name self.tn = None self.HOST = "192" # ---------------------------------- # def TurnOn(self): onCommand = "OUT 1\r" if self.Status == "ON": print "I'm already on" else: self.tn = telnetlib.Telnet(self.HOST,self.Port) self.tn.write(onCommand) self.Status = "ON" print "I am now on" # ---------------------------------- # def TurnOff(self): offCommand = "OUT 0\r" self.tn.write(offCommand) self.tn.close() print "I am now off" # ---------------------------------- # def SetVoltage(self,volts): voltageCommand = "PV" + " " + str(volts) + "\r" self.tn.write(voltageCommand) # ---------------------------------- # def GetAllData(self): while(self.Status == "ON"): self.tn.write("DVC?\r") all_data = self.tn.read_some() vdc = all_data.split(',') vdc = vdc[0] print vdc # ---------------------------------- # def print_time(self, tname, delay): P = Process(target=self._print_time, args=(tname, delay)) P.start() def _print_time(tname, delay): count = 0 while count &lt; 5: time.sleep(delay) count += 1 print "%s: %s"%(tname, time.ctime(time.time())) </code></pre>
1
2016-10-18T01:34:15Z
[ "python", "oop", "python-multiprocessing" ]
How to use Multiprocessing in Python within a class
40,097,485
<p>What I'd like to do is use multiprocessing on one of my class methods. I have tried to follow the example in the Python help file but am not getting the result expected. Here is my class file:</p> <pre><code>import os import telnetlib class PowerSupply(): # ---------------------------------- # def __init__(self,port_no,my_name): self.Status = "Off" self.Port = port_no self.Name = my_name self.tn = None self.HOST = "192" self.P = Process(target=self.print_time, args=('tname','delay') self.P.start() self.P.join() # ---------------------------------- # def TurnOn(self): onCommand = "OUT 1\r" if self.Status == "ON": print "I'm already on" else: self.tn = telnetlib.Telnet(self.HOST,self.Port) self.tn.write(onCommand) self.Status = "ON" print "I am now on" # ---------------------------------- # def TurnOff(self): offCommand = "OUT 0\r" self.tn.write(offCommand) self.tn.close() print "I am now off" # ---------------------------------- # def SetVoltage(self,volts): voltageCommand = "PV" + " " + str(volts) + "\r" self.tn.write(voltageCommand) # ---------------------------------- # def GetAllData(self): while(self.Status == "ON"): self.tn.write("DVC?\r") all_data = self.tn.read_some() vdc = all_data.split(',') vdc = vdc[0] print vdc # ---------------------------------- # def print_time(self, tname, delay): count = 0 while count &lt; 5: time.sleep(delay) count += 1 print "%s: %s"%(tname, time.ctime(time.time())) </code></pre> <p>Here is how I try to use the implementation:</p> <pre><code>ps1 = PowerSuppy(8000,'L1') ps1.print_time('thread1',2) ps1.print_time('thread2',3) </code></pre> <p>When I try to use it as above, it still uses a procedural approach and doesn't call the thread2 until thread1 is complete. What is it exactly that I am doing wrong and how can I fix it?</p>
0
2016-10-18T00:02:36Z
40,098,172
<p>Try to add a function in your class:</p> <pre><code>def print_time_subprocess(self, tname, delay): p = Process(target=self.print_time, args=('tname','delay')) p.start() </code></pre> <p>and use this to test:</p> <pre><code>ps1 = PowerSupply(8000,'L1') ps1.print_time_subprocess('thread1',2) ps1.print_time_subprocess('thread2',3) </code></pre> <p>and do not forget import <code>Process</code></p>
1
2016-10-18T01:35:49Z
[ "python", "oop", "python-multiprocessing" ]
Which API key do I use in SpeechRecognition (Google) in python
40,097,617
<p>I am working on a project that uses voice recognition in python and I was looking at some example code, I was wondering which API key to use and what does it look like.</p> <pre><code>def callback(recognizer, audio): # received audio data, now we'll recognize it using Google Speech Recognition try: # for testing purposes, we're just using the default API key # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` # instead of `r.recognize_google(audio)` print(recognizer.recognize_google(audio)) &lt;-- right there except sr.UnknownValueError: pass except sr.RequestError as e: pass </code></pre> <p>I have a google developer account. Please help. Thanks! </p>
0
2016-10-18T00:19:23Z
40,098,146
<p>Create an account here <a href="https://cloud.google.com/speech/" rel="nofollow">Google Cloud Speech API</a>. You will be able to get a limited amount of api requests with a free account. for a full documentation, visit <a href="https://cloud.google.com/speech/docs/rest-tutorial" rel="nofollow">https://cloud.google.com/speech/docs/rest-tutorial</a></p>
0
2016-10-18T01:31:45Z
[ "python", "api" ]
Pandas Grouping - Creating a Generic Aggregation Function
40,097,706
<p>I need to do a lot of aggregation on data and I was hoping to write a function that would allow me to pass</p> <p>1) The string to use for grouping 2) The fields that would constitute the numerator/denominator/ and formula</p> <p>As I will be doing a lot of cuts on the data using different groupings and different numerators and denominators, it would be easier for me to create a generic group by and pass it what I need</p> <p>So lets take the following example:</p> <pre><code>import pandas as pd df=pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/master/ch08/tips.csv", sep=',') (df.groupby(['sex', 'smoker'])[['total_bill','tip']].sum().apply(lambda r: r.tip/r.total_bill, axis = 1)) </code></pre> <p>Now, I would want to create a function that would allow me to pass a group by value and a numerator denominator field</p> <p>So, for example</p> <pre><code>groupbyvalue=['sex', 'smoker'] fieldstoaggregate=['tip','total_bill'] </code></pre> <p>And plug them into something like</p> <pre><code>(df.groupby(groupbyvalue)[fieldstoaggregate].sum().apply(lambda r: r.tip/r.total_bill, axis = 1)) </code></pre> <p>That works fine, but when I tried to replace the formula with something like: </p> <pre><code>dfformula="r.tip/r.total_bill" </code></pre> <p>And then placed it in the formula as follows </p> <pre><code>(df.groupby(groupbyvalue)[fieldstoaggregate].sum().apply(lambda r: dfformula, axis = 1)*10000) </code></pre> <p>My output looks as follows:</p> <pre><code>sex smoker Female No r.tip/r.total_billr.tip/r.total_billr.tip/r.to... Yes r.tip/r.total_billr.tip/r.total_billr.tip/r.to... Male No r.tip/r.total_billr.tip/r.total_billr.tip/r.to... Yes r.tip/r.total_billr.tip/r.total_billr.tip/r.to... dtype: object </code></pre> <p>Is there any way to create the calculation dynamically then use it in the formula rather than having it interpreted as a string?</p> <p>Thanks</p>
0
2016-10-18T00:31:01Z
40,097,904
<p>You can achieve this using <code>eval()</code> function</p> <pre><code>import pandas as pd df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/master/ch08/tips.csv", sep=',') groupbyvalue = ['sex', 'smoker'] fieldstoaggregate = ['tip','total_bill'] dfformula = "r.tip/r.total_bill" (df.groupby(groupbyvalue)[fieldstoaggregate].sum().apply(lambda r: eval(dfformula), axis = 1)) </code></pre> <p>The output would be as follows</p> <pre><code>sex smoker Female No 0.153189 Yes 0.163062 Male No 0.157312 Yes 0.136919 dtype: float64 </code></pre>
1
2016-10-18T01:00:58Z
[ "python", "pandas", "dataframe", "aggregate", "aggregation" ]
Making a list of mouse over event functions in Tkinter
40,097,711
<p>I'm making a GUI for a medical tool as a class project. Given a condition, it should output a bunch of treatment options gathered from different websites like webMD. I would like to be able to handle mouseover events on any of the treatments listed to give a little more information about the treatment (such as the category of drug, whether it is a generic or not, etc).</p> <p>The labels are stored in a list, as I have no idea how many different treatments will be returned beforehand. So my question is how can I make these mouseover events work. I can't write a function definition for every single possible label, they would number in the hundreds or thousands. I'm sure there's a very pythonic way to do it, but I have no idea what.</p> <p>Here's my code for creating the labels:</p> <pre><code> def search_click(): """ Builds the search results after the search button has been clicked """ self.output_frame.destroy() # Delete old results build_output() # Rebuild output frames treament_list = mockUpScript.queryConditions(self.condition_entry.get()) # Get treatment data labels = [] frames = [self.onceFrame, self.twiceFrame, self.threeFrame, self.fourFrame] # holds the list of frames for treament in treament_list: # For each treatment in the list label = ttk.Label(frames[treament[1] - 1], text=treament[0]) # Build the label for treatment labels.append(label) # Add the treatment to the list label.pack() </code></pre> <p>and here is what the GUI looks like (don't judge [-; )<a href="https://i.stack.imgur.com/RXFyL.png" rel="nofollow"><img src="https://i.stack.imgur.com/RXFyL.png" alt="GUI image"></a></p> <p>The text "Hover over drugs for information" should be changed depending on which drug your mouse is hovering over.</p>
3
2016-10-18T00:32:05Z
40,097,861
<blockquote> <p>I can't write a function definition for every single possible label, they would number in the hundreds or thousands. I'm sure there's a very pythonic way to do it, but I have no idea what.</p> </blockquote> <p>Check out <a href="http://www.secnetix.de/olli/Python/lambda_functions.hawk" rel="nofollow">lambda functions</a> which are nearly identical to what you want.</p> <p>In your case, something like:</p> <pre><code>def update_bottom_scroll_bar(text): # whatever you want to do to update the text at the bottom for treatment in treament_list: # For each treatment in the list label = ttk.Label(frames[treatment[1] - 1], text=treatment[0]) # Build the label for treatment label.bind("&lt;Enter&gt;", lambda event, t=treatment: update_bottom_scroll_bar(text=t)) label.bind("&lt;Leave&gt;", lambda event: update_bottom_scroll_bar(text='Default label text')) labels.append(label) # Add the treatment to the list label.pack() </code></pre> <p>Also please spell your variables right, I corrected <code>treament</code> to <code>treatment</code>...</p>
3
2016-10-18T00:54:35Z
[ "python", "list", "user-interface", "tkinter", "mouseover" ]
How to click on the list of the <li> elements in an <ul> elements with selenium in python?
40,097,838
<p><a href="https://i.stack.imgur.com/0rFR0.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/0rFR0.jpg" alt="enter image description here"></a></p> <p>I tried to select 2002 in dropdown menu. It doesn't work at any late. I used xpath</p> <pre><code>driver.find_element_by_xpath("html/body/main/div/form/div[3]/div[1]/section/div[3]/fieldset/div[7]/dl[1]/dd/ul/li[1]/a").click() </code></pre> <p>but it doesn't work..I tried all the solutions I got... How can I select this?</p>
2
2016-10-18T00:51:18Z
40,097,955
<p>If you're able to open dropdown item but unable to click on item, you should try using <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow"><code>Explicit Waits</code></a> with <code>WebDriverWait</code> to wait until this element is visible and enable to click as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul#ulBirthYear a[data-value='2002']"))) element.click() </code></pre> <p>Or</p> <pre><code>element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "2002"))) element.click() </code></pre>
1
2016-10-18T01:09:24Z
[ "python", "selenium" ]
How to click on the list of the <li> elements in an <ul> elements with selenium in python?
40,097,838
<p><a href="https://i.stack.imgur.com/0rFR0.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/0rFR0.jpg" alt="enter image description here"></a></p> <p>I tried to select 2002 in dropdown menu. It doesn't work at any late. I used xpath</p> <pre><code>driver.find_element_by_xpath("html/body/main/div/form/div[3]/div[1]/section/div[3]/fieldset/div[7]/dl[1]/dd/ul/li[1]/a").click() </code></pre> <p>but it doesn't work..I tried all the solutions I got... How can I select this?</p>
2
2016-10-18T00:51:18Z
40,097,995
<p>First of all, try to avoid using absolute XPATH. Use something like this:</p> <pre><code>'//ul[@id="uiBirthYear"]/li/a[@data-value="2002"]' </code></pre> <p>Also ensure, that the DOM is fully built, before you trying to get/click on this element.</p> <p>Try to set an <em>implicit wait</em></p> <pre><code>driver.implicitly_wait(10) </code></pre> <p>or an <em>explicit wait</em> (read more: <a href="http://selenium-python.readthedocs.io/waits.html" rel="nofollow">http://selenium-python.readthedocs.io/waits.html</a>)</p>
0
2016-10-18T01:14:50Z
[ "python", "selenium" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> <pre><code>for merchant, product, quantity in big_list: d[merchant][product] += quantity print ({ k:dict(v) for k,v in d.items() }) </code></pre> <p>My desired output:</p> <pre><code>'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQ SEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 </code></pre> <p>As I am still new to python, may I ask if i wish to remove the all the curly brackets in the dictionary of dictionaries. Would my desired output be achievable? If so, how should I go about doing it? Any suggestions / ideas would be appreciated. Thank you.</p>
3
2016-10-18T00:54:53Z
40,097,901
<p>You can do this by converting the dictionary first to a string and then replacing all the brackets with empty strings:</p> <pre><code>d = {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQSEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} print(str(d).replace("{","").replace("}", "")) </code></pre> <p>which will print what you are looking for:</p> <pre><code>'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQSEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 </code></pre>
1
2016-10-18T01:00:29Z
[ "python", "dictionary" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> <pre><code>for merchant, product, quantity in big_list: d[merchant][product] += quantity print ({ k:dict(v) for k,v in d.items() }) </code></pre> <p>My desired output:</p> <pre><code>'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQ SEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 </code></pre> <p>As I am still new to python, may I ask if i wish to remove the all the curly brackets in the dictionary of dictionaries. Would my desired output be achievable? If so, how should I go about doing it? Any suggestions / ideas would be appreciated. Thank you.</p>
3
2016-10-18T00:54:53Z
40,097,968
<p>Build up the string like so</p> <pre><code>d = {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} st = ', '.join('%r: %s' % (k, ', '.join('%r: %r' % (sk, sv) for sk, sv in v.items())) for k, v in d.items()) print(st) </code></pre> <p>This code builds the string by first iterating over the outer dict. It appends the key to the string (plus a ':' in keeping with your formatting requirements). Then it iterates over the inner dict and appends the key and value the same way. It uses the <code>%r</code> format specifier which means that the elements being printed are converted using their <code>repr</code> function. This gives the strings their quotes, without having to manually add them.</p> <p>You can't count on the order being fixed though. So for different runs you'll get slightly different orders. </p> <p>Output looks like</p> <blockquote> <p>'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQ SEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 </p> </blockquote> <p>Someone could probably wrap it up into a giant <code>join</code>/comprehension to make it more functional if they really wanted to.</p>
0
2016-10-18T01:12:07Z
[ "python", "dictionary" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> <pre><code>for merchant, product, quantity in big_list: d[merchant][product] += quantity print ({ k:dict(v) for k,v in d.items() }) </code></pre> <p>My desired output:</p> <pre><code>'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQ SEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 </code></pre> <p>As I am still new to python, may I ask if i wish to remove the all the curly brackets in the dictionary of dictionaries. Would my desired output be achievable? If so, how should I go about doing it? Any suggestions / ideas would be appreciated. Thank you.</p>
3
2016-10-18T00:54:53Z
40,098,210
<pre><code>d = {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} ', '.join(['{}: {}'.format(merchant, ', '.join(['{}: {}'.format(product, quantity) for product, quantity in products.items()])) for merchant, products in d.items()]) </code></pre> <p>if you are using python2 instead of python3, replace items with iteritems</p>
0
2016-10-18T01:40:57Z
[ "python", "dictionary" ]
How to remove the all the curly bracket in dictionary of dictionaries
40,097,863
<p>I wish to remove all the curly brackets from my current output. My current output as shown below:</p> <pre><code> {'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 }} </code></pre> <p>My current code as shown below:</p> <pre><code>for merchant, product, quantity in big_list: d[merchant][product] += quantity print ({ k:dict(v) for k,v in d.items() }) </code></pre> <p>My desired output:</p> <pre><code>'Chin PTE LTD': 'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89, 'COQ SEAFOOD': 'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1 </code></pre> <p>As I am still new to python, may I ask if i wish to remove the all the curly brackets in the dictionary of dictionaries. Would my desired output be achievable? If so, how should I go about doing it? Any suggestions / ideas would be appreciated. Thank you.</p>
3
2016-10-18T00:54:53Z
40,098,348
<pre><code>import re result={'Chin PTE LTD': {'Carrot Cake': 22, 'Chocolate Cake': 12, 'Beer': 89}, 'COQ SEAFOOD': {'GRILLED AUSTRALIA ANGU': 1, 'CRISPY CHICKEN WINGS': 1}} expected_output=re.sub("}|{","",str(result)) </code></pre>
0
2016-10-18T01:58:40Z
[ "python", "dictionary" ]
Downloading the top comments for an imgur image (jpg)
40,097,882
<p>How can I access the comments related to an imgur image using json? </p> <p>for <a href="http://imgur.com/gallery/DVNWyG8" rel="nofollow">http://imgur.com/gallery/DVNWyG8</a> , browsing to <a href="http://api.imgur.com/3/image/DVNWyG8.json" rel="nofollow">http://api.imgur.com/3/image/DVNWyG8.json</a> yields:</p> <pre><code>{"data":{"id":"DVNWyG8","title":"Fiber optic dress","description":null,"datetime":1476709283,"type":"image\/jpeg","animated":false,"width":2056,"height":1694,"size":482983,"views":1883274,"bandwidth":909589326342,"vote":null,"favorite":false,"nsfw":false,"section":"pics","account_url":null,"account_id":null,"is_ad":false,"in_gallery":true,"link":"http:\/\/i.imgur.com\/DVNWyG8.jpg"},"success":true,"status":200} </code></pre> <p>Also I can't wget it as I get this error:</p> <pre><code>wget http://api.imgur.com/3/image/DVNWyG8.json --2016-10-17 19:55:48-- http://api.imgur.com/3/image/DVNWyG8.json Resolving api.imgur.com (api.imgur.com)... 151.101.44.193 Connecting to api.imgur.com (api.imgur.com)|151.101.44.193|:80... connected. HTTP request sent, awaiting response... 400 Bad Request 2016-10-17 19:55:48 ERROR 400: Bad Request. </code></pre> <p>Basically I want to download an Imgur image with its top 30 comments. I wonder if I should do something with its json or if there's a neat Python API for this purpose? </p> <p>Even using the API, I don't see the method for getting all the comments related to an image:</p> <pre><code> 9 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 10 11 image = imgur_client.get_image("S1jmapR") 12 print(image.title) 13 print(image.link) 14 print(dir(image)) </code></pre> <p>I get:</p> <pre><code>mona@pascal:~/computer_vision/imgur$ python download.py /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Cat Ying &amp; Yang http://i.imgur.com/S1jmapR.jpg ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'account_id', 'account_url', 'animated', 'bandwidth', 'datetime', 'description', 'favorite', 'height', 'id', 'in_gallery', 'is_ad', 'link', 'nsfw', 'section', 'size', 'title', 'type', 'views', 'vote', 'width'] mona@pascal:~/computer_vision/imgur$ vi download.py </code></pre> <p>As you see image has no comment method or get_comment.</p>
0
2016-10-18T00:58:19Z
40,098,189
<p>This python library here suits your needs, <a href="https://github.com/Imgur/imgurpython" rel="nofollow">https://github.com/Imgur/imgurpython</a></p>
0
2016-10-18T01:38:20Z
[ "python", "json", "web-scraping", "imgur" ]
Downloading the top comments for an imgur image (jpg)
40,097,882
<p>How can I access the comments related to an imgur image using json? </p> <p>for <a href="http://imgur.com/gallery/DVNWyG8" rel="nofollow">http://imgur.com/gallery/DVNWyG8</a> , browsing to <a href="http://api.imgur.com/3/image/DVNWyG8.json" rel="nofollow">http://api.imgur.com/3/image/DVNWyG8.json</a> yields:</p> <pre><code>{"data":{"id":"DVNWyG8","title":"Fiber optic dress","description":null,"datetime":1476709283,"type":"image\/jpeg","animated":false,"width":2056,"height":1694,"size":482983,"views":1883274,"bandwidth":909589326342,"vote":null,"favorite":false,"nsfw":false,"section":"pics","account_url":null,"account_id":null,"is_ad":false,"in_gallery":true,"link":"http:\/\/i.imgur.com\/DVNWyG8.jpg"},"success":true,"status":200} </code></pre> <p>Also I can't wget it as I get this error:</p> <pre><code>wget http://api.imgur.com/3/image/DVNWyG8.json --2016-10-17 19:55:48-- http://api.imgur.com/3/image/DVNWyG8.json Resolving api.imgur.com (api.imgur.com)... 151.101.44.193 Connecting to api.imgur.com (api.imgur.com)|151.101.44.193|:80... connected. HTTP request sent, awaiting response... 400 Bad Request 2016-10-17 19:55:48 ERROR 400: Bad Request. </code></pre> <p>Basically I want to download an Imgur image with its top 30 comments. I wonder if I should do something with its json or if there's a neat Python API for this purpose? </p> <p>Even using the API, I don't see the method for getting all the comments related to an image:</p> <pre><code> 9 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 10 11 image = imgur_client.get_image("S1jmapR") 12 print(image.title) 13 print(image.link) 14 print(dir(image)) </code></pre> <p>I get:</p> <pre><code>mona@pascal:~/computer_vision/imgur$ python download.py /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Cat Ying &amp; Yang http://i.imgur.com/S1jmapR.jpg ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'account_id', 'account_url', 'animated', 'bandwidth', 'datetime', 'description', 'favorite', 'height', 'id', 'in_gallery', 'is_ad', 'link', 'nsfw', 'section', 'size', 'title', 'type', 'views', 'vote', 'width'] mona@pascal:~/computer_vision/imgur$ vi download.py </code></pre> <p>As you see image has no comment method or get_comment.</p>
0
2016-10-18T00:58:19Z
40,098,483
<pre><code> 21 for item in imgur_client.gallery_item_comments("c1SN8", sort='best'): 22 print item.comment </code></pre> <p>Will do the job</p>
1
2016-10-18T02:17:14Z
[ "python", "json", "web-scraping", "imgur" ]
list.sort() not sorting values correctly by second tuple parameter
40,097,975
<p>I am trying to sort a list of tuples by the second parameter in the tuple in Python 3.5.2 to find which algorithms take the <code>least -&gt; most</code> time in ascending order, however for some reason the looks to be sorting by random. My code:</p> <pre><code>import math def speeds(n): new_dictionary = {} six_n_log_n = 6 * n * math.log(n, 2) thr_n_exp05 = 3 * (n ** 0.5) four_expn = 4 ** n ceil_sqrt_n = math.ceil(math.sqrt(n)) five_n = 5 * n n_cubed = n ** 3 log_log_n = math.log(math.log(n, 2)) n_exp_01 = n ** 0.01 floor_2_n_log_exp2_n = math.floor(2 * n * (math.log(n, 2)**2)) n_exp2_log_n = (n ** 2) * math.log(n, 2) log_exp2_n = math.log(n, 2) ** 2 one_div_n = 1 / n two_exp_n = 2 ** n four_exp_logn = 4 ** (math.log(n, 2)) two_exp_logn = 2 ** (math.log(n, 2)) four_n_exp_threehalves = 4 * (n ** (3/2)) n_exp2 = n ** 2 sqrt_log_n = math.sqrt(math.log(n, 2)) new_dictionary[0] = six_n_log_n new_dictionary[1] = thr_n_exp05 new_dictionary[2] = four_expn new_dictionary[3] = ceil_sqrt_n new_dictionary[4] = five_n new_dictionary[5] = n_cubed new_dictionary[6] = log_log_n new_dictionary[7] = n_exp_01 new_dictionary[8] = floor_2_n_log_exp2_n new_dictionary[9] = n_exp2_log_n new_dictionary[10] = log_exp2_n new_dictionary[11] = one_div_n new_dictionary[12] = two_exp_n new_dictionary[13] = four_exp_logn new_dictionary[14] = two_exp_logn new_dictionary[15] = four_n_exp_threehalves new_dictionary[16] = n_exp2 new_dictionary[17] = sqrt_log_n sorted_list = [] for key in new_dictionary: sorted_list.append((key, new_dictionary[key])) sorted_list.sort(key=lambda x: x[1]) for i, x in sorted_list: print(sorted_list[i]) return sorted_list n = 15 speeds(n) </code></pre> <p>The expected output should be tuples in ascending order by the second parameter, but instead, I receive this:</p> <pre><code>(15, 232.379000772445) (10, 15.263794126054286) (14, 15.000000000000002) (2, 1073741824) (17, 1.9765855902562173) (7, 1.027450511266727) (9, 879.0503840119167) (13, 225.00000000000006) (3, 4) (12, 32768) (8, 457) (5, 3375) (11, 0.06666666666666667) (4, 75) (16, 225) (1, 11.618950038622252) (0, 351.6201536047667) (6, 1.3627418135330593) </code></pre> <p>Can anyone tell me why I'm getting a seemingly random order from this? Can't seem to find where my problem is.</p>
0
2016-10-18T01:13:02Z
40,098,040
<p>If you examine <code>sorted_list</code> following the sort, you will see that it has been sorted correctly.</p> <pre><code>[(11, 0), (7, 1.027450511266727), (6, 1.3627418135330593), (17, 1.9765855902562173), (3, 4.0), (1, 11.618950038622252), (14, 15.000000000000002), (10, 15.263794126054286), (15, 60), (4, 75), (16, 225), (13, 225.00000000000006), (0, 351.6201536047667), (8, 457.0), (9, 879.0503840119167), (5, 3375), (12, 32768), (2, 1073741824)] </code></pre> <p>The error occurs in the following line:</p> <pre><code>for i, x in sorted_list: </code></pre> <p>You are not iterating over the keys and values as you think. Rather, this is unpacking each tuple in the list and assigning its first component to <code>i</code> and its second component to <code>x</code>. You are then accessing the element at the <code>i</code>th position in the list, which leads to what appears to be a random ordering. You can instead write:</p> <pre><code>for i, x in enumerate(sorted_list): </code></pre> <p>Or more simply, you can print the tuple you are trying to display</p> <pre><code>for item in sorted_list: print(item) </code></pre>
4
2016-10-18T01:20:26Z
[ "python", "python-3.x", "sorting", "tuples" ]
list.sort() not sorting values correctly by second tuple parameter
40,097,975
<p>I am trying to sort a list of tuples by the second parameter in the tuple in Python 3.5.2 to find which algorithms take the <code>least -&gt; most</code> time in ascending order, however for some reason the looks to be sorting by random. My code:</p> <pre><code>import math def speeds(n): new_dictionary = {} six_n_log_n = 6 * n * math.log(n, 2) thr_n_exp05 = 3 * (n ** 0.5) four_expn = 4 ** n ceil_sqrt_n = math.ceil(math.sqrt(n)) five_n = 5 * n n_cubed = n ** 3 log_log_n = math.log(math.log(n, 2)) n_exp_01 = n ** 0.01 floor_2_n_log_exp2_n = math.floor(2 * n * (math.log(n, 2)**2)) n_exp2_log_n = (n ** 2) * math.log(n, 2) log_exp2_n = math.log(n, 2) ** 2 one_div_n = 1 / n two_exp_n = 2 ** n four_exp_logn = 4 ** (math.log(n, 2)) two_exp_logn = 2 ** (math.log(n, 2)) four_n_exp_threehalves = 4 * (n ** (3/2)) n_exp2 = n ** 2 sqrt_log_n = math.sqrt(math.log(n, 2)) new_dictionary[0] = six_n_log_n new_dictionary[1] = thr_n_exp05 new_dictionary[2] = four_expn new_dictionary[3] = ceil_sqrt_n new_dictionary[4] = five_n new_dictionary[5] = n_cubed new_dictionary[6] = log_log_n new_dictionary[7] = n_exp_01 new_dictionary[8] = floor_2_n_log_exp2_n new_dictionary[9] = n_exp2_log_n new_dictionary[10] = log_exp2_n new_dictionary[11] = one_div_n new_dictionary[12] = two_exp_n new_dictionary[13] = four_exp_logn new_dictionary[14] = two_exp_logn new_dictionary[15] = four_n_exp_threehalves new_dictionary[16] = n_exp2 new_dictionary[17] = sqrt_log_n sorted_list = [] for key in new_dictionary: sorted_list.append((key, new_dictionary[key])) sorted_list.sort(key=lambda x: x[1]) for i, x in sorted_list: print(sorted_list[i]) return sorted_list n = 15 speeds(n) </code></pre> <p>The expected output should be tuples in ascending order by the second parameter, but instead, I receive this:</p> <pre><code>(15, 232.379000772445) (10, 15.263794126054286) (14, 15.000000000000002) (2, 1073741824) (17, 1.9765855902562173) (7, 1.027450511266727) (9, 879.0503840119167) (13, 225.00000000000006) (3, 4) (12, 32768) (8, 457) (5, 3375) (11, 0.06666666666666667) (4, 75) (16, 225) (1, 11.618950038622252) (0, 351.6201536047667) (6, 1.3627418135330593) </code></pre> <p>Can anyone tell me why I'm getting a seemingly random order from this? Can't seem to find where my problem is.</p>
0
2016-10-18T01:13:02Z
40,098,056
<p>When you iterate over your tuples, you want to print the <em>tuple</em> itself:</p> <pre><code>for tup in sorted_list: print(tup) </code></pre> <p>otherwise, you are printing the values at the index based on the <em>first value</em> of the index. For example, the first value in the sorted list is:</p> <pre><code>(11, 0) </code></pre> <p>is actually looking for:</p> <pre><code>sorted_list[11] </code></pre> <p>which is why you see the improper first value.</p>
1
2016-10-18T01:22:37Z
[ "python", "python-3.x", "sorting", "tuples" ]
PyQt5 Pass user inputs from GUI to main code
40,097,999
<p>I have an interface that prompts users for 3 inputs and a selection from a comboBox. What I want to happen is have all of the information entered by the user, they press the button and then those inputs are used to run on the subsequent processes for the project (folder creation, copying, ect).</p> <p>My problem is that I do not know how to grab the variable I am assigning from the user inputs. If I place the app.exec_() after I am calling the variables in if___name___ they appear to never be assigned. How can call this .py file and pass the necessary inputs to the other parts of my code? Thanks for any help, I am brand new to python and qt so if this is making no sense ill try my best to clarify...</p> <pre><code>from new2 import Ui_Line import nextProcess from PyQt5 import QtCore, QtGui, QtWidgets import glob, os, shutil #GUI Called from 'new2' now apply functions to create the line based on users inputs class window(QtWidgets.QMainWindow, Ui_Line): def __init__(self, parent = None): QtWidgets.QMainWindow.__init__(self, parent) self.setupUi(self) self.pushButton.clicked.connect(self.assign) #Function that happens when the 'click line' button is pressed def assign(self): num1 = str(self.num1EDIT.toPlainText()) num2 = str(self.num2EDIT.toPlainText()) num3 = str(self.num3EDIT.toPlainText()) mas = str(self.comboBox.currentText()) if mas == 'Path 1': master = 'cbm' elif mas == 'Path 2': master = 'crwt' else: master = 'wst' #QtCore.QCoreApplication.instance().quit() """Potential fix edit proc2 = nextProcess() &lt;---- Do I need to put nextProcess inside the assign() or in the window()? """ return num1, num2, num3, master if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) newWindow = window(None) newWindow.show() app.exec_() # &lt;---- This is my fix, but I know this probably isn't correct info = newWindow.assign() num1 = info[0] num2 = info[1] num3 = info[2] master = info[3] next = nextProcess(num1, num2, num3, master) </code></pre>
0
2016-10-18T01:15:29Z
40,098,242
<p>Instead of having the slot connected to the push button's <code>clicked()</code> signal quit the application, just have it run the code you're interested in using the appropriate values.</p> <p>So the <code>assign()</code> method could more aptly be named <code>callNextProcess()</code>, which retrieves the values from the widgets and just calls <code>nextProcess()</code> directly.</p>
0
2016-10-18T01:44:14Z
[ "python", "qt", "pyqt5" ]
Plot each column of Pandas dataframe pairwise against one column
40,098,058
<p>I have a pandas dataframe where one of the columns is a set of labels that I would like to plot each of the other columns against in subplots. In other words, I want the y-axis of each subplot to use the same column, called 'labels', and I want a subplot for each of the remaining columns with the data from each column on the x-axis. I expected the following code snippet to achieve this, but I don't understand why this results in a single nonsensical plot:</p> <pre><code>examples.plot(subplots=True, layout=(-1, 3), figsize=(20, 20), y='labels', sharey=False) </code></pre>
0
2016-10-18T01:22:42Z
40,098,371
<p>The problem with that code is that you didn't specify an x value. It seems nonsensical because it's plotting the <code>labels</code> column against an index from 0 to the number of rows. As far as I know, you can't do what you want in pandas directly. You might want to check out <a href="https://seaborn.github.io/generated/seaborn.PairGrid.html#seaborn.PairGrid" rel="nofollow">seaborn</a> though, it's another visualization library that has some nice grid plotting helpers.</p> <p>Here's an example with your data:</p> <pre><code>import pandas as pd import seaborn as sns import numpy as np examples = pd.DataFrame(np.random.rand(10,4), columns=['a', 'b', 'c', 'labels']) g = sns.PairGrid(examples, x_vars=['a', 'b', 'c'], y_vars='labels') g = g.map(plt.plot) </code></pre> <p>This creates the following plot: <a href="https://i.stack.imgur.com/cv8n8.png" rel="nofollow"><img src="https://i.stack.imgur.com/cv8n8.png" alt="enter image description here"></a></p> <p>Obviously it doesn't look great with random data, but hopefully with your data it will look better. </p>
1
2016-10-18T02:01:20Z
[ "python", "pandas", "plot" ]
python sentence tokenizing according to the word index of dictionary
40,098,093
<p>I have a vocabulary with the form of dic = {'a':30, 'the':29,....}, the key is the word, the value is its word count. </p> <p>I have some sentences, like:</p> <p>"this is a test"</p> <p>"an apple"</p> <p>....</p> <p>In order to tokenize the sentences, each sentence will be encoded as the word index of dictionary. If the word in a sentence also exist in the dictionary, get this word's index; otherwise set the value to 0.</p> <p>for example, I set the sentence dimension to 6, if the length of a sentence is smaller than 6, padding 0s to make it 6 dimension.</p> <p>"this is the test" ----> [2, 0, 2, 4, 0, 0] "an apple" ----> [5, 0, 0, 0, 0, 0,]</p> <p>Here is my sample code:</p> <pre><code>words=['the','a','an'] #use this list as my dictionary X=[] with open('test.csv','r') as infile: for line in infile: for word in line: if word in words: X.append(words.index(word)) else: X.append(0) </code></pre> <p>My code has some problem because the output is not correct; in addition, I have no idea how to set the sentence dimension and how to padding. </p>
0
2016-10-18T01:25:45Z
40,098,700
<p>There are a couple of issues with your code:</p> <ol> <li><p>You're not tokenizing on a word, but a character. You need to split up each line into words</p></li> <li><p>You're appending into one large list, instead of a list of lists representing each sentence/line</p></li> <li><p>Like you said, you don't limit the size of the list</p></li> <li><p>I also don't understand why you're using a list as a dictionary</p></li> </ol> <p>I edited your code below, and I think it aligns better with your specifications:</p> <pre><code>words={'the': 2,'a': 1,'an': 3} X=[] with open('test.csv','r') as infile: for line in infile: # Inits the sublist to [0, 0, 0, 0, 0, 0] sub_X = [0] * 6 # Enumerates each word in the list with an index # split() splits a string by whitespace if no arg is given for idx, word in enumerate(line.split()): if word in words: # Check if the idx is within bounds before accessing if idx &lt; 6: sub_X[idx] = words[word] # X represents the overall list and sub_X the sentence X.append(sub_X) </code></pre>
1
2016-10-18T02:46:21Z
[ "python", "encoding", "tokenize" ]
ImportError only for crontab job?
40,098,216
<p>So I wrote a nifty automation script that does some of my work for me via the jira module + handy dandy logic. It runs perfectly from the command line via:</p> <pre><code>me@local] ~/Documents/auto_updater &gt; python /Users/me/Documents/auto_updater/jira_updater.py Missing info starting checking out: ES-20157 No array outage Already has sev1_missing_outage label. ***snip*** </code></pre> <p>It also works just fine ran with fullpath without the python call:</p> <pre><code>me@local] ~/Documents/auto_updater &gt; /Users/me/Documents/auto_updater/jira_updater.py Missing info starting checking out: ES-20157 No array outage Already has sev1_missing_outage label. </code></pre> <p>Now - assuming that it working means life is good, I decided to set it up on a crontab for 30 min periods, and I'm getting spam failures every time where it can't seem to find the jira module:</p> <pre><code>From me@me-mbp Mon Oct 17 19:30:04 2016 Return-Path: &lt;me@me-mbp&gt; X-Original-To: me Delivered-To: me@me-mbp Received: by me-mbp (Postfix, from userid 502) id 514D0203328A; Mon, 17 Oct 2016 19:30:00 -0600 (MDT) From: me@me-mbp (Cron Daemon) To: me@me-mbp Subject: Cron &lt;me@local&gt; python /Users/me/Documents/auto_updater/jira_updater.py &gt;&gt; /Users/me/Documents/auto_updater/updated_log.txt X-Cron-Env: &lt;SHELL=/bin/sh&gt; X-Cron-Env: &lt;PATH=/usr/bin:/bin&gt; X-Cron-Env: &lt;LOGNAME=me&gt; X-Cron-Env: &lt;USER=me&gt; X-Cron-Env: &lt;HOME=/Users/me&gt; Message-Id: &lt;[email protected]&gt; Date: Mon, 17 Oct 2016 19:30:00 -0600 (MDT) Traceback (most recent call last): File "/Users/me/Documents/auto_updater/jira_updater.py", line 3, in &lt;module&gt; from jira.client import JIRA ImportError: No module named jira.client </code></pre> <p>Originally I had problems with the #!/usr/bin/python path, so I switched it to #!/usr/bin/env python:</p> <pre><code>[me@local] ~/Documents/auto_updater &gt; head jira_updater.py #!/usr/bin/env python from jira.client import JIRA import random # Here's some responses that we can randomize from so it doesn't feel quite so botty. FIRST_RESPONSES = ['- Do you need help moving this forward?', '- Can I help you get traction on this?', </code></pre> <p>I've seen some workarounds that state that I just need my cronjob to run with my pythonpath explicitely declared, but that seems like a shoddy workaround, and I've set up a server to run this for me, so I'd prefer to solve it by making things work properly - but what I can't figure out is why the cronjob run command can't seem to find the module, but I can as root run it with the same syntax as specified in the crontab. I've verified this by manually running the same commant specified in the crontab:</p> <pre><code>me@local] ~/Documents/auto_updater &gt; crontab -l */30 * * * * python /Users/me/Documents/auto_updater/jira_updater.py &gt;&gt; /Users/me/Documents/auto_updater/updated_log.txt </code></pre> <p>Anyone have any insight into why cronjob can't find the module, or is specifying the pythonpath manually really the only "fix"?</p>
0
2016-10-18T01:41:07Z
40,100,537
<p>probably explicitly append the lib path for jira in jira_updater.py should do.</p> <pre><code># added code below before import jira # append path where jira lib located, for example in /usr/bin/lib import sys sys.path.append('/usr/bin/lib') # if yout don't know where jira located, use code below to get jira path first # then put the path found into code sys.path.append above import imp;imp.find_module('jira') </code></pre>
0
2016-10-18T05:54:18Z
[ "python", "import", "cron", "jira" ]
What does <function at ...> mean
40,098,280
<p>Here's the code:</p> <pre><code>def my_func(f, arg): return f(arg) print((lambda x: 2*x*x, (5))) &gt;&gt;&gt;(&lt;function &lt;lambda&gt; at 0x10207b9d8&gt;, 5) </code></pre> <p>How to solve the error, and can some please explain in a clear language what exactly that error means.</p>
0
2016-10-18T01:48:37Z
40,098,556
<p>There is no error; you simply supplied two arguments to <code>print</code>, the <code>lambda x: 2*x*x</code> and <code>5</code>. You're not calling your anonymous function rather, just passing it to <code>print</code>.</p> <p><code>print</code> will then call the objects <code>__str__</code> method which returns what you see:</p> <pre><code>&gt;&gt;&gt; str(lambda x: 2*x*x) # similarly for '5' '&lt;function &lt;lambda&gt; at 0x7fd4ec5f0048&gt;' </code></pre> <p>Instead, fix your parenthesis to actually <em>call</em> the lambda with the <code>5</code> passed as the value for <code>x</code>:</p> <pre><code>print((lambda x: 2*x*x)(5)) </code></pre> <p>which prints out <code>50</code>.</p> <hr> <blockquote> <p>What's the general meaning of <code>&lt;function at 0x ...&gt;</code>?</p> </blockquote> <p>That's simply the way Python has chosen to represent function objects when printed. Their <code>str</code> takes the name of the function and the <code>hex</code> of the <code>id</code> of the function and prints it out. E.g:</p> <pre><code>def foo(): pass print(foo) # &lt;function foo at 0x7fd4ec5dfe18&gt; </code></pre> <p>Is created by returning the string:</p> <pre><code>"&lt;function {0} at {1}&gt;".format(foo.__name__, hex(id(foo))) </code></pre>
2
2016-10-18T02:27:35Z
[ "python", "function", "python-3.x" ]
Converting If statement to a loop
40,098,290
<p>I am working on a practice problem where we are to input a list into a function argument, that will represent a tic tac toe board, and return the outcome of the board. That is, X wins, O wins, Draw, or None (null string).</p> <p>I have it solved, but I was wondering if there is a way I could manipulate my algorithm into a loop, as it was recommended to use a loop to compare each element of the main diagonal with all the elements of its intersecting row and column, and then check the two diagonals. I'm new to python, so my solution might be a bit longer then it needs to be. How could a loop be implemented to check the outcome of the tic tac toe board? </p> <pre><code>def gameState (List): xcounter=0 ocounter=0 if List[0][0]==List[0][1] and List[0][0]==List[0][2]: return List[0][0] elif List[0][0]==List[1][0] and List[0][0]==List[2][0]: return List[0][0] elif List[0][0]==List[1][1] and List[0][0]==List[2][2]: return List[0][0] elif List[1][1]==List[1][2] and List[1][1]==List[1][0] : return List[1][1] elif List[1][1]==List[0][1] and List[1][1]==List[2][1]: return List[1][1] elif List[1][1]==List[0][0] and List[1][1]==List[2][2]: return List[1][1] elif List[2][2]==List[2][0] and List[2][2]==List[2][1]: return List[2][2] elif List[2][2]==List[1][2] and List[2][2]==List[0][2]: return List[2][2] elif List[2][2]==List[1][1] and List[2][2]==List[0][0]: return List[2][2] for listt in List: for elm in listt: if elm=="X" or elm=="x": xcounter+=1 elif elm=="O" or elm=="o": ocounter+=1 if xcounter==5 or ocounter==5: return "D" else: return '' </code></pre>
0
2016-10-18T01:50:49Z
40,098,499
<p>First up, there are only <em>eight</em> ways to win at TicTacToe. You have nine compare-and-return statements so one is superfluous. In fact, on further examination, you check <code>00, 11, 22</code> <em>three</em> times (cases 3, 6 and 9) and totally <em>miss</em> the <code>02, 11, 20</code> case.</p> <p>In terms of checking with a loop, you can split out the row/column checks from the diagonals as follows:</p> <pre><code># Check all three rows and columns. for idx in range(3): if List[0][idx] != ' ': if List[0][idx] == List[1][idx] and List[0][idx] == List[2][idx]: return List[0][idx] if List[idx][0] != ' ': if List[idx][0] == List[idx][1] and List[idx][0] == List[idx][2]: return List[idx][0] # Check two diagonals. if List[1][1] != ' ': if List[1][1] == List[0][0] and List[1][1] == List[2][2]: return List[1][1] if List[1][1] == List[0][2] and List[1][1] == List[2][0]: return List[1][1] # No winner yet. return ' ' </code></pre> <p>Note that this ensures a row of empty cells isn't immediately picked up as a win by nobody. You need to check only for wins by a "real" player. By that, I mean you don't want to detect three empty cells in the first row and return an indication based on that if the second row has an <em>actual</em> winner.</p> <hr> <p>Of course, there are numerous ways to refactor such code to make it more easily read and understood. One way is to separate out the logic for checking a <em>single</em> line and then call that for each line:</p> <pre><code># Detect a winning line. First cell must be filled in # and other cells must be equal to first. def isWinLine(brd, x1, y1, x2, y2, x3, y3): if brd[x1][y1] == ' ': return False return brd[x1][y1] == brd[x2][y2] and brd[x1][y1] == brd[x3][y3] # Get winner of game by checking each possible line for a winner, # return contents of one of the cells if so. Otherwise return # empty value. def getWinner(brd): # Rows and columns first. for idx in range(3): if isWinLine(brd, idx, 0, idx, 1, idx, 2): return brd[idx][0] if isWinLine(brd, 0, idx, 1, idx, 2, idx): return brd[0][idx] # Then diagonals. if isWinLine(brd, 0, 0, 1, 1, 2, 2): return brd[1][1] if isWinLine(brd, 2, 0, 1, 1, 0, 2): return brd[1][1] # No winner yet. return ' ' </code></pre> <p>Then you can just use:</p> <pre><code>winner = getWinner(List) </code></pre> <p>in your code and you'll either get back the winner or an empty indication if there isn't one.</p>
5
2016-10-18T02:19:16Z
[ "python", "loops", "for-loop", "while-loop" ]
Default value for ndb.KeyProperty
40,098,294
<p>I have these two models:</p> <pre><code>################# ### Usergroup ### ################# class Usergroup(ndb.Model): group_name = ndb.StringProperty(indexed = False, required = True) is_admin_group = ndb.BooleanProperty(indexed = False, required = False, default = False) ############ ### User ### ############ class User(ndb.Model): fb_id = ndb.StringProperty(indexed = True, required = True) fb_access_token = ndb.TextProperty(indexed = False, required = True) email = ndb.StringProperty(indexed = True, required = True) first_name = ndb.StringProperty(indexed = False, required = True) last_name = ndb.StringProperty(indexed = False, required = True) gender = ndb.StringProperty(indexed = False) group_key = ndb.KeyProperty(indexed = False, required = False, kind = Usergroup, default = ndb.Key(Usergroup, 'member')) join_date = ndb.DateTimeProperty(indexed = True, auto_now_add = True) last_login = ndb.DateTimeProperty(indexed = True, auto_now_add = True, auto_now = False) @app.route('/user/login', methods=['POST']) def user_login(): me = exchange_token_me(request.form['accessToken']) if me is not False: user = user_find_or_register(me) if user is not None: register_session(user) return 'success' return 'error' def user_find_or_register(user): qry = User.query(User.fb_id == user['id']) existing_user = qry.get() if existing_user is not None: existing_user.fb_access_token = user['access_token'] existing_user.fb_id = user['id'] existing_user.email = user['email'] existing_user.last_login = datetime.datetime.now() existing_user.put() return existing_user new_user = User() new_user.fb_id = user['id'] new_user.fb_access_token = user['access_token'] new_user.email = user['email'] new_user.first_name = user['first_name'] new_user.last_name = user['last_name'] new_user.gender = user['gender'] new_user.last_login = datetime.datetime.now() #new_user.group_key = ndb.key(Usergroup, 'member') key = new_user.put() saved_user = key.get() #key.delete() # DEBUG if saved_user is not None: return saved_user def register_session(user): session['fb_id'] = user.fb_id session['first_name'] = user.first_name session['last_name'] = user.last_name session['group_key'] = user.group_key session['loggedin'] = True </code></pre> <p>The Usergroup model has a small unique string as entity key. There is already a Usergroup whose key is 'member'</p> <p>Whenever we create/save a user, it should use the key to the 'member' usergroup, but we get this error instead:</p> <p>TypeError: Key('Usergroup', 'member') is not JSON serializable</p> <p>Traceback:</p> <pre><code>ERROR 2016-10-18 14:32:40,572 app.py:1587] Exception on /user/login [POST] Traceback (most recent call last): File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1643, in full_dispatch_request response = self.process_response(response) File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1864, in process_response self.save_session(ctx.session, response) File "/var/www/mywebsite/public_html/lib/flask/app.py", line 926, in save_session return self.session_interface.save_session(self, session, response) File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 359, in save_session val = self.get_signing_serializer(app).dumps(dict(session)) File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 565, in dumps payload = want_bytes(self.dump_payload(obj)) File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 847, in dump_payload json = super(URLSafeSerializerMixin, self).dump_payload(obj) File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 550, in dump_payload return want_bytes(self.serializer.dumps(obj)) File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 85, in dumps return json.dumps(_tag(value), separators=(',', ':')) File "/var/www/mywebsite/public_html/lib/flask/json.py", line 126, in dumps rv = _json.dumps(obj, **kwargs) File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/lib/python2.7/json/encoder.py", line 209, in encode chunks = list(chunks) File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode o = _default(o) File "/var/www/mywebsite/public_html/lib/flask/json.py", line 83, in default return _json.JSONEncoder.default(self, o) File "/usr/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: Key('Usergroup', 'member') is not JSON serializable ERROR 2016-10-18 14:32:40,593 main.py:178] An error occurred during a request. Traceback (most recent call last): File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1988, in wsgi_app response = self.full_dispatch_request() File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1643, in full_dispatch_request response = self.process_response(response) File "/var/www/mywebsite/public_html/lib/flask/app.py", line 1864, in process_response self.save_session(ctx.session, response) File "/var/www/mywebsite/public_html/lib/flask/app.py", line 926, in save_session return self.session_interface.save_session(self, session, response) File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 359, in save_session val = self.get_signing_serializer(app).dumps(dict(session)) File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 565, in dumps payload = want_bytes(self.dump_payload(obj)) File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 847, in dump_payload json = super(URLSafeSerializerMixin, self).dump_payload(obj) File "/var/www/mywebsite/public_html/lib/itsdangerous.py", line 550, in dump_payload return want_bytes(self.serializer.dumps(obj)) File "/var/www/mywebsite/public_html/lib/flask/sessions.py", line 85, in dumps return json.dumps(_tag(value), separators=(',', ':')) File "/var/www/mywebsite/public_html/lib/flask/json.py", line 126, in dumps rv = _json.dumps(obj, **kwargs) File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/lib/python2.7/json/encoder.py", line 209, in encode chunks = list(chunks) File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode o = _default(o) File "/var/www/mywebsite/public_html/lib/flask/json.py", line 83, in default return _json.JSONEncoder.default(self, o) File "/usr/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: Key('Usergroup', 'member') is not JSON serializable INFO 2016-10-18 14:32:40,610 module.py:788] default: "POST /user/login HTTP/1.1" 500 27 </code></pre> <p>UPDATE: After Dan has spotted the problem, the solution is in the following function:</p> <pre><code>def register_session(user): session['fb_id'] = user.fb_id session['first_name'] = user.first_name session['last_name'] = user.last_name session['group_key'] = user.group_key.id() # Thanks Dan session['loggedin'] = True </code></pre>
1
2016-10-18T01:51:45Z
40,110,173
<p>FWIW, a quick test with your code as <code>models.py</code> shows this to be working just fine, at least on the development server:</p> <pre><code> from models import User user = User(email='email', username='username') user.put() </code></pre> <p>produced:</p> <p><a href="https://i.stack.imgur.com/ZmrHY.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZmrHY.png" alt="enter image description here"></a></p> <p>This worked without even having a <code>Usergroup</code> entity - a key can exist without a matching entity. Of course, trying to follow the link to the Usergroup in the datastore viewer fails:</p> <pre><code>Traceback (most recent call last): File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1536, in __call__ rv = self.handle_exception(request, response, e) File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1530, in __call__ rv = self.router.dispatch(request, response) File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 1102, in __call__ return handler.dispatch() File "/home/usr_local/google_appengine/google/appengine/tools/devappserver2/admin/admin_request_handler.py", line 96, in dispatch super(AdminRequestHandler, self).dispatch() File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) File "/home/usr_local/google_appengine_1.9.40/lib/webapp2-2.5.1/webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "/home/usr_local/google_appengine/google/appengine/tools/devappserver2/admin/datastore_viewer.py", line 741, in get entities = [datastore.Get(entity_key)] File "/home/usr_local/google_appengine/google/appengine/api/datastore.py", line 671, in Get return GetAsync(keys, **kwargs).get_result() File "/home/usr_local/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result return self.__get_result_hook(self) File "/home/usr_local/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1717, in __get_hook entities = extra_hook(entities) File "/home/usr_local/google_appengine/google/appengine/api/datastore.py", line 640, in local_extra_hook raise datastore_errors.EntityNotFoundError() EntityNotFoundError </code></pre> <p>So you might want to show your actual code creating the entity and the full traceback, something else may be going on.</p> <p>Your traceback indicates that the problem is <strong>not</strong> with creating the entity, but with saving your session:</p> <pre><code>File "/var/www/mywebsite/public_html/lib/flask/app.py", line 926, in save_session return self.session_interface.save_session(self, session, response) </code></pre> <p>It appears you included in the session content the key object (possibly by including the entire <code>User</code> entity?), which is what causes the failure. For that purpose keys need to be serialized and you can use <code>key.urlsafe()</code> for that. See this answer for an example: <a href="http://stackoverflow.com/a/34835074/4495081">http://stackoverflow.com/a/34835074/4495081</a></p> <p>If indeed you included the entire <code>User</code> entity in the session you can just include its urlsafe key instead.</p> <p>Yup, this is the source of your problem:</p> <pre><code>session['group_key'] = user.group_key </code></pre> <p>change it to:</p> <pre><code>session['group_key'] = user.group_key.urlsafe() </code></pre> <p>And you'll retrieve it like this:</p> <pre><code>urlsafe_key = session.get('group_key') if urlsafe_key: group_key = ndb.Key(urlsafe=urlsafe_key) </code></pre>
1
2016-10-18T13:53:08Z
[ "python", "google-app-engine", "flask", "google-app-engine-python" ]
Use a list to conditionally fill a new column based on values in multiple columns
40,098,300
<p>I am trying to populate a new column within a pandas dataframe by using values from several columns. The original columns are either <code>0</code> or '1' with exactly a single <code>1</code> per series. The new column would correspond to df['A','B','C','D'] by populating <code>new_col = [1, 3, 7, 10]</code> as shown below. (A <code>1</code> at <code>A</code> means <code>new_col = 1</code>; if <code>B=1</code>,<code>new_col = 3</code>, etc.)</p> <pre><code>df A B C D 1 1 0 0 0 2 0 0 1 0 3 0 0 0 1 4 0 1 0 0 </code></pre> <p>The new <code>df</code> should look like this.</p> <pre><code>df A B C D new_col 1 1 0 0 0 1 2 0 0 1 0 7 3 0 0 0 1 10 4 0 1 0 0 3 </code></pre> <p>I've tried to use <code>map</code>, <code>loc</code>, and <code>where</code> but can't seem to formulate an efficient way to get it done. Problem seems very close <a href="http://stackoverflow.com/questions/36551128/how-to-fill-a-column-conditionally-to-values-in-an-other-column-being-in-a-list">to this</a>. A couple other posts I've looked at <a href="http://stackoverflow.com/questions/10715519/conditionally-fill-column-values-based-on-another-columns-value-in-pandas">1</a> <a href="http://stackoverflow.com/questions/19226488/python-pandas-change-one-value-based-on-another-value">2</a> <a href="http://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas">3</a>. None of these show how to use multiple columns conditionally to fill a new column based on a list.</p>
1
2016-10-18T01:52:59Z
40,098,712
<p>It's not the most elegant solution, but for me it beats the if/elif/elif loop:</p> <pre><code>d = {'A': 1, 'B': 3, 'C': 7, 'D': 10} def new_col(row): k = row[row == 1].index.tolist()[0] return d[k] df['new_col'] = df.apply(new_col, axis=1) </code></pre> <p>Output:</p> <pre><code> A B C D new_col 1 1 0 0 0 1 2 0 0 1 0 7 3 0 0 0 1 10 4 0 1 0 0 3 </code></pre>
0
2016-10-18T02:47:10Z
[ "python", "list", "python-2.7", "pandas" ]
Use a list to conditionally fill a new column based on values in multiple columns
40,098,300
<p>I am trying to populate a new column within a pandas dataframe by using values from several columns. The original columns are either <code>0</code> or '1' with exactly a single <code>1</code> per series. The new column would correspond to df['A','B','C','D'] by populating <code>new_col = [1, 3, 7, 10]</code> as shown below. (A <code>1</code> at <code>A</code> means <code>new_col = 1</code>; if <code>B=1</code>,<code>new_col = 3</code>, etc.)</p> <pre><code>df A B C D 1 1 0 0 0 2 0 0 1 0 3 0 0 0 1 4 0 1 0 0 </code></pre> <p>The new <code>df</code> should look like this.</p> <pre><code>df A B C D new_col 1 1 0 0 0 1 2 0 0 1 0 7 3 0 0 0 1 10 4 0 1 0 0 3 </code></pre> <p>I've tried to use <code>map</code>, <code>loc</code>, and <code>where</code> but can't seem to formulate an efficient way to get it done. Problem seems very close <a href="http://stackoverflow.com/questions/36551128/how-to-fill-a-column-conditionally-to-values-in-an-other-column-being-in-a-list">to this</a>. A couple other posts I've looked at <a href="http://stackoverflow.com/questions/10715519/conditionally-fill-column-values-based-on-another-columns-value-in-pandas">1</a> <a href="http://stackoverflow.com/questions/19226488/python-pandas-change-one-value-based-on-another-value">2</a> <a href="http://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas">3</a>. None of these show how to use multiple columns conditionally to fill a new column based on a list.</p>
1
2016-10-18T01:52:59Z
40,098,922
<p>I can think of a few ways, mostly involving <code>argmax</code> or <code>idxmax</code>, to get either an ndarray or a Series which we can use to fill the column.</p> <p>We could drop down to <code>numpy</code>, find the maximum locations (where the 1s are) and use those to index into an array version of new_col:</p> <pre><code>In [148]: np.take(new_col,np.argmax(df.values,1)) Out[148]: array([ 1, 7, 10, 3]) </code></pre> <p>We could make a Series with new_col as the values and the columns as the index, and index into that with idxmax:</p> <pre><code>In [116]: pd.Series(new_col, index=df.columns).loc[df.idxmax(1)].values Out[116]: array([ 1, 7, 10, 3]) </code></pre> <p>We could use get_indexer to turn the column idxmax results into integer offsets we can use with new_col:</p> <pre><code>In [117]: np.array(new_col)[df.columns.get_indexer(df.idxmax(axis=1))] Out[117]: array([ 1, 7, 10, 3]) </code></pre> <p>Or (and this seems very wasteful) we could make a new frame with the new columns and use idxmax directly:</p> <pre><code>In [118]: pd.DataFrame(df.values, columns=new_col).idxmax(1) Out[118]: 0 1 1 7 2 10 3 3 dtype: int64 </code></pre>
1
2016-10-18T03:14:32Z
[ "python", "list", "python-2.7", "pandas" ]
How to use Iterator that traverses the doubly linked list and skips null nodes
40,098,393
<p>Since the doubly linked list has two dummy nodes, one is the head and the other one is the tail. I can skip the dummy tail node by <code>self.__current == None: raise StopIteration</code>, but I don't know how to pass the dummy head nodes and continue traverse the following node.</p> <pre><code>class LinkedListDLL: def __init__(self): self.__head = NodeDLL(None) self.__head.set_next(self.__head) self.__head.set_prev(self.__head) self.__count = 0 def size(self): return self.__count; def is_empty(self): return self.__count == 0 def add_before(self, item, curr): new_node = NodeDLL(item) new_node.set_next(curr) new_node.set_prev(curr.get_prev()) curr.set_prev(new_node) new_node.get_prev().set_next(new_node) self.__count += 1 def add_to_head(self, item): self.add_before(item, self.__head.get_next()) def add_to_tail(self, item): self.add_before(item, self.__head) def remove_from_head(self): self.remove(self.__head.get_next()) def remove_from_tail(self): self.remove(self.__head.get_prev()) def remove(self, curr): curr.get_prev().set_next(curr.get_next()) curr.get_next().set_prev(curr.get_prev()) self.__count -= 1 def __iter__(self): return LinkedListIterator(self.__head) class LinkedListIterator: def __init__(self, head): self.__current = head def __next__(self): if self.__current == None : raise StopIteration else: item = self.__current.set_data.get_next() self.__current = self.__current.get_next() return item </code></pre>
0
2016-10-18T02:03:46Z
40,098,653
<p>You should refactor your code keeping in mind that <code>NodeDLL(None)</code> may not be the same as <code>None</code>. With that done:</p> <pre><code>def __next__(self): if not self.__current.get_next(): raise StopIteration #Skips first value in list, i.e. head self.__current = self.__current.get_next() return self.__current </code></pre>
0
2016-10-18T02:40:09Z
[ "python", "linked-list", "iterator", "doubly-linked-list" ]
Python -Passing a class method as the default value of an argument to another class initialization
40,098,414
<p>Modifying the original question to prevent confusions. I have 2 classes defined in 2 different modules:</p> <pre><code>class Heuristic: def process(self,data,x,y): processed_data = (data + x) /y return processed_data class GTS(Abstract_Strat): def __init__(self, data, method= Heuristic().process(),*args): self.data= data self.method = method self.func_args = args </code></pre> <p>So in the class GTS, in the initialization function, I am trying to pass a method that belongs to class heuristic which is in another module. On trying this, I get the following error:</p> <pre><code>TypeError: process() takes exactly 3 arguments (1 given) </code></pre> <p>I searched stackoverflow and found similar questions where the <code>Typerror</code> referred to the <code>_init_</code> method. But in this case, the error is for a function passed in as argument to the <code>_init_</code> method. So the question is- What is the right way to pass a method of one class as a default argument value to to intializer of another class?</p>
-1
2016-10-18T02:06:33Z
40,098,492
<p>In python, you must construct an instance of the class before you can have access to an object and then subsequently it's methods.</p> <p>You might do something like:</p> <pre><code>class GTS(Abstract_Strat): heuristic = Heuristic(data) def __init__(self, data, method= heuristic.process(),*args): self.data= data self.method = method self.func_args = args </code></pre> <p>Thereby constructing your object and giving you access to its "bound" methods. The first parameter it is referring to is the "self" in the definition, to which you do not have access until it is an instance of the class has been initialized.</p>
1
2016-10-18T02:18:01Z
[ "python", "class", "methods", "parameter-passing", "typeerror" ]
Python -Passing a class method as the default value of an argument to another class initialization
40,098,414
<p>Modifying the original question to prevent confusions. I have 2 classes defined in 2 different modules:</p> <pre><code>class Heuristic: def process(self,data,x,y): processed_data = (data + x) /y return processed_data class GTS(Abstract_Strat): def __init__(self, data, method= Heuristic().process(),*args): self.data= data self.method = method self.func_args = args </code></pre> <p>So in the class GTS, in the initialization function, I am trying to pass a method that belongs to class heuristic which is in another module. On trying this, I get the following error:</p> <pre><code>TypeError: process() takes exactly 3 arguments (1 given) </code></pre> <p>I searched stackoverflow and found similar questions where the <code>Typerror</code> referred to the <code>_init_</code> method. But in this case, the error is for a function passed in as argument to the <code>_init_</code> method. So the question is- What is the right way to pass a method of one class as a default argument value to to intializer of another class?</p>
-1
2016-10-18T02:06:33Z
40,099,065
<p>I resolved the issue mentioned in the modified question above by changing <code>Heuristic().process()</code> to <code>Heuristic().process</code> when passing it as the default value of the function parameter. </p> <p>Would also like to thank Andrew for his comment on the original version of the question.</p>
0
2016-10-18T03:34:04Z
[ "python", "class", "methods", "parameter-passing", "typeerror" ]
How to Scrape Page HTML and follow Next Link in Selenium
40,098,489
<p>I'm trying to scrape a website for research, and I'm stuck. I want the scraper to read the page source, and append that to a local HTML file so I can analyze the data off-campus. I have experimented with <code>BeautifulSoup</code> and <code>Scrapy</code>, but I have found that I need to use <code>Selenium</code> to interact with the page to navigate through my university's authentication system. (I'm not including that code, because it's tangential to my question.)</p> <p>When I run the script it navigates to the page and clicks the link, but it only saves the first page's HTML. It then duplicates and appends that page's HTML every time it click on the link. </p> <p>How do I use <code>Selenium</code> to click on the next page link, scrape the HTML, and save to file until I reach the last page?</p> <pre><code>source = driver.page_source while True: with open("test.html", "a") as TestFile: TestFile.write(source) try: driver.implicitly_wait(200) driver.find_element_by_css_selector('li.next').click() except AttributeError: break </code></pre> <p>Edit: I added the AttributeError to the except and received the following error.</p> <blockquote> <p>selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document</p> </blockquote> <p>My assumption is that I need to slow down the <code>.click()</code>, which is why I originally had the implicit wait, but that doesn't seem to be doing the trick.</p>
1
2016-10-18T02:17:38Z
40,100,124
<p>You need to assign the <code>page source</code> to <code>source</code> variable inside the while loop.</p> <pre><code>source = driver.page_source while True: with open("test.html", "a") as TestFile: TestFile.write(source) try: driver.implicitly_wait(200) driver.find_element_by_css_selector('li.next').click() source = driver.page_source except AttributeError: break </code></pre>
0
2016-10-18T05:22:20Z
[ "python", "selenium" ]
The `or` operator on dict.keys()
40,098,500
<p>As I've been unable to find any documentation on this, so I'll ask here. </p> <p>As shown in the code below, I found that the <code>or</code> operator (<code>|</code>), worked as such:</p> <pre><code>a = {"a": 1,"b": 2, 2: 3} b = {"d": 10, "e": 11, 11: 12} keys = a.keys() | b.keys() aonce = a.keys() | a.values() bonce = b.keys() | b.values() for i in keys: print(i, end=" ") print() for i in aonce: print(i, end=" ") print() for i in bonce: print(i, end=" ") print() </code></pre> <p>Which produces the result, in some order:</p> <pre><code>2 d 11 a b e 3 1 2 a b 10 e 11 12 d </code></pre> <p>Initially I assumed these iterable was compatible with <code>|</code>, similar to the way sets are, however. Testing with other iterable, such as a <code>list.__iter__()</code>, threw an error. Even; </p> <pre><code>values = a.values() | b.values() for i in values: print(i, end=" ") print() </code></pre> <p>Which I'd assume worked, due to the use of <code>dict.values()</code> in the previous examples, threw an error.</p> <p>So, my question is; What on earth have I come across, and more importantly, how reliable is it? What subclass does my arguments need to be, for me to be able to use this?</p>
3
2016-10-18T02:19:17Z
40,098,512
<p>The <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects">Python 3 Documentation</a> notes that the <code>dict.keys</code> method is set-like and implements <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Set"><code>collections.abc.Set</code></a>.</p> <p>Note that <code>dict.values</code> is <strong>not set-like</strong> even though it might appear to be so in your examples:</p> <pre><code>aonce = a.keys() | a.values() bonce = b.keys() | b.values() </code></pre> <p>However these are leveraging off the fact that the keys view implements <code>__or__</code> (and <code>__ror__</code>) over arbitrary iterables.</p> <p>For example, the following will not work:</p> <pre><code>&gt;&gt;&gt; a.values() | b.values() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for |: 'dict_values' and 'dict_values' </code></pre>
5
2016-10-18T02:21:13Z
[ "python", "python-3.x", "python-3.5" ]
Controlling contour label formatting in pyplot
40,098,535
<p>I'm making a plot where I have contours at <code>[2000, 4000, 6000, 8000]</code>. The contours are labeled as 2000.000, 4000.000 etc. I'd like to get rid of all those trailing zeros. The best option I can find right now is here: <a href="http://matplotlib.org/examples/pylab_examples/contour_label_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/contour_label_demo.html</a>, which suggests defining a new class for the labels which controls how they are displayed, and then using that class. I've never seen such a convoluted option in python before. Is there no more direct way?</p> <p>Here is the code provided as an example of defining a class for the labels.</p> <pre><code>import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.ticker as ticker import matplotlib.pyplot as plt matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' ################################################## # Define our surface ################################################## delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1) ################################################## # Make contour labels using creative float classes # Follows suggestion of Manuel Metz ################################################## plt.figure() # Basic contour plot CS = plt.contour(X, Y, Z) # Define a class that forces representation of float to look a certain way # This remove trailing zero so '1.0' becomes '1' class nf(float): def __repr__(self): str = '%.1f' % (self.__float__(),) if str[-1] == '0': return '%.0f' % self.__float__() else: return '%.1f' % self.__float__() # Recast levels to new class CS.levels = [nf(val) for val in CS.levels] # Label levels with specially formatted floats if plt.rcParams["text.usetex"]: fmt = r'%r \%%' else: fmt = '%r %%' plt.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10) </code></pre>
0
2016-10-18T02:24:37Z
40,101,078
<p>The <code>fmt</code> parameter can be either a classic format string or a callable that converts a scalar to a string.</p> <p>If you don't have fancy requirements you could just pass <code>fmt='%d'</code> instead of a custom class.</p> <p>For common formats you should be also able to resort to the default formatters in <code>matplotlib.ticker</code> before having to implement your own. </p>
0
2016-10-18T06:31:10Z
[ "python", "matplotlib" ]
(<type 'exceptions.ValueError'>, ValueError('need more than 1 value to unpack',), <traceback object at 0x7f24dea1a0e0>) NULL NULL NULL
40,098,589
<p>I have HIVE table like this in MapR.</p> <p><a href="https://i.stack.imgur.com/zTolR.png" rel="nofollow"><img src="https://i.stack.imgur.com/zTolR.png" alt="enter image description here"></a></p> <p>data was separated with commas at back end. I am trying to use custom map reduce in using python. Here is the python code.</p> <pre><code>import sys import datetime try: for line in sys.stdin: line = line.strip() userid, movieid, rating, unixtime = line.split(',') weekday = datetime.datetime.fromtimestamp(float(unixtime)).isoweekday() print ','.join([userid, movieid, rating, unixtime, str(weekday)]) except: print sys.exc_info() </code></pre> <p>I have added python script using <code>add File</code>, submitted query like this</p> <pre><code>select TRANSFORM (userid,movieid,rating,unixtime) using 'python mod.py' as (userid,movieid,rating,weekday) from u_data; </code></pre> <p>Error that i am getting here is </p> <pre><code>(&lt;type 'exceptions.ValueError'&gt;, ValueError('need more than 1 value to unpack',), &lt;traceback object at 0x7f24dea1a0e0&gt;) NULL NULL NULL </code></pre> <p>Why am i getting this error?</p>
0
2016-10-18T02:31:36Z
40,098,954
<p>The only line in your code that could give you that error is this one:</p> <pre><code>userid, movieid, rating, unixtime = line.split(',') </code></pre> <p>So it's complaining that there aren't enough values to unpack, which means there aren't any commas in the line. Try printing the line before processing it; that way you will easily be able to tell what data you are getting and how you need to process it.</p>
0
2016-10-18T03:18:47Z
[ "python", "hive", "mapr" ]
TypeError: can't pickle face_BasicFaceRecognizer objects
40,098,624
<p>I want to store the trained object, however there is an error shown above. What should I do if I need to store this trained model?</p> <pre><code>fishface = cv2.face.createFisherFaceRecognizer() m = fishface.train(training_data, np.asarray(training_labels)) output = open('data.pkl', 'wb') pickle.dump(fishface, output) </code></pre>
0
2016-10-18T02:36:00Z
40,099,011
<p>Unfortunately, OpenCV bindings typically don't support pickling. You'll have to use built-in OpenCV serialization.</p> <p>You can do <code>m.save("serialized_recognizer.cv2")</code> and at runtime, <code>m.load("serialized_recognizer.cv2")</code>, if <code>m</code> is an instantiated FaceRecognizer.</p>
0
2016-10-18T03:27:41Z
[ "python", "opencv", "pickle" ]
pandas Dataframe columns doing algorithm
40,098,680
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'A': ['a', 'a', 'a', 'a', 'a'], 'lon1': [128.0, 135.0, 125.0, 123.0, 136.0], 'lon2': [128.0, 135.0, 139.0, 142.0, 121.0], 'lat1': [38.0, 32.0, 38.0, 38.0, 38.0], 'lat2': [31.0, 32.0, 35.0, 38.0, 29.0], 'angle': [0, 0, 0, 0, 0] }) </code></pre> <p>I want to count the angle of each row by this function and save back to the angle column</p> <pre><code>def angle(lon1,lat1,lon2,lat2): dx = lon2 - lon1 dy = lat2 - lat1 direction = 0; if ((dx == 0) &amp; (dy == 0)): # same position return direction if (dx &gt; 0.0) : direction = 90-np.arctan2(dy,dx)*180/np.pi elif (dy &gt; 0.0 ) : direction = 180+(270-(np.arctan2(dy,dx)*180/np.pi)) else : direction = 360-(270+(np.arctan2(dy,dx)*180/np.pi)) if (direction &lt; 0) : direction += 360 return (direction.astype(int) % 360) </code></pre> <p>I tried </p> <pre><code>df.ix[df['A'].notnull(), 'angle'] =angle( df[df['A'].notnull()]['lon1'], df[df['A'].notnull()]['lat1'], df[df['A'].notnull()]['lon2'], df[df['A'].notnull()]['lat2']) </code></pre> <p>and I got an error</p> <blockquote> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>I tried <code>for index,row in df.iterrows():</code> the result of for loop is ok but it took terribly long long time(original data is about 10 million rows ) </p> <p>could anyone kindly give some efficient methods?</p>
0
2016-10-18T02:44:10Z
40,098,861
<p>It seems like you are trying to apply function <code>angle(...)</code> to every row of your dataframe.</p> <p>First it is necessary to cast all your string-typed numbers into float so as to calculate.</p> <pre><code>df1.loc[:, "lon1"] = df1.loc[:, "lon1"].astype("float") df1.loc[:, "lon2"] = df1.loc[:, "lon2"].astype("float") df1.loc[:, "lat1"] = df1.loc[:, "lat2"].astype("float") df1.loc[:, "lat2"] = df1.loc[:, "lat2"].astype("float") </code></pre> <p>There you go.</p> <pre><code>df1.loc[:, "angle"] = df1.apply(lambda x: angle(x["lon1"], x["lat1"], x["lon2"], x["lat2"]), axis = 1) </code></pre> <p>As for performance concern, here are some tips for you.</p> <ol> <li>Profiling. </li> <li>Use <code>numba</code> for JIT compilation and automatic vectorization of your function.</li> </ol>
1
2016-10-18T03:06:04Z
[ "python", "pandas" ]
pandas Dataframe columns doing algorithm
40,098,680
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'A': ['a', 'a', 'a', 'a', 'a'], 'lon1': [128.0, 135.0, 125.0, 123.0, 136.0], 'lon2': [128.0, 135.0, 139.0, 142.0, 121.0], 'lat1': [38.0, 32.0, 38.0, 38.0, 38.0], 'lat2': [31.0, 32.0, 35.0, 38.0, 29.0], 'angle': [0, 0, 0, 0, 0] }) </code></pre> <p>I want to count the angle of each row by this function and save back to the angle column</p> <pre><code>def angle(lon1,lat1,lon2,lat2): dx = lon2 - lon1 dy = lat2 - lat1 direction = 0; if ((dx == 0) &amp; (dy == 0)): # same position return direction if (dx &gt; 0.0) : direction = 90-np.arctan2(dy,dx)*180/np.pi elif (dy &gt; 0.0 ) : direction = 180+(270-(np.arctan2(dy,dx)*180/np.pi)) else : direction = 360-(270+(np.arctan2(dy,dx)*180/np.pi)) if (direction &lt; 0) : direction += 360 return (direction.astype(int) % 360) </code></pre> <p>I tried </p> <pre><code>df.ix[df['A'].notnull(), 'angle'] =angle( df[df['A'].notnull()]['lon1'], df[df['A'].notnull()]['lat1'], df[df['A'].notnull()]['lon2'], df[df['A'].notnull()]['lat2']) </code></pre> <p>and I got an error</p> <blockquote> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>I tried <code>for index,row in df.iterrows():</code> the result of for loop is ok but it took terribly long long time(original data is about 10 million rows ) </p> <p>could anyone kindly give some efficient methods?</p>
0
2016-10-18T02:44:10Z
40,098,864
<p>I'm sure there's a more vectorized solution, but here is a solution using the row-wise version of the <code>apply</code> method, which only slightly alters your function:</p> <pre><code>def angle(row): dx = row.lon2 - row.lon1 dy = row.lat2 - row.lat1 direction = 0; if ((dx == 0) &amp; (dy == 0)): # same position return direction if (dx &gt; 0.0) : direction = 90-np.arctan2(dy,dx)*180/np.pi elif (dy &gt; 0.0 ) : direction = 180+(270-(np.arctan2(dy,dx)*180/np.pi)) else : direction = 360-(270+(np.arctan2(dy,dx)*180/np.pi)) if (direction &lt; 0) : direction += 360 return (direction.astype(int) % 360) df['angle'] = df.apply(angle, axis=1) </code></pre> <p>Output:</p> <pre><code> A angle lat1 lat2 lon1 lon2 0 a 180 38.0 31.0 128.0 128.0 1 a 0 32.0 32.0 135.0 135.0 2 a 102 38.0 35.0 125.0 139.0 3 a 90 38.0 38.0 123.0 142.0 4 a 239 38.0 29.0 136.0 121.0 </code></pre>
0
2016-10-18T03:06:37Z
[ "python", "pandas" ]
imgur_client.search_gallery doesn't yield many images
40,098,718
<p>I wonder how can I modify this code so that it will show more queries? Right now it only shows 59 queries that only one of them has more than 30 comments:</p> <pre><code> 9 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 10 11 search = imgur_client.gallery_search('cat', window='all') 12 print(len(search)) 13 14 print(type(search[0])) 15 print(dir(search[0])) 16 print(type(search)) 17 18 print(search[0].id) 19 print(random.choice(search).link) 20 21 for i in range(0, len(search)): 22 print(search[i].link) 23 if search[i].comment_count &gt; 10: 24 count = 0 25 for post in imgur_client.gallery_item_comments(search[i].id, sort='best'): 26 if count &lt;= 30: 27 print post.comment 28 count += 1 </code></pre> <p>I have:</p> <pre><code>mona@pascal:~/computer_vision/imgur$ python download.py /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning 59 &lt;class 'imgurpython.imgur.models.gallery_album.GalleryAlbum'&gt; ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'account_id', 'account_url', 'comment_count', 'cover', 'cover_height', 'cover_width', 'datetime', 'description', 'downs', 'favorite', 'id', 'images_count', 'in_gallery', 'is_ad', 'is_album', 'layout', 'link', 'nsfw', 'points', 'privacy', 'score', 'section', 'title', 'topic', 'topic_id', 'ups', 'views', 'vote'] &lt;type 'list'&gt; E7WWf http://imgur.com/a/zx507 http://imgur.com/a/E7WWf http://imgur.com/a/dakxH http://imgur.com/a/wfmk4 http://imgur.com/a/U7f2S http://imgur.com/a/fu7q6 http://imgur.com/a/wwIqU http://imgur.com/a/kTwtF http://imgur.com/a/QqbSl http://imgur.com/a/cxviy http://imgur.com/a/g0cXi http://i.imgur.com/9zg6EZd.gif http://imgur.com/a/vYZXX http://imgur.com/a/QFZqB http://imgur.com/a/5JV8O http://imgur.com/a/xuR32 http://i.imgur.com/9Ut5Nci.jpg http://imgur.com/a/KMmmK http://imgur.com/a/8K8Cf http://imgur.com/a/RHndJ http://imgur.com/a/3zvW1 http://imgur.com/a/tYWcR http://imgur.com/a/YBYcZ http://imgur.com/a/rb40b http://imgur.com/a/fpBKP http://imgur.com/a/hYmda http://i.imgur.com/88TELvj.gif http://imgur.com/a/aHEGE http://imgur.com/a/oODh0 http://i.imgur.com/lfEUPJR.jpg http://imgur.com/a/u0Cb4 http://imgur.com/a/EQjnP http://imgur.com/a/5KQLb http://i.imgur.com/laMSJU6.png http://imgur.com/a/zx507 http://imgur.com/a/ryf0H http://i.imgur.com/Z7s62fp.jpg http://imgur.com/a/zbaw1 http://imgur.com/a/7oZMM http://i.imgur.com/zWohUjv.gif http://imgur.com/a/7jk4t http://imgur.com/a/9hGyR http://imgur.com/a/Y0clC http://imgur.com/a/h7D2Z /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning vet, now. whats in the jar on the table? Image last seen 3.0 years before at https://imgur.com/gallery/phREVH7 Title similarity: ★★★★★ (5/5) Get her chip checked, please. She looks healthy enouh that she's probably a pet Definitely go to a vet. They served our country and love cats. make sure she's not a domesticated outdoorsy cat.I have a lot of kitties running around where I live, and they are owned. Might be somebodys You reposting piece of shit OP, go kill yourself Looks like she's got some eye smegma going on,if you really want to keep her,wouldn't her to get her checked out. Do you want cats? Cause that's how you get cats! I wanted to talk about their jar of weed and records in the back but it's a repost. You have been chosen! Enjoy your new furry overlord. Are you in Brisbane? For some reason I read, "I have a cow now" and was highly confused based from the picture. Nope, the cat has *you* now. You've been chosen. You've been adopted! Quit smokin catnip ffs That looks almost exactly like my cat. His name is Morty. http://imgur.com/a/jVsoK http://imgur.com/a/kWqPt http://imgur.com/a/ZEUBu http://imgur.com/a/gBPFO http://imgur.com/a/C0Js1 http://i.imgur.com/EA3pyJt.png http://imgur.com/a/WaM3t http://imgur.com/a/berUE http://imgur.com/a/xfiyU http://i.imgur.com/M4q7QnK.jpg http://imgur.com/a/wg0Re http://imgur.com/a/DIY8b http://i.imgur.com/mJcXmWe.jpg http://i.imgur.com/R0a9oI9h.gif http://imgur.com/a/2qWZ8 http://i.imgur.com/LwD4UAY.gif </code></pre>
0
2016-10-18T02:48:00Z
40,098,811
<p>You should use the <code>page=</code> parameter to gallery_search to get the next page of results and iterate over them that way.</p>
1
2016-10-18T02:59:40Z
[ "python", "api", "web-scraping", "imgur" ]
Python format() without {}
40,098,740
<p>I am working on python 3.6 64 bit.</p> <p>Here is my code:</p> <pre><code>days = "Mon Tue Wed Thu Fri Sat Sun" print("Here are the days",format(days)) </code></pre> <p>The output I got is </p> <p>Here are the days Mon Tue Wed Thu Fri Sat Sun</p> <p>I didn't add "{}" in my string. Also I used a comma "," instead of a dot "."</p> <p>My understanding was that format() will replace {} in string with its arguments.</p> <p>Question : How did format() worked without {} and . operator</p>
0
2016-10-18T02:50:04Z
40,098,772
<p>The print function prints the arguments one right after the other, with a space in between. The <code>format</code> call, finding no replacements, is doing nothing and returning the original string.</p> <p>Here are some examples that may help:</p> <pre><code>&gt;&gt;&gt; colors = "Red Blue" &gt;&gt;&gt; print("Here are the colors", format(colors)) Here are the colors Red Blue &gt;&gt;&gt; print("", format(colors)) Red Blue &gt;&gt;&gt; print(format("abc"), format("xyz")) abc xyz &gt;&gt;&gt; print("Here are the colors", colors) Here are the colors Red Blue </code></pre>
0
2016-10-18T02:54:17Z
[ "python", "format" ]
Python format() without {}
40,098,740
<p>I am working on python 3.6 64 bit.</p> <p>Here is my code:</p> <pre><code>days = "Mon Tue Wed Thu Fri Sat Sun" print("Here are the days",format(days)) </code></pre> <p>The output I got is </p> <p>Here are the days Mon Tue Wed Thu Fri Sat Sun</p> <p>I didn't add "{}" in my string. Also I used a comma "," instead of a dot "."</p> <p>My understanding was that format() will replace {} in string with its arguments.</p> <p>Question : How did format() worked without {} and . operator</p>
0
2016-10-18T02:50:04Z
40,098,785
<p>I think you're thinking what's happening is similar to:</p> <pre><code>print("Here are the days {}".format(days)) </code></pre> <p>However, what's actually happening is that you're passing in multiple arguments to print(). If you look at the <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow">docs</a> for print(), it takes a couple of parameters:</p> <pre><code>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) </code></pre> <p>The asterisk in front of objects indicates it can take multiple arguments. Right now you're passing in "Here are the days" as the first argument, and format(days) as the second, which results in:</p> <pre><code>Here are the days Mon Tue Wed Thu Fri Sat Sun </code></pre>
1
2016-10-18T02:56:11Z
[ "python", "format" ]
Python format() without {}
40,098,740
<p>I am working on python 3.6 64 bit.</p> <p>Here is my code:</p> <pre><code>days = "Mon Tue Wed Thu Fri Sat Sun" print("Here are the days",format(days)) </code></pre> <p>The output I got is </p> <p>Here are the days Mon Tue Wed Thu Fri Sat Sun</p> <p>I didn't add "{}" in my string. Also I used a comma "," instead of a dot "."</p> <p>My understanding was that format() will replace {} in string with its arguments.</p> <p>Question : How did format() worked without {} and . operator</p>
0
2016-10-18T02:50:04Z
40,099,310
<p>Some of the confusion here may be the difference between the <code>format()</code> <em>function</em> and the related <code>"string".format()</code> <em>method</em>. The function invokes the object's (first argument) <code>__format__()</code> method with a <em>format specification</em> (second argument). If the second argument is None, then it's just like <code>str()</code>. The <code>format()</code> method of <code>str</code> walks the string on which it is invoked, looking for <em>substitution brackets</em> which may, or may not contain format specifications to be applied similar to the <code>format()</code> function. An example:</p> <pre><code>&gt;&gt;&gt; # format() function which invokes float.__format__() &gt;&gt;&gt; format(0.324, "+.4%") '+32.4000%' &gt;&gt;&gt; &gt;&gt;&gt; # str format() method that invokes various object.__format__() methods &gt;&gt;&gt; # if a format specification is found in the substitution brackets: &gt;&gt;&gt; "{:+.4%} rise in {}".format(0.324, "temperature") '+32.4000% rise in temperature' &gt;&gt;&gt; </code></pre> <blockquote> <p>Question : How did format() worked without {} and . operator</p> </blockquote> <p>It worked because without the '.' operator, you mistakenly invoked the <code>format()</code> function which, with no second argument, simply return the string. The <code>format()</code> function doesn't use {} brackets. It's the <code>format()</code> method of str, invoked by the '.' operator, that uses {} brackets to make substitutions, some of which may require formatting.</p> <p>Perhaps it might have been less confusing if the str method had a different name like <code>"{} string {}".interpolate(x, y)</code> as formatting is only part of what it does.</p>
0
2016-10-18T04:04:11Z
[ "python", "format" ]
Why running a Python script as a service in Windows can not write data to text?
40,098,752
<p>I want to reproduce the same result as <a href="http://www.chrisumbel.com/article/windows_services_in_python" rel="nofollow">Windows Services in Python</a>:</p> <pre><code>import win32service import win32serviceutil import win32event class PySvc(win32serviceutil.ServiceFramework): # you can NET START/STOP the service by the following name _svc_name_ = "PySvc" # this text shows up as the service name in the Service # Control Manager (SCM) _svc_display_name_ = "Python Test Service" # this text shows up as the description in the SCM _svc_description_ = "This service writes stuff to a file" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self,args) # create an event to listen for stop requests on self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) # core logic of the service def SvcDoRun(self): import servicemanager print 'hello' f = open('test.dat', 'w+') rc = None # if the stop event hasn't been fired keep looping while rc != win32event.WAIT_OBJECT_0: f.write('TEST DATA\n') f.flush() # block for 5 seconds and listen for a stop event rc = win32event.WaitForSingleObject(self.hWaitStop, 5000) f.write('SHUTTING DOWN\n') f.close() # called when we're being shut down def SvcStop(self): # tell the SCM we're shutting down self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # fire the stop event win32event.SetEvent(self.hWaitStop) if __name__ == '__main__': win32serviceutil.HandleCommandLine(PySvc) </code></pre> <p>In the <code>cmd</code> administrator mode,I type these commands,it works good.And telling me <code>Python Test Service</code> start.</p> <blockquote> <p>python.exe .\PySvc.py install</p> <p>NET START PySvc</p> </blockquote> <p>But the file <code>test.dat</code> isn't been created.So how to make the program into <code>SvcDoRun</code> function? </p>
0
2016-10-18T02:51:25Z
40,114,875
<p>Converting Comment to Answer...</p> <p>Try using a full path for the test.dat file (C:\servicedata\test,dat). The path when you run in the interperter is different from when you run as a service.</p>
0
2016-10-18T17:50:03Z
[ "python", "windows" ]
Python code to return total count of no. of positions in which items are differing at same index
40,098,820
<p>A=[1,2,3,4,5,6,7,8,9] B=[1,2,3,7,4,6,5,8,9]</p> <p>I have to compare these two lists and return the count of no. of location in which items are differing using one line python code.</p> <p>For example: the output should be 4 for given arrays because at index (3,4,5,6) the items are differing.So, program should return 4.</p> <p>My way of doing this is comparing each and every location using for loop:</p> <pre><code>count=0 for i in range(0,len(A)): if(A[i]==B[i]): continue else: count+=1 print(count) </code></pre> <p>Please help me in writing one line python code for this.</p>
0
2016-10-18T03:01:14Z
40,098,992
<pre><code>count = sum(a != b for a, b in zip(A, B)) print(count) </code></pre> <p>or just <code>print sum(a != b for a, b in zip(A, B))</code></p> <p>you can check about <a href="https://bradmontgomery.net/blog/pythons-zip-map-and-lambda/" rel="nofollow">zip/lambda/map here</a>, those tools are very powerfull and important in python..</p> <p><a href="http://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list">Here</a> you can also check others kind of ways to use those tools.</p> <p>Have fun!!</p>
1
2016-10-18T03:24:36Z
[ "python", "arrays", "python-2.7", "python-3.x", "numpy" ]
Python code to return total count of no. of positions in which items are differing at same index
40,098,820
<p>A=[1,2,3,4,5,6,7,8,9] B=[1,2,3,7,4,6,5,8,9]</p> <p>I have to compare these two lists and return the count of no. of location in which items are differing using one line python code.</p> <p>For example: the output should be 4 for given arrays because at index (3,4,5,6) the items are differing.So, program should return 4.</p> <p>My way of doing this is comparing each and every location using for loop:</p> <pre><code>count=0 for i in range(0,len(A)): if(A[i]==B[i]): continue else: count+=1 print(count) </code></pre> <p>Please help me in writing one line python code for this.</p>
0
2016-10-18T03:01:14Z
40,114,857
<p>There are <a href="http://stackoverflow.com/questions/28663856/how-to-count-the-occurrence-of-certain-item-in-an-ndarray-in-python">many ways</a> to do this. If you're using numpy, you could just use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html" rel="nofollow"><code>np.count_nonzero</code></a>:</p> <pre><code>&gt;&gt;&gt; a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) &gt;&gt;&gt; b = np.array([1, 2, 3, 7, 4, 6, 5, 8, 9]) &gt;&gt;&gt; a != b array([False, False, False, True, True, False, True, False, False], dtype=bool) &gt;&gt;&gt; np.count_nonzero(a != b) 3 </code></pre> <p>Note that <code>a != b</code> returns an <em>array</em> containing true and false depending upon how the condition evaluates at each index.</p> <p>Here's a speed comparison:</p> <pre><code>&gt;&gt;&gt; %timeit np.count_nonzero(a != b) The slowest run took 40.59 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 752 ns per loop &gt;&gt;&gt; %timeit sum(i != j for i, j in zip(a, b)) The slowest run took 5.86 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 18.5 µs per loop </code></pre> <p>The caching obscures the timing, but <code>40.59 * 0.752 = 30.52µs</code>, while <code>5.86 * 18.5 = 108.41µs</code>, so numpy's slowest still seems significantly faster than pure python's slowest run.</p> <p>This is much clearer with larger arrays:</p> <pre><code>&gt;&gt;&gt; n = 10000 &gt;&gt;&gt; a = np.arange(n) &gt;&gt;&gt; b = np.arange(n) &gt;&gt;&gt; k = 50 &gt;&gt;&gt; ids = np.random.randint(0, n, k) &gt;&gt;&gt; a[ids] = 0 &gt;&gt;&gt; ids = np.random.randint(0, n, k) &gt;&gt;&gt; b[ids] = 0 &gt;&gt;&gt; %timeit np.count_nonzero(a != b) The slowest run took 20.50 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 11.5 µs per loop &gt;&gt;&gt; %timeit sum(i != j for i, j in zip(a, b)) 100 loops, best of 3: 15.6 ms per loop </code></pre> <p>The difference is much more stark, with numpy taking <em>at most</em> 235 <em>micro</em>-seconds, while pure python takes 15.6 <em>milli</em>-seconds on <em>average</em>!</p>
0
2016-10-18T17:48:49Z
[ "python", "arrays", "python-2.7", "python-3.x", "numpy" ]
How do I find the location of Python module sources while I can not import it?
40,098,880
<p>The answer in <a href="http://stackoverflow.com/questions/269795/how-do-i-find-the-location-of-python-module-sources">How do I find the location of Python module sources?</a> says just import it and print its <code>__file__</code>. But my question is that I cannot import a library <code>cv2</code> while it returns <code>ImportError: libcudart.so.7.5: cannot open shared object file: No such file or directory</code>, so I cannot get its <code>__file__</code> too. I want to find where does Python import this library so that I can check what is wrong with the library.</p>
0
2016-10-18T03:08:55Z
40,099,175
<p>Try:</p> <pre><code>import imp imp.find_module('cv2') </code></pre>
1
2016-10-18T03:47:06Z
[ "python", "module", "python-import" ]
How do I complete my OAuth Google Login?
40,098,935
<p>My application has React and Redux running on the client side and Flask running on the server side.</p> <p>I received a OAUTH token from Google on my client in the form of:</p> <pre><code> Object { El: "109087143026456349612", Zi: Object, w3: Object, googleId: "109087143026456349612", tokenObj: Object, tokenId: "eyJhbGciOiJSUzI1NiIsImtpZCI6IjUxNjE…", accessToken: "ya29.Ci- AAyPxYI7qVyKp2QTwadhiVtc9Qg…", profileObj: Object } </code></pre> <p>I sent this entire token object to my server via</p> <pre><code> axios.post(`${local_env_url}/gconnect`, {returnData}) </code></pre> <p>My Flask server has recognized with:</p> <pre><code>@app.route('/gconnect', methods=['POST']) def gconnect(): token = request.data </code></pre> <p>Where do i go from here? On the docs it says that I can verify the token by sending it to this link: '<a href="https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=%s" rel="nofollow">https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=%s</a>' %(tokenid)</p> <p>but it's not clear if I'm sending the entire token object or just the access token value.</p>
-1
2016-10-18T03:15:45Z
40,101,480
<p>Steps are like this </p> <ol> <li>Get google auth data after user successfully connects to your app.</li> <li>After a user successfully signs in, send the user's ID token to your server using HTTPS.</li> <li>Then, on the server, verify the integrity of the ID token and retrieve the user's ID from the sub claim of the ID token. </li> </ol> <p>On server side you just need to send <code>id_token</code> and nothing else.</p> <p>Now comes the verification of the integrity of the ID token passed to your blackened server which in your case is flask.</p> <p>From server side you need to make a http request to validate the ID token to this end point - </p> <pre><code>https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123 </code></pre> <p>If the token is properly signed and valid, you will get a HTTP 200 response, where the body contains the JSON-formatted ID token claims.</p> <p>You can get all the user info from the response received on server side.</p> <p>To send the request to validate id_token you can use any python library to make http request or you can use google client library for python -</p> <pre><code>from oauth2client import client, crypt # (Receive token by HTTPS POST) try: idinfo = client.verify_id_token(token, CLIENT_ID) # If multiple clients access the backend server: if idinfo['aud'] not in [ANDROID_CLIENT_ID, IOS_CLIENT_ID, WEB_CLIENT_ID]: raise crypt.AppIdentityError("Unrecognized client.") if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise crypt.AppIdentityError("Wrong issuer.") if idinfo['hd'] != APPS_DOMAIN_NAME: raise crypt.AppIdentityError("Wrong hosted domain.") except crypt.AppIdentityError: # Invalid token userid = idinfo['sub'] </code></pre> <p>More info <a href="https://developers.google.com/identity/sign-in/web/backend-auth#using-a-google-api-client-library" rel="nofollow">here</a> - regarding how to use google client library.</p>
0
2016-10-18T06:53:55Z
[ "python", "reactjs", "flask", "oauth" ]
Python Update Dictionary values to reference dataframes with the same name
40,098,963
<p>I have many dataframes with names such as 'ABC', 'XYZ'...</p> <p>I also have a dictionary with keys, where each key has a list of 200 values which are the names of the dataframes i.e. ['ABC','XYZ',...]</p> <p>I want to update this dictionary, so instead of containing the names of the dataframes, it contains the dataframes themselves as a nested dictionary.</p> <p>THis will enable me to iterate over a specific key of the main dictionary dictionary, and access each of its 200 dataframes by name</p> <p>i.e. dictionary[key1][ABC] would print out the ABC dataframe.</p> <p>Any ideas? :)</p>
2
2016-10-18T03:20:05Z
40,099,212
<p>What are the keys currently in this dictionary? / Where are your dataframes currently stored? You probably want something like this: </p> <pre><code>dfDict ={dfName: &lt;df&gt;} #assuming a bit here newDict = {} for key, value in oldDict.items(): newDict[key] = { dfName:dfDict[dfName] for dfName in value } </code></pre>
1
2016-10-18T03:52:48Z
[ "python", "pandas", "dictionary", "dataframe", "nested" ]
Python Update Dictionary values to reference dataframes with the same name
40,098,963
<p>I have many dataframes with names such as 'ABC', 'XYZ'...</p> <p>I also have a dictionary with keys, where each key has a list of 200 values which are the names of the dataframes i.e. ['ABC','XYZ',...]</p> <p>I want to update this dictionary, so instead of containing the names of the dataframes, it contains the dataframes themselves as a nested dictionary.</p> <p>THis will enable me to iterate over a specific key of the main dictionary dictionary, and access each of its 200 dataframes by name</p> <p>i.e. dictionary[key1][ABC] would print out the ABC dataframe.</p> <p>Any ideas? :)</p>
2
2016-10-18T03:20:05Z
40,099,215
<p>Easy enough, use <code>eval</code>:</p> <pre><code>u, v, w, x, y, z = 1, 2, 3, 4, 5, 6 frames = {} names = {'a' : ['u', 'v'], 'b' : ['w', 'x'], 'c' : ['y', 'z']} for key in names: frames[key] = dict(zip(names[key], [eval(name) for name in names[key]])) frames # Output: {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]} </code></pre>
2
2016-10-18T03:53:03Z
[ "python", "pandas", "dictionary", "dataframe", "nested" ]
Opening a pdf bytestring for reading
40,098,982
<p>I am working on a scrapy spider, trying to convert pdfs, using pdfminer (<a href="https://pypi.python.org/pypi/pdfminer2" rel="nofollow">https://pypi.python.org/pypi/pdfminer2</a>). I have no interest in saving the actual PDF to disk , and so I've been advised to look into the io.bytesIO subclass at <a href="https://docs.python.org/2/library/io.html#buffered-streams" rel="nofollow">https://docs.python.org/2/library/io.html#buffered-streams</a>. Based on <a href="http://stackoverflow.com/questions/39799009/creating-and-accessing-bytesio-object/39799090#39799090">Creating bytesIO object</a> , I have initialized the bytesIO class with the pdf body, but now I need to open the data and follow and example like the basic usage <a href="http://www.unixuser.org/~euske/python/pdfminer/programming.html" rel="nofollow">http://www.unixuser.org/~euske/python/pdfminer/programming.html</a> So far based on <a href="http://zevross.com/blog/2014/04/09/extracting-tabular-data-from-a-pdf-an-example-using-python-and-regular-expressions/" rel="nofollow">http://zevross.com/blog/2014/04/09/extracting-tabular-data-from-a-pdf-an-example-using-python-and-regular-expressions/</a> I have:</p> <pre><code> in_memory_pdf = BytesIO(bytes(response.body)) in_memory_pdf.seek(0) rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = file(in_memory_pdf, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos=set() for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): interpreter.process_page(page) fp.close() device.close() st = retstr.getvalue() retstr.close() print st </code></pre> <p>When I run this I get:</p> <pre><code>fp = file(in_memory_pdf, 'rb') TypeError: coercing to Unicode: need string or buffer, _io.BytesIO found </code></pre> <p>How can I open this pdf bytestring for processing?</p> <p>After the suggested change I'm getting:</p> <pre><code>2016-10-17 23:59:35 [root] DEBUG: exec: ET 2016-10-17 23:59:35 [root] DEBUG: nexttoken: (2819L, /'Q') 2016-10-17 23:59:35 [root] DEBUG: do_keyword: pos=2819L, token=/'Q', stack=[] 2016-10-17 23:59:35 [root] DEBUG: add_results: ((2819L, /'Q'),) 2016-10-17 23:59:35 [root] DEBUG: nextobject: (2819L, /'Q') 2016-10-17 23:59:35 [root] DEBUG: exec: Q Traceback (most recent call last): File "C:\\site-packages\twisted\internet\defer.py", line 588, in _runCallbacks current.result = callback(current.result, *args, **kw) File "C:\j1\spiders\j1_spider.py", line 235, in parse_pdf_to_html interpreter.process_page(page) File "C:\\site-packages\pdfminer\pdfinterp.py", line 835, in process_page self.device.end_page(page) File "C:\\site-packages\pdfminer\converter.py", line 53, in end_page self.receive_layout(self.cur_item) File "C:\\site-packages\pdfminer\converter.py", line 206, in receive_layout render(ltpage) File "C:\\site-packages\pdfminer\converter.py", line 196, in render render(child) File "C:\\site-packages\pdfminer\converter.py", line 196, in render render(child) File "C:\\site-packages\pdfminer\converter.py", line 196, in render render(child) File "C:\\site-packages\pdfminer\converter.py", line 198, in render self.write_text(item.get_text()) File "C:\\site-packages\pdfminer\converter.py", line 189, in write_text self.outfp.write(text) TypeError: unicode argument expected, got 'str' </code></pre>
0
2016-10-18T03:22:53Z
40,101,128
<p>There are two problems:</p> <ol> <li><code>in_memory_pdf</code> is already a file-like object for <code>str</code> (or <code>bytes</code> in Py3), can be directly used without opening. Thus changing <code>fp = file(in_memory_pdf, 'rb')</code> to <code>fp = in_memory_pdf</code> partially worked.</li> <li>The second parameter of <code>TextConverter</code> should also be a file-like object for <code>str</code> (or <code>bytes</code> in Py3). But <code>retstr</code> in the question is for <code>unicode</code> (or <code>str</code> in Py3). Therefore <code>retstr = StringIO()</code> should be changed to <code>retstr = BytesIO()</code>.</li> </ol>
1
2016-10-18T06:35:24Z
[ "python", "pdf" ]
How to parse this file using python?
40,098,984
<p>I have a file with contents like</p> <pre><code>[Input:1] Name=Feature1 Transform=Linear Slope=1 Intercept=0 [Input:4] Name=Feature2 Transform=Linear Slope=1 Intercept=0 [Input:2] Expression=( if ( &gt; Var 10000000) ( - Var 10000000) ( + Var 10000000)) Transform=Freeform [Input:3] Transform=FreeForm Expression=(if (&gt; Var2 1) Var2 0) Slope=1 Intercept=0 </code></pre> <p>I need to create a list of objects with each object containing fields given above. Thus [Input:1] will correspond to object 1, there will be 4 variables inside given as Name, Transform, Slope and Intercept. The value ( in string) of that fields will be "Feature1", "Linear", "1" and "0" respectively. Note that each object can have different fields. How do I do this in python?</p>
-1
2016-10-18T03:23:03Z
40,099,037
<p>I guess u can try config</p> <pre><code>import ConfigParser conf = ConfigParser.ConfigParser() conf.read("test.cfg") sections = conf.sections() print 'sections:', sections #sections: ['sec_b', 'sec_a'] options = conf.options("Input:1") </code></pre> <p>but I misunderstand that how to define Expression, is it just a string</p>
0
2016-10-18T03:30:41Z
[ "python", "parsing", "text" ]
How to parse this file using python?
40,098,984
<p>I have a file with contents like</p> <pre><code>[Input:1] Name=Feature1 Transform=Linear Slope=1 Intercept=0 [Input:4] Name=Feature2 Transform=Linear Slope=1 Intercept=0 [Input:2] Expression=( if ( &gt; Var 10000000) ( - Var 10000000) ( + Var 10000000)) Transform=Freeform [Input:3] Transform=FreeForm Expression=(if (&gt; Var2 1) Var2 0) Slope=1 Intercept=0 </code></pre> <p>I need to create a list of objects with each object containing fields given above. Thus [Input:1] will correspond to object 1, there will be 4 variables inside given as Name, Transform, Slope and Intercept. The value ( in string) of that fields will be "Feature1", "Linear", "1" and "0" respectively. Note that each object can have different fields. How do I do this in python?</p>
-1
2016-10-18T03:23:03Z
40,099,087
<p>You can generate a grammar analyzer which can parse this file by BNF. Use Boson to do this, Boson is a lightweight grammar analyzer generator.</p> <p><a href="https://github.com/ictxiangxin/boson" rel="nofollow">Boson Github</a></p>
0
2016-10-18T03:36:17Z
[ "python", "parsing", "text" ]
How to parse this file using python?
40,098,984
<p>I have a file with contents like</p> <pre><code>[Input:1] Name=Feature1 Transform=Linear Slope=1 Intercept=0 [Input:4] Name=Feature2 Transform=Linear Slope=1 Intercept=0 [Input:2] Expression=( if ( &gt; Var 10000000) ( - Var 10000000) ( + Var 10000000)) Transform=Freeform [Input:3] Transform=FreeForm Expression=(if (&gt; Var2 1) Var2 0) Slope=1 Intercept=0 </code></pre> <p>I need to create a list of objects with each object containing fields given above. Thus [Input:1] will correspond to object 1, there will be 4 variables inside given as Name, Transform, Slope and Intercept. The value ( in string) of that fields will be "Feature1", "Linear", "1" and "0" respectively. Note that each object can have different fields. How do I do this in python?</p>
-1
2016-10-18T03:23:03Z
40,100,770
<p>Try:</p> <pre><code>try: # Python 2 import ConfigParser as cfgp except: # Python 3 import configparser as cfgp class MyObject: def __getitem__(self, attr): return getattr(self, attr) conf = cfgp.ConfigParser() conf.optionxform = str conf.read('sample.cfg') objects = [] for section in conf.sections(): obj = MyObject() for field, value in conf.items(section): setattr(obj, field, value) objects.append(obj) </code></pre> <p>Then, you can get the field values by:</p> <pre><code>for obj in objects: print(obj.Transform) # or obj.Name, etc print(obj['Transform']) # or obj['Name'], etc </code></pre>
1
2016-10-18T06:09:58Z
[ "python", "parsing", "text" ]
Testing taskqueues locally on google app engine using dev_appserver.py
40,098,999
<p>My app engine app has 2 queues. A worker from the first queue initiates several workers in the second queue and wait for them to complete and consolidate.</p> <p>This works fine when I deploy it, but it <s>doesn't work</s> never spawns the tasks in the second queue when testing locally. It gets stuck while waiting for it to update (see code below). The reason seems to be that dev_appserver is single threaded and does not launch services in the background.</p> <p>This is really slowing down my development since I have to deploy to the cloud to test anything.</p> <p>Any ways around this?</p> <p>Edit: Adding the (sort of) pseudo code below. Again, this works perfectly fine in the cloud because I have a 10 minute time limit to complete the task and each <code>BigTask</code> takes not more than 30-40 seconds to complete.</p> <h3>Queue 1 Worker</h3> <pre><code>class BigTask(webapp2.RequestHandler): def do_stuff(self): #do something here small_task1 = taskqueue.add(...) small_task2 = taskqueue.add(...) small_task3 = taskqueue.add(...) small_task4 = taskqueue.add(...) # Create ndb entries for all small tasks while True: time.sleep(2) # Check if ndb entry updated for all small_tasks if status == 'Completed': #for all break add_results(...) # of all tasks here # Update ndb entry for big_task # done </code></pre> <h3>Queue 2 Worker</h3> <pre><code>class SmallTask(webapp2.RequestHandler): def do_stuff(self): # Do processing # Update ndb entry # done </code></pre>
1
2016-10-18T03:26:19Z
40,107,896
<p>Generally sleeping in GAE app code is not a good idea - wasting instance uptime, increasing request latency, risk of exceeding the request deadline etc.</p> <p>You can achieve the same functionality by enqueuing a delayed BigTask (using the <code>countdown</code> option) which would check the status for all smaller tasks, do the <code>add_results(...)</code> stuff if they completed or, if not, re-queue itself (again delayed) to re-check later on.</p> <p>As a side effect you could even use the same task queue for both kind of tasks (if that's inline with your app requirements, of course).</p>
2
2016-10-18T12:10:00Z
[ "python", "google-app-engine", "task-queue" ]
raise ImgurClientError('JSON decoding of response failed.') imgurpython.helpers.error.ImgurClientError: JSON decoding of response failed
40,099,046
<p>For the code below:</p> <pre><code> 12 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 13 for p in range(100, 500): 14 search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) 15 for i in range(0, len(search)): 16 #print(search[i].link) 17 #print(dir(search[i])) 18 print(search[i].type) 19 if search[i].comment_count &gt; 30 and search[i].type!='gif': 20 count = 0 21 image_file = urllib2.urlopen(search[i].link, timeout = 5) 22 image_file_name = 'images/'+ search[i].id+search[i].type 23 output_image = open(image_file_name, 'wb') 24 output_image.write(image_file.read()) 25 26 for post in imgur_client.gallery_item_comments(search[i].id, sort='best'): 27 if count &lt;= 30: 28 count += 1 29 </code></pre> <p>I get :</p> <pre><code>$ python download.py /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Traceback (most recent call last): File "download.py", line 14, in &lt;module&gt; search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 531, in gallery_search response = self.make_request('GET', 'gallery/search/%s/%s/%s' % (sort, window, page), data) File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 158, in make_request raise ImgurClientError('JSON decoding of response failed.') imgurpython.helpers.error.ImgurClientError: JSON decoding of response failed. </code></pre> <p>Can you please suggest fixes?</p>
0
2016-10-18T03:31:52Z
40,099,484
<p>Maybe not the best solution but this solved the problem:</p> <pre><code> 1 from imgurpython import ImgurClient 2 import inspect 3 import random 4 import urllib2 5 import requests 6 from imgurpython.helpers.error import ImgurClientError 15 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 16 17 for p in range(100, 500): 18 try: 19 search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) 20 for i in range(0, len(search)): 21 if search[i].comment_count &gt; 30 and not search[i].is_album: 22 print(search[i].type) 23 if 'jpg' in search[i].type : 24 count = 0 25 image_file = urllib2.urlopen(search[i].link, timeout = 5) 26 image_file_name = 'images/'+ search[i].id+'.'+search[i].type[6:] 27 output_image = open(image_file_name, 'wb') 28 output_image.write(image_file.read()) 29 for post in imgur_client.gallery_item_comments(search[i].id, sort='best'): 30 if count &lt;= 30: 31 count += 1 32 except ImgurClientError as e: 33 print(e) 34 continue </code></pre>
0
2016-10-18T04:24:32Z
[ "python", "json", "api", "exception", "imgur" ]
Installing bpython for Python 3
40,099,088
<p>I've been using bpython for Python 2 and now I want to use it for Python 3 as well.</p> <p>However I've run into problems. The bpython documentation reads:</p> <blockquote> <p>bpython supports Python 3. It's as simple as running setup.py with Python 3.</p> </blockquote> <p>When I run the setup script it creates a build folder, but I don't know what to do from there? I want to be able to type "bpython" in the Terminal and run the bpython interface for Python 3.</p> <p>I originally installed bpython with pip, that worked off the bat.</p>
1
2016-10-18T03:36:18Z
40,099,124
<p><a href="https://docs.python.org/3/install/#standard-build-and-install" rel="nofollow">Run <code>python3 setup.py install</code> command</a> (without <code>install</code> it only builds); You may need to prepend the command with <code>sudo</code>: <code>sudo python3 setup.py install</code>.</p> <p>BTW, you can also use <code>pip</code>: <code>pip3 install bpython</code> or <code>python3 -m pip install bpython</code></p>
1
2016-10-18T03:41:57Z
[ "python", "pip", "distutils", "bpython" ]
Python - convert list into dictionary in order to reduce complexity
40,099,239
<p>Let's say I have a big list:</p> <pre><code>word_list = [elt.strip() for elt in open("bible_words.txt", "r").readlines()] </code></pre> <p><code>//complexity O(n) --&gt; proporcional to list length "n"</code></p> <p>I have learned that <code>hash function</code> used for building up <code>dictionaries</code> allows <code>lookup</code> to be much faster, like so:</p> <pre><code>word_dict = dict((elt, 1) for elt in word_list) </code></pre> <p><code>// complexity O(l) ---&gt; constant.</code></p> <p>using <code>word_list</code>, is there a <strong>most efficient way</strong> which is recommended to reduce the complexity of my code?</p>
0
2016-10-18T03:56:43Z
40,099,692
<p>The code from the question does just one thing: fills all words from a file into a list. The complexity of that is O(n).</p> <p>Filling the same words into any other type of container will still have at least O(n) complexity, because it has to read all of the words from the file and it has to put all of the words into the container.</p> <h2>What is different with a <code>dict</code>?</h2> <p>Finding out whether something is in a <code>list</code> has O(n) complexity, because the algorithm has to go through the list item by item and check whether it is the sought item. The item can be found at position 0, which is fast, or it could be the last item (or not in the list at all), which makes it O(n).</p> <p>In <code>dict</code>, data is organized in <em>"buckets"</em>. When a key:value pair is saved to a <code>dict</code>, <code>hash</code> of the key is calculated and that number is used to identify the <em>bucket</em> into which data is stored. Later on, when the key is looked up, <code>hash(key)</code> is calculated again to identify the bucket and then only that bucket is searched. There is typically only one key:value pair per bucked, so the search can be done in O(1).</p> <p>For more detils, see <a href="https://wiki.python.org/moin/DictionaryKeys" rel="nofollow">the article about DictionaryKeys on python.org</a>.</p> <h2>How about a <code>set</code>?</h2> <p>A set is something like a dictionary with only keys and no values. The question contains this code:</p> <pre><code>word_dict = dict((elt, 1) for elt in word_list) </code></pre> <p>That is obviously a dictionary which does not need values, so a set would be more appropriate.</p> <p>BTW, there is no need to create a <code>word_list</code> which is a list first and convert it to <code>set</code> or <code>dict</code>. The first step can be skipped:</p> <pre><code>set_of_words = {elt.strip() for elt in open("bible_words.txt", "r").readlines()} </code></pre> <h2>Are there any drawbacks?</h2> <p>Always ;)</p> <ul> <li><p>A set does not have duplicates. So counting how many times a word is in the set will never return 2. If that is needed, don't use a set.</p></li> <li><p>A set is not ordered. There is no way to check which was the first word in the set. If that is needed, don't use a set.</p></li> <li><p>Objects saved to sets have to be hashable, which kind-of implies that they are immutable. If it was possible to modify the object, then its <em>hash</em> would change, so it would be in the wrong bucket and searching for it would fail. Anyway, <code>str</code>, <code>int</code>, <code>float</code>, and <code>tuple</code> objects are immutable, so at least those can go into sets.</p></li> <li><p><strong>Writing</strong> to a set is probably going to be a bit slower than writing to a list. Still O(n), but a slower O(n), because it has to calculate hashes and organize into buckets, whereas a list just dumps one item after another. See timings below.</p></li> <li><p><strong>Reading everything</strong> from a set is also going to be a bit slower than reading <strong>everything</strong> from a list.</p></li> </ul> <p>All of these apply to <code>dict</code> as well as to <code>set</code>.</p> <h2>Some examples with timings</h2> <p>Writing to list vs. set:</p> <pre><code>&gt;&gt;&gt; timeit.timeit('[n for n in range(1000000)]', number=10) 0.7802875302271843 &gt;&gt;&gt; timeit.timeit('{n for n in range(1000000)}', number=10) 1.025623542189976 </code></pre> <p>Reading from list vs. set:</p> <pre><code>&gt;&gt;&gt; timeit.timeit('989234 in values', setup='values=[n for n in range(1000000)]', number=10) 0.19846207875508526 &gt;&gt;&gt; timeit.timeit('989234 in values', setup='values={n for n in range(1000000)}', number=10) 3.5699193290383846e-06 </code></pre> <p>So, writing to a set seems to be about 30% slower, but finding an item in the set is thousands of times faster when there are thousands of items.</p>
5
2016-10-18T04:45:38Z
[ "python", "list", "dictionary", "asymptotic-complexity" ]
Why can I make a numpy array that's (apparently) bigger than my computer's memory?
40,099,264
<p>When I run code below:</p> <pre><code>import scipy.sparse x = scipy.sparse.random(100000, 100000, 1e-4) y = x.toarray() print(y.nbytes) </code></pre> <p>I get an output of 80000000000 bytes = 80 GB. And yet I am using a Macbook Air with only 4 GB of RAM. Can someone explain how I am (apparently) creating a NumPy array larger than my memory size? Is <code>y</code> somehow a view of <code>x</code>, rather than a copy? I didn't find anything about this in the <code>scipy.sparse</code> documentation. Unsurprisingly if I do something like <code>y.copy()</code> I crash Python... I can't expect to do something to an array of size 10^10. Thanks!</p> <p>Versions: Python 3.5.2 via Anaconda 4.1.1, SciPy 0.17.1, NumPy 1.11.1.</p>
0
2016-10-18T03:59:40Z
40,099,378
<p>This is because numpy doesn't actually allocate all that space. Most likely sparse arrays and matrices are represented with <a href="http://btechsmartclass.com/DS/U1_T14.html" rel="nofollow">triplets, linked nodes</a> or some other means of ignoring all the empty space between. The bytes are calculated based on the assigned dimensions of the matrix/array, not the actual data in memory.</p>
0
2016-10-18T04:12:57Z
[ "python", "numpy", "memory", "scipy", "sparse-matrix" ]