title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
separate certain characters when matched from either direction regex python
38,011,333
<p>I have something like this:</p> <pre><code>text = "hey;)there" </code></pre> <p>Need this:</p> <pre><code>text = "hey ;) there" </code></pre> <p>I am doing 2 passes:</p> <pre><code>op_1 = re.sub(r'([a-zA-Z])([:;()])', r'\1 \2', text) final_result = re.sub(r'([:;()])([a-zA-Z])', r'\1 \2', op_1) </code></pre> <p...
1
2016-06-24T10:34:56Z
38,011,410
<p>You can use lookaheads and lookbehinds with alternation</p> <pre><code>&gt;&gt;&gt; re.sub('(?&lt;=[a-zA-Z])(?=[:;()])|(?&lt;=[:;()])(?=[a-zA-Z])', ' ', text) 'hey ;) there' </code></pre> <p><em>Regex Breakdown</em></p> <pre><code>(?&lt;=[a-zA-Z]) #Lookbehind to match an alphabet (?=[:;()]) #Lookahead to match th...
1
2016-06-24T10:38:49Z
[ "python", "regex" ]
Unable to display data using matplotlib
38,011,334
<p>This is my first attempt to plot using matplotlib. I am trying to plot a netCDF file data of geopotential height using matplotlib and I get a blank image. There are no coastlines or anything. Just a blank screen. My data ranges from 5 N to 40 N and from 65 E to 100 E. </p> <p>I printed out the values of lat, lon an...
1
2016-06-24T10:34:57Z
38,012,337
<ol> <li><p>You may write just like <code>lons = nc_fid.variables['lon']</code>. </p></li> <li><p>Check your lat-lon values they have to cover your region of from 5 N to 40 N and from 65 E to 100 E.</p></li> <li><p><code>drawstates()</code> does not work for your region this command draw states boundaries for US.</p><...
1
2016-06-24T11:27:58Z
[ "python", "python-3.x", "matplotlib", "plot", "netcdf" ]
PyQt4 QTextBrowser.append Does'nt show any output
38,011,365
<p>i just started to learn PyQt and GUI programing and i copied this code exactly from the book "Rapid GUI Programming with Python and Qt:The Definitive Guide to PyQt Programming" and it supposed to show a calculator that calculates an expression. when i run the application main window shows up but does not do anything...
0
2016-06-24T10:36:33Z
38,011,533
<p>You have a typo in your signal name it should be</p> <pre><code>self.connect(self.lineedit, SIGNAL("returnPressed()"), </code></pre> <p>not</p> <p>self.connect(self.lineedit, SIGNAL("ret<strong>ru</strong>nPressed()"),</p> <p>so apparently you didn't copy it well, also it seems that book was written in python2 s...
0
2016-06-24T10:46:02Z
[ "python", "qt", "pyqt", "pyqt4" ]
Python format a string with a double inside quote with a dict
38,011,523
<p>Why formatting with a dict when there is a double quote in the string fails?</p> <pre><code>'%(x)"%(y)' % {'x': 1, 'y':2} Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unsupported format character '"' (0x22) at index 4 </code></pre> <p>It works with :</p> <pre...
-1
2016-06-24T10:45:20Z
38,011,562
<p>You are forgetting the conversion type code:</p> <pre><code>&gt;&gt;&gt; '%(x)s"%(y)s' % {'x': 1, 'y':2} '1"2' </code></pre> <p>Note the <code>s</code> strings. The syntax is <code>%(key)conversiontype</code>. Without a character signalling the conversion type, the parser picks the next character and that's <code>...
3
2016-06-24T10:47:03Z
[ "python", "string", "string-formatting" ]
Python format a string with a double inside quote with a dict
38,011,523
<p>Why formatting with a dict when there is a double quote in the string fails?</p> <pre><code>'%(x)"%(y)' % {'x': 1, 'y':2} Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: unsupported format character '"' (0x22) at index 4 </code></pre> <p>It works with :</p> <pre...
-1
2016-06-24T10:45:20Z
38,011,568
<p>Just as you use <code>%s</code>, you should use <code>%(x)s</code>. Just as <code>%"</code> is wrong, <code>%(x)"</code> is wrong. You just need to add that little <code>s</code>:</p> <pre><code>'%(x)s"%(y)s' % {'x': 1, 'y':2} </code></pre> <p>That letter is required for the same reason it is required in normal ...
0
2016-06-24T10:47:20Z
[ "python", "string", "string-formatting" ]
Read data from a serial device using Python and save it to PostgreSQL using a Raspberry Pi
38,011,713
<p>Im trying read data from a smartmeter that has FTDI chip. Wrote a simple Python serial program to pass the commands to meter and the meter replies back. the data from meter is then converted to float and stored in dictionary.</p> <p>now i want to store the dictionary to DB, <strong>here is the code to put data in t...
0
2016-06-24T10:54:29Z
38,011,865
<p>Error says: <em>Some of fields you try to push into database are string fields but you push integer values.</em></p> <p>Make sure that your data values matches your database table fields.</p>
0
2016-06-24T11:02:06Z
[ "python", "postgresql", "raspberry-pi", "psycopg2", "ftdi" ]
Read data from a serial device using Python and save it to PostgreSQL using a Raspberry Pi
38,011,713
<p>Im trying read data from a smartmeter that has FTDI chip. Wrote a simple Python serial program to pass the commands to meter and the meter replies back. the data from meter is then converted to float and stored in dictionary.</p> <p>now i want to store the dictionary to DB, <strong>here is the code to put data in t...
0
2016-06-24T10:54:29Z
38,013,096
<p>You have extra closing parenthesis and missing commas:</p> <pre><code>cur.executemany (""" INSERT INTO metertable( time,meter,temperature,freq,penergy,qenergy,senergy,cospi,irms,vrms,ppower,qpower,spower ) VALUES ( %(time)s, %(meter)s, %(temperature)s, %(freq)s, %(penergy)s, %(qenergy)s, %(s...
0
2016-06-24T12:07:32Z
[ "python", "postgresql", "raspberry-pi", "psycopg2", "ftdi" ]
Read data from a serial device using Python and save it to PostgreSQL using a Raspberry Pi
38,011,713
<p>Im trying read data from a smartmeter that has FTDI chip. Wrote a simple Python serial program to pass the commands to meter and the meter replies back. the data from meter is then converted to float and stored in dictionary.</p> <p>now i want to store the dictionary to DB, <strong>here is the code to put data in t...
0
2016-06-24T10:54:29Z
38,097,270
<p>Thanks for the help . The error was with the executemany. i used type(variable) to get the variable types and changed in those table I changed that to cur.execute. But when I run the code. I see no data saving in my database. <strong>here is the code</strong></p> <pre><code>import serial import psycopg2 port=ser...
0
2016-06-29T10:43:25Z
[ "python", "postgresql", "raspberry-pi", "psycopg2", "ftdi" ]
How to create .txt file with variables when pybot fails
38,011,838
<p><a href="http://i.stack.imgur.com/JOXPy.png" rel="nofollow"><img src="http://i.stack.imgur.com/JOXPy.png" alt="No Description Provided"></a> I have scenario where text file i need to create when pybot fails. When test case fails it should trigger a text file which should be pickup by jenkins downstream job and upda...
0
2016-06-24T11:00:51Z
38,013,998
<p>There is an option for "Trigger even if the build fails" when you're creating the jenkins job.</p> <p><img src="http://laurent.bristiel.com/wp-content/uploads/2014/09/trigger_build.png" alt="Trigger build"></p> <p>Read this blog post for the full context: <a href="http://laurent.bristiel.com/create-jenkins-job-for...
0
2016-06-24T12:56:37Z
[ "python", "jenkins", "robotframework" ]
How to create .txt file with variables when pybot fails
38,011,838
<p><a href="http://i.stack.imgur.com/JOXPy.png" rel="nofollow"><img src="http://i.stack.imgur.com/JOXPy.png" alt="No Description Provided"></a> I have scenario where text file i need to create when pybot fails. When test case fails it should trigger a text file which should be pickup by jenkins downstream job and upda...
0
2016-06-24T11:00:51Z
38,055,778
<p>The simplest solution is to create a <a href="http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#suite-setup-and-teardown" rel="nofollow">suite teardown</a> keyword that writes to the file. For example:</p> <pre><code>*** Settings *** Library OperatingSystem Suite Teardown Sav...
0
2016-06-27T13:52:32Z
[ "python", "jenkins", "robotframework" ]
Assigning set value to dictionary
38,011,855
<p>I have list <code>company_list_present</code> with duplicate values whihc looks like <code>[u'SOUTH ASIAN ENTERPRISES LTD', u'SPICEJET LTD', u'SPICEJET LTD']</code></p> <p>I have assigned this list to dictionary</p> <pre><code>record['company_present'] = set(company_list_present) </code></pre> <p>When I return it...
-2
2016-06-24T11:01:37Z
38,011,972
<p>You just want to return you set to a list ? then</p> <pre><code>record['company_present'] = list(set(company_list_present)) </code></pre>
3
2016-06-24T11:07:35Z
[ "python", "list", "dictionary", "set" ]
Getting apihelper module from Dive into Python
38,011,915
<p>I have a problem with chapter 4 of this book. I run python shell (IDLE, python 2.7) and try to import apihelper module, but I keep getting traceback saying</p> <pre><code>No module named apihelper </code></pre> <p>I downloaded the code from Pilgrim's site, but it still doesn't work. What do I miss?</p>
0
2016-06-24T11:04:26Z
38,012,010
<p>That's because your Python interpreter doesn't know where did you download <code>apihelper</code> module, and it cannot import it.</p> <p>More about where does <code>import</code> look for packages you can <strong><a href="http://www.diveintopython.net/getting_to_know_python/everything_is_an_object.html#d0e4550" re...
1
2016-06-24T11:10:05Z
[ "python" ]
Django access object attribute in choice form
38,011,917
<p>I have a choice form, which allows user to choose employees with specific range assigned to them.</p> <pre><code>class ReservationBookingForm(forms.Form): employee = forms.ModelChoiceField( queryset = Employee.objects.none(), #widget = forms.RadioSelect, empty_label = None, requ...
2
2016-06-24T11:04:28Z
38,012,196
<p>In the end of <a href="https://docs.djangoproject.com/en/1.9/ref/forms/fields/#modelchoicefield" rel="nofollow">ModelChoiceField</a> section:</p> <blockquote> <p>The <code>__str__</code> (<code>__unicode__</code> on Python 2) method of the model will be called to generate string representations of the objects for...
2
2016-06-24T11:20:17Z
[ "python", "django", "choicefield" ]
Python StatsModels Time Series Decomposition Duplicate Plot
38,011,931
<p>I am using a mixture of <a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a> and <a href="http://statsmodels.sourceforge.net/" rel="nofollow">StatsModels</a> to plot a time series decomposition. I followed <a href="http://stackoverflow.com/questions/20672236/time-series-decomposition-function-in-python/2828...
0
2016-06-24T11:05:11Z
38,013,407
<p>Assign the result of <code>res.plot()</code> to something, e.g. <code>fig = res.plot()</code>. The result of that method is a <code>matplotlib.figure</code>. The duplicate is from it's <code>_repr_html_</code>, which the notebook renders since it's the last item in the cell. You can try it yourself with</p> <pre><c...
2
2016-06-24T12:24:41Z
[ "python", "pandas", "matplotlib", "dataframe" ]
Replacing column of inf values with 0
38,012,050
<p>I am new to numpy but i cannot seem to get this piece of code to work.</p> <pre><code>item3.apply(lambda x : (x[np.isneginf(x)] = 0)) </code></pre> <p>item3 is a vector of numpy arrays with 300 dimensions in each array.</p> <p>The error thrown is invalid syntax. How do i get to achieve this function.</p> <p>Howe...
1
2016-06-24T11:12:14Z
38,013,205
<p>You could make something like that :</p> <pre><code>import numpy as np from numpy import inf x = np.array([inf, inf, 0]) # Create array with inf values print x # Show x array x[x == inf] = 0 # Replace inf by 0 print x # Show the result </code></pre> <p><a href="http://i.stack.imgur.com/YbshY.png" rel="nofollow...
0
2016-06-24T12:13:04Z
[ "python", "numpy" ]
How can I append new data to existing xml with python
38,012,278
<p>Hello Here is my existing xml file </p> <pre><code>&lt;domain type='kvm'&gt; &lt;name&gt;mydomain&lt;/name&gt; &lt;features&gt; &lt;acpi/&gt; &lt;apic/&gt; &lt;pae/&gt; &lt;/features&gt; &lt;devices&gt; &lt;disk type='block' device='disk'&gt; &lt;dri...
-1
2016-06-24T11:24:53Z
38,013,241
<p>You can use <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a> to parse and update XML.</p> <p>Here is a code to do that.</p> <pre><code>import xml.etree.ElementTree as ET def get_new_element(): #create element and set attributes disk = ET.Element('disk')...
0
2016-06-24T12:15:09Z
[ "python", "xml" ]
How to feed string a program in python
38,012,371
<p>I have a code that run with this command</p> <pre><code>echo "my string" | my_program.sh </code></pre> <p>and I was wondering what's the best way to do this inside a python script.</p> <p>What I have for now is this</p> <pre><code>import os my_string = "my string" os.system('echo %s | my_program.sh' % my_string)...
1
2016-06-24T11:29:15Z
38,013,259
<p>Have you looked into argparse?</p> <pre><code>import argparse parser = argparse.ArgumentParser(description='your description') parser.add_argument('-entry', dest="entry") args = parser.parse_args() print (args.entry) </code></pre> <p>You can then call this with python yourfile.py -entry="this is the entry"</p> <p...
0
2016-06-24T12:16:20Z
[ "python" ]
How to execute cmd.exe with arguments in Python
38,012,431
<p>I was trying to run <code>cmd.exe</code> with argument <code>ls</code>.</p> <p>I used the below code</p> <pre><code>import subprocess subprocess.call(['C:\Windows\System32\cmd.exe', 'ls']) </code></pre> <p>After executing this <code>cmd.exe</code> is opening but not taking <code>ls</code> as input</p>
0
2016-06-24T11:32:54Z
38,012,574
<p>I think , it doesn't work with windows , if you want to use linux syntax in windows you have to use cygwin environment. or change command "ls" to "dir" ("dir /w") </p>
0
2016-06-24T11:39:18Z
[ "python", "python-2.7" ]
How to execute cmd.exe with arguments in Python
38,012,431
<p>I was trying to run <code>cmd.exe</code> with argument <code>ls</code>.</p> <p>I used the below code</p> <pre><code>import subprocess subprocess.call(['C:\Windows\System32\cmd.exe', 'ls']) </code></pre> <p>After executing this <code>cmd.exe</code> is opening but not taking <code>ls</code> as input</p>
0
2016-06-24T11:32:54Z
38,012,825
<p>There are two mistake in your script</p> <ol> <li><code>ls</code> not supported in windows use <code>dir</code> instead</li> <li><code>/C</code> parameter needed to run a command</li> </ol> <p>Modified script is</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.call(['C:\\windows\\system32\\cm...
1
2016-06-24T11:53:11Z
[ "python", "python-2.7" ]
How to execute cmd.exe with arguments in Python
38,012,431
<p>I was trying to run <code>cmd.exe</code> with argument <code>ls</code>.</p> <p>I used the below code</p> <pre><code>import subprocess subprocess.call(['C:\Windows\System32\cmd.exe', 'ls']) </code></pre> <p>After executing this <code>cmd.exe</code> is opening but not taking <code>ls</code> as input</p>
0
2016-06-24T11:32:54Z
38,013,012
<p>If you add argument shell=True, python will use default shell which is available. In this case, python will use Windows cmd. In other word, below code should work: </p> <pre><code>&gt;&gt;&gt; subprocess.call('dir', shell=True) </code></pre>
0
2016-06-24T12:03:31Z
[ "python", "python-2.7" ]
Python2.7: ssh.exec_command not executing any command
38,012,503
<p>I'm creating an <code>SSH Channel</code> to a remote host using <code>paramiko</code>. However, when I try to execute any command using the <code>ssh_object.exec_command</code>, the command doesn't seem to get executed.</p> <p>This function creates my <code>ssh</code> handler:</p> <pre><code>def ssh_connect(ip,us...
2
2016-06-24T11:36:02Z
38,789,910
<p>I encountered with the same problem on CentOS 7 servers using paramiko 2.0.2. The example from the paramiko github homepage didn't work for me at first: <a href="https://github.com/paramiko/paramiko#demo" rel="nofollow">https://github.com/paramiko/paramiko#demo</a></p> <pre><code>import paramiko client = paramiko.S...
1
2016-08-05T13:00:44Z
[ "python", "python-2.7", "ssh", "paramiko" ]
Evaluating tf.py_func in session.run() returns "Invalid type list"
38,012,743
<p>My data is arranged in structure:</p> <pre><code>data/ good/ bad/ </code></pre> <p>with each subfolder containing jpg files. I'm trying to create an input pipeline that would accept <code>basepath</code> as input and construct an <code>image_op</code> and <code>label_op</code>. Evaluating these would give me a...
0
2016-06-24T11:48:46Z
38,013,183
<p><code>tf.py_func</code> returns a <strong>list</strong> of Tensors.</p> <p>You should just get <code>self.label = self.label[0]</code>:</p> <pre><code> filename_queue = tf.train.string_input_producer(filenames, shuffle=True) reader = tf.IdentityReader() self.key, self.value = reader.read(filename_queue)...
1
2016-06-24T12:12:06Z
[ "python", "tensorflow" ]
How add empty sheet to `excel` file that has already created using pandas
38,012,751
<p>I have data and I add that to excel </p> <pre><code>df.groupby('id').apply(lambda g: g.to_excel(g.name + '.xlsx', u'Смартфоны кратко')) </code></pre> <p>Next I add <code>sheet</code> with data to those files</p> <pre><code>df_upd.groupby('id').apply(lambda x: add_xlsx_sheet(x, u'Смартфоны ...
1
2016-06-24T11:49:09Z
38,013,584
<p>You can use <code>workbook.add_worksheet()</code>:</p> <pre><code>def add_xlsx_sheet(df, sheet_name=u'Смартфоны кратко', index=True, digits=2, path=None): book = load_workbook(path) writer = pd.ExcelWriter(path, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws)...
1
2016-06-24T12:34:01Z
[ "python", "excel", "pandas" ]
How to call decorated functions with XML RPC in Python?
38,012,752
<p>I have a XML RPC server against which I need to register some functions which are decorated. Every time I call those registered functions from client, I get below error:</p> <p>xmlrpclib.Fault: :method "test" is not supported'></p> <p>Below is the code:</p> <p>Server Code:</p> <pre><code>from SimpleXMLRPCServer ...
0
2016-06-24T11:49:10Z
38,013,574
<p>Just add a name for function on register. <code>server.register_function(test, "test")</code> works good. </p> <p>But you also need fix decorator itself: <code>AttributeError: "'tuple' object has no attribute 'pop'"</code></p>
0
2016-06-24T12:33:36Z
[ "python", "xml-rpc", "xmlrpclib" ]
wx python 3.0.2 classic SetFocus blows
38,012,813
<p>I had a Progress class that was working fine in 2.8.12.1 unicode:</p> <pre><code>class Progress(bolt.Progress): """Progress as progress dialog.""" def __init__(self,title=_(u'Progress'),message=u' '*60,parent=None, style=wx.PD_APP_MODAL|wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_SMOOTH, ...
0
2016-06-24T11:52:29Z
38,017,173
<p>On Windows the <code>ProgressDialog</code> is now a stock common control (like <code>MessageDialog</code>, <code>FileDialog</code>, etc.) instead of a generic dialog implemented in wx like it used to be. So it is not a real native window any longer but just a wrapper around a platform API. So this means that it has...
2
2016-06-24T15:39:26Z
[ "python", "python-2.7", "wxpython" ]
override __getattr__ for methods and not variables
38,012,851
<p>i want the next code to work</p> <pre><code>class A(object): def __getattr__(self, item): print item return self.item def x(self): print 4 a = A() a.x() </code></pre> <p>and the output will ber</p> <pre><code>x 4 </code></pre> <p>i know its not working becuase x is like a static v...
0
2016-06-24T11:54:22Z
38,013,106
<p>There are a couple of obvious problems with your code:</p> <pre><code>class A(object): def __getattr__(self, item): # 1 print item return self.item # 2 def x(self): # 1 again print 4 </code></pre> <ol> <li><code>__getattr__</code> will only be invoked if <code>item</code> cann...
4
2016-06-24T12:08:17Z
[ "python" ]
Storing 100Mb files and efficient cross-join operation in MongoDB or other DB
38,012,904
<p>Part of a project I am involved in consists of developing a scientific application for internal usage, working with large collection of files (about 20000) each of which is ~100Mb in size. Files are accompanied with meta information, used to select subsets of the whole set. </p> <p><em>Update</em> <em>after</em> <e...
0
2016-06-24T11:57:15Z
38,013,999
<p>In this case you could go for <code>sharded gridfs</code> as a part of mongo <a href="https://docs.mongodb.com/manual/tutorial/shard-gridfs-data/" rel="nofollow">more here</a></p> <p>That will allow for faster file retrieval process and still have metadata together with file record.</p> <p>other way to speed up w...
1
2016-06-24T12:56:46Z
[ "python", "mongodb", "nosql", "bigdata" ]
Increase extent of vector layer with OGR or GDAL?
38,012,977
<p>When using the OGR library or GDAL library with Python script, is it possible to increase the extent of a vector layer without actually adding new data points? In my specific case, I would like to increase the extent of vector layers associated with gpx files so that when I convert them to rasters they all have the...
0
2016-06-24T12:01:35Z
38,065,698
<p>I was unable to find a method to change the extent of the vector layer. However, I was able to write a python Function that uses gdal.RasterizeLayer() to produce a raster with an extent much larger than the original vector layer. The code for this function is:</p> <pre><code>import os import gdal import ogr ...
0
2016-06-28T01:30:43Z
[ "python", "geospatial", "gdal", "ogr", "extent" ]
Python Raw_Input in specific range
38,012,982
<p>I need to allow the user to input only numbers from 1111 to 9999 as raw_input in python. How do I create a constraint for this condition? Thanks</p>
-1
2016-06-24T12:01:51Z
38,013,019
<p>Get the input then check if the input is valid to your constraint (e.g. via an <code>if</code> condition). If it is not valid repeat the input (probably with notifiyng the user what was wrong with the input before) (e.g. with a <code>while</code> loop).</p>
2
2016-06-24T12:03:50Z
[ "python" ]
Python Raw_Input in specific range
38,012,982
<p>I need to allow the user to input only numbers from 1111 to 9999 as raw_input in python. How do I create a constraint for this condition? Thanks</p>
-1
2016-06-24T12:01:51Z
38,013,025
<p>You cannot force the user to input any specific thing using <code>raw_input()</code>. You'll have to validate the user input and preferably use a while loop until user enters correctly. </p> <p>This will work (assuming the user is not stupid to input non-digits).</p> <pre><code>i = int(raw_input('Please, enter a n...
0
2016-06-24T12:04:01Z
[ "python" ]
Python Raw_Input in specific range
38,012,982
<p>I need to allow the user to input only numbers from 1111 to 9999 as raw_input in python. How do I create a constraint for this condition? Thanks</p>
-1
2016-06-24T12:01:51Z
38,013,173
<p>Use a while loop until the user inputs a valid number. Check for ValueError to eliminate invalid input.</p> <pre><code>user_input = -1 _continue = True while _continue: try: user_input = int(raw_input("Value: ")) if 1111 &lt;= user_input &lt;= 9999: _continue = False except Valu...
0
2016-06-24T12:11:34Z
[ "python" ]
Python Raw_Input in specific range
38,012,982
<p>I need to allow the user to input only numbers from 1111 to 9999 as raw_input in python. How do I create a constraint for this condition? Thanks</p>
-1
2016-06-24T12:01:51Z
38,013,370
<pre><code>is_input_valid = False while is_input_valid == False: inp = int(raw_input("Input your number: ")) if inp &gt;= 1111 and inp &lt;= 9999: is_input_valid = True else: print "Please input only numbers from 1111 to 9999" print "Thanks, your input is valid" </code></pre>
0
2016-06-24T12:21:43Z
[ "python" ]
Install python dependencies not working
38,013,224
<p>I recently formatted my hard drive and got rid of Windows and went to Linux. I had a program that used to work fine before the reformat but isn't working fine now.</p> <p>I believe it was written for 3.4 and not 2.7 since I used import tkinter and not import Tkinter. In either case the program won't run now that ...
2
2016-06-24T12:14:26Z
38,013,274
<p>I think you have the librairies installed for Python 2... Did you use <code>pip</code> to install the librairies ?</p> <p>Try :</p> <pre><code>pip3 install numpy </code></pre> <p>And same for your other librairies.</p>
3
2016-06-24T12:17:15Z
[ "python", "numpy" ]
Install python dependencies not working
38,013,224
<p>I recently formatted my hard drive and got rid of Windows and went to Linux. I had a program that used to work fine before the reformat but isn't working fine now.</p> <p>I believe it was written for 3.4 and not 2.7 since I used import tkinter and not import Tkinter. In either case the program won't run now that ...
2
2016-06-24T12:14:26Z
38,013,321
<p>If you use Ubuntu then you have 2 versions of python executables - <code>python</code> and <code>python3</code>. So I think you need to install dependencies for python3 version by <code>sudo pip3 install numpy</code> or <code>sudo apt-get install python3-numpy</code> if it exists in repos.</p>
2
2016-06-24T12:19:11Z
[ "python", "numpy" ]
How can I download a youtube audio via python script in windows
38,013,233
<p>I am building a program in python and I need to download an audio from a youtube video.</p> <p>I searched on google and I found that there is a package called <code>youtube-dl</code>, but it has only an interpreter and I need to use it in code.</p> <p>So I continued looking and I found out that you can't use this ...
-1
2016-06-24T12:14:43Z
38,013,408
<p>Check this <a href="https://github.com/rg3/youtube-dl/blob/master/README.md#embedding-youtube-dl" rel="nofollow">developer section</a> and <a href="https://github.com/rg3/youtube-dl/blob/master/README.md#installation" rel="nofollow"> the installation instructions</a> for Windows.</p>
0
2016-06-24T12:24:41Z
[ "python", "youtube-dl" ]
How to connect spark with mysql using pycharm
38,013,291
<p>i try to select a table content from mysql database to a dataframe, i follow this steps to connect spark with mysql.</p> <ol> <li>download <code>mysql-connector-java-5.0.8-bin.jar</code></li> <li>i put <code>mysql-connector-java-5.0.8-bin.jar</code> at path <code>$SPARK_HOME/bin/mysql-connector-java-5.0.8-bin.jar</...
0
2016-06-24T12:17:57Z
38,013,811
<p>Just look you download download mysql-connector-java-5.0.8-bin.jar and in your code you start shell $SPARK_HOME/bin/pyspark –-jars mysql-connector-java-5.1.8-bin.jar your version of mysql driver is not same so can you once check after fix it.</p>
1
2016-06-24T12:47:27Z
[ "python", "mysql", "jdbc", "apache-spark", "pycharm" ]
Implement multithreading (or multiprocessing?) with this script?
38,013,470
<p>Let me first start this off by saying I don't have any real experience with multithreading. This script that I wrote reads ~4,400 addresses from a text file and then cleans the address and geocodes it. My brother mentioned something about using multithreading to improve the speed of it. I read online that multithrea...
0
2016-06-24T12:28:01Z
38,013,751
<p>Short answer is: <strong>no, you cannot</strong>.</p> <p>Python <code>multiprocessing</code> library allows you to decrease time needed to do all calculations by distributing them over several processes. It can speed up whole run of your script, but only when there is a lot to calculate for CPU.</p> <p>In your exa...
0
2016-06-24T12:42:51Z
[ "python", "multithreading", "geopy" ]
Applying function to Pandas dataframe by column
38,013,618
<p>I have a function which I want to apply to certain columns of a pandas dataframe. So rather than explicitly stating the columns, I want to dynamically select the columns I want and then call the function e.g.</p> <p>How to implement something like:</p> <pre><code>for column in dataframe: if column.name != 'ma...
2
2016-06-24T12:35:48Z
38,013,673
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow">drop()</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">apply()</a>:</p> <pre><code>df.drop('manager', axis=1).apply(func) </code></pre> <p...
1
2016-06-24T12:38:43Z
[ "python", "function", "pandas", "dataframe", "multiple-columns" ]
Applying function to Pandas dataframe by column
38,013,618
<p>I have a function which I want to apply to certain columns of a pandas dataframe. So rather than explicitly stating the columns, I want to dynamically select the columns I want and then call the function e.g.</p> <p>How to implement something like:</p> <pre><code>for column in dataframe: if column.name != 'ma...
2
2016-06-24T12:35:48Z
38,013,729
<p>I think you can first find all columns by <code>list comprehension</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> <code>func</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A':[1,2,3], ...
2
2016-06-24T12:41:35Z
[ "python", "function", "pandas", "dataframe", "multiple-columns" ]
JavaScript onload not recognized in extended html python flask
38,013,689
<p>I use a <code>basic.html</code> in my flask application which loads all needed ressources like footer navbar etc., all my other html sites extend this <code>basic.html</code></p> <p>In my <code>main.js</code> I created a simple function:</p> <pre><code>function fun() { alert("we have fun"); } </code></pre> <p>I...
1
2016-06-24T12:39:38Z
38,016,354
<p>The problem is simple. You can't attach <code>onload</code> to a <code>div</code>.</p> <blockquote> <p>The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and...
1
2016-06-24T14:55:53Z
[ "javascript", "jquery", "python", "html", "flask" ]
JavaScript onload not recognized in extended html python flask
38,013,689
<p>I use a <code>basic.html</code> in my flask application which loads all needed ressources like footer navbar etc., all my other html sites extend this <code>basic.html</code></p> <p>In my <code>main.js</code> I created a simple function:</p> <pre><code>function fun() { alert("we have fun"); } </code></pre> <p>I...
1
2016-06-24T12:39:38Z
38,017,662
<p>Put that in your basic.html </p> <pre><code>&lt;head&gt; &lt;script src="{{url_for('static', filename='js/main.js')}}"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onLoad="fun();"&gt; </code></pre> <p>onLoad needs to go in the body not in div</p>
1
2016-06-24T16:05:53Z
[ "javascript", "jquery", "python", "html", "flask" ]
Python - Data type handling for data fetched by connecting to the MSSQL DB
38,013,747
<p>Using the below Python Code connected to the mssql db and tried fetching the data from the DB.</p> <pre><code>import pymssql conn=pymssql.connect(host='localhost',user='sa',password='Password',database='HB') mycursor=conn.cursor() mycursor.execute("Select * from HB.dbo.TRANS") results=mycursor.fetchall() with open(...
0
2016-06-24T12:42:37Z
38,014,131
<p>If you want to change <code>datetime.datetime()</code> object you can use <strong>.strftime() method</strong></p> <p>Example usage:</p> <pre><code>import datetime some_datetime = datetime.datetime.now() print(some_datetime) # will output: datetime.datetime(2016, 6, 24, 14, 57, 54, 190307) print(some_datetime.strft...
0
2016-06-24T13:03:08Z
[ "python", "sql-server", "datetime" ]
Is there any numpy group by function?
38,013,778
<p>Is there any function in numpy to group this array down below by the first column?</p> <p>I couldn't find any good answer over the internet..</p> <pre><code>&gt;&gt;&gt; a array([[ 1, 275], [ 1, 441], [ 1, 494], [ 1, 593], [ 2, 679], [ 2, 533], [ 2, 686], [ ...
5
2016-06-24T12:45:15Z
38,013,977
<pre><code>n = unique(a[:,0]) array( [ list(a[a[:,0]==i,1]) for i in n] ) </code></pre> <p>outputs:</p> <pre><code>array([[275, 441, 494, 593], [679, 533, 686], [559, 219, 455], [605, 468, 692, 613]], dtype=object) </code></pre>
2
2016-06-24T12:55:37Z
[ "python", "arrays", "numpy" ]
Is there any numpy group by function?
38,013,778
<p>Is there any function in numpy to group this array down below by the first column?</p> <p>I couldn't find any good answer over the internet..</p> <pre><code>&gt;&gt;&gt; a array([[ 1, 275], [ 1, 441], [ 1, 494], [ 1, 593], [ 2, 679], [ 2, 533], [ 2, 686], [ ...
5
2016-06-24T12:45:15Z
38,015,063
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) aims to fill this gap in numpy. All operations in numpy-indexed are fully vectorized, and no O(n^2) algorithms were harmed during the making of this library.</p> <pre><code>i...
3
2016-06-24T13:51:00Z
[ "python", "arrays", "numpy" ]
Properly Format Data in CSV for Easy Import with Pandas
38,013,903
<p>Currently I am storing my data in the following manner in a csv file: </p> <pre><code>a,b,c 1 1 1 1,22 22 22,333 333 333 10 10 10, 20 20 20, 30 30 30 </code></pre> <p>However, this turns out to be a major pain in Pandas or in R's dataframe because by default, each language treats the values as strings. I therefore...
0
2016-06-24T12:51:44Z
38,014,002
<p>You could try this:</p> <pre><code>df[columns] = df[columns].convert_objects(convert_numeric=True) # astype df[columns] = df[columns].astype('float32') </code></pre>
0
2016-06-24T12:56:50Z
[ "python", "csv", "pandas" ]
Python remove all console output
38,013,983
<p>I want to erase all console output that was printed before each loop iteration.</p> <p>Currently I have a code like this:</p> <pre><code>import sys from time import sleep def delete_last_printed_lines(n=1): CURSOR_UP_ONE = '\x1b[1A' ERASE_LINE = '\x1b[2K' for _ in range(n): sys.stdout.write(C...
0
2016-06-24T12:56:08Z
38,014,102
<p>You can use subprocess : </p> <pre><code># -*- coding: utf-8 -*- import sys import subprocess from time import sleep for x in range(1, 3): subprocess.call('clear') print('') print('Some information #{0}'.format(x)) print('And a lot of different prints') sleep(1) </code></pre>
1
2016-06-24T13:01:54Z
[ "python", "console" ]
Python remove all console output
38,013,983
<p>I want to erase all console output that was printed before each loop iteration.</p> <p>Currently I have a code like this:</p> <pre><code>import sys from time import sleep def delete_last_printed_lines(n=1): CURSOR_UP_ONE = '\x1b[1A' ERASE_LINE = '\x1b[2K' for _ in range(n): sys.stdout.write(C...
0
2016-06-24T12:56:08Z
38,016,152
<p>An Unbutu solution would be to call <em>reset</em>:</p> <pre><code>for x in range(1, 3): subprocess.call('reset') print('Some information #{0}'.format(x)) print('And a lot of different prints') sleep(1) </code></pre>
0
2016-06-24T14:45:01Z
[ "python", "console" ]
Using multiple if & elif statements in a while loop won't work
38,014,016
<p>I have a task to make a program that asks the user about an issue they have with their mobile phone. My program is then to look at the input and go through a series of keywords it may recognise. Certain keywords allow it to read a certain line from a file I have created.</p> <p><a href="http://i.stack.imgur.com/Qnc...
-3
2016-06-24T12:57:31Z
38,014,609
<p>It's because once an if or (elif) statement is matched the whole of statement is done. Use all if statements and get rid of your last else statement. If you never satisfy any of the if statements your false condition will remain false anyway. You can have your last if statement be if keyword_comparison == false prin...
1
2016-06-24T13:27:59Z
[ "python" ]
Using multiple if & elif statements in a while loop won't work
38,014,016
<p>I have a task to make a program that asks the user about an issue they have with their mobile phone. My program is then to look at the input and go through a series of keywords it may recognise. Certain keywords allow it to read a certain line from a file I have created.</p> <p><a href="http://i.stack.imgur.com/Qnc...
-3
2016-06-24T12:57:31Z
38,014,852
<h1>Question</h1> <p>First of all, as you have been asked in the comments, you should provide a MCV example, this means the smallest code that can run on its own and reproduces your error, which usually means including all in one single file but if you decide to keep the <code>.txt</code> at least provide it.</p> <p>...
0
2016-06-24T13:40:18Z
[ "python" ]
Learning OR gate through gradient descent
38,014,053
<p>I am trying to make my program learn OR logic gate using neural network and gradient descent algorithm. I took additional input neuron as -1 so that I can adjust threshold of neuron for activation later. currently threshold is simply 0. Here's my attempt at implementation</p> <pre><code>#!/usr/bin/env python from n...
1
2016-06-24T12:59:37Z
38,019,593
<p>Well this <strong>is</strong> an OR gate, if you correct your testing data to be</p> <pre><code>activation = dot(array([[0,0,-1],[1,0,-1],[1,1,-1],[0,1,-1]]),wei) </code></pre> <p>(your code has 0,0 twice, and never 0,1) it produces</p> <pre><code>[[ 0.30021868] [ 0.67476151] [ 1.0276208 ] [ 0.65307797]] </cod...
1
2016-06-24T18:06:26Z
[ "python", "numpy", "machine-learning" ]
error while executing phyton code
38,014,124
<pre><code>from os import popen from string import split, join from re import match import subprocess import os # execute the code and pipe the result to a string rtr_table = [elem.strip().split() for elem in popen("route print").read().split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())] #print "Activ...
-2
2016-06-24T13:02:59Z
38,014,390
<pre><code>from os import popen from string import split, join from re import match import subprocess import os # execute the code and pipe the result to a string rtr_table = [elem.strip().split() for elem in popen("route print").read().split("Metric\n")[1].split("\n") if match("^[0-9]", elem.strip())] #print "Activ...
0
2016-06-24T13:15:53Z
[ "python", "python-2.7", "python-3.x" ]
Data types and documentation for for-loop in Python 3
38,014,233
<p>I am very confused about the data types and UTF-8 encoding. What is actually happening under the hood? I am reading a messy JSON data without delimiters in Python 3 (data has Japanese/Chinese characters time to time).</p> <p>I am reading in the data:</p> <pre><code>url = "http://localhost:8001" data = urllib.reque...
1
2016-06-24T13:07:53Z
38,014,292
<p>You need to decode the <a href="https://docs.python.org/3.6/library/stdtypes.html#bytes" rel="nofollow"><em>bytes</em></a> to <em>str</em>:</p> <pre><code>In [12]: data = urllib.request.urlopen("http://stackoverflow.com/questions/38014233/data-types-and-documentation-for-for-loop-in-python-3/38014292#38014292").rea...
1
2016-06-24T13:10:42Z
[ "python", "string", "python-3.x", "utf-8" ]
Data types and documentation for for-loop in Python 3
38,014,233
<p>I am very confused about the data types and UTF-8 encoding. What is actually happening under the hood? I am reading a messy JSON data without delimiters in Python 3 (data has Japanese/Chinese characters time to time).</p> <p>I am reading in the data:</p> <pre><code>url = "http://localhost:8001" data = urllib.reque...
1
2016-06-24T13:07:53Z
38,014,421
<p>Decoding the data as Padraic Cunningham suggested should work:</p> <pre><code>data = urllib.request.urlopen(url).read().decode("utf-8") </code></pre> <p>You also asked for the official documentatio for the for-loop. I'm not sure if you refer to <a href="https://docs.python.org/3/reference/compound_stmts.html#for" ...
3
2016-06-24T13:17:47Z
[ "python", "string", "python-3.x", "utf-8" ]
Django exclude on multiple fields in subquery
38,014,377
<p>Given some code like this:</p> <pre><code># coding: utf-8 import datetime from django.db import models from django.contrib.auth.models import User from django.contrib.sites.models import Site class Premium(models.Model): """Access to Premium Features™®.""" end = models.DateField() user = models.Fo...
1
2016-06-24T13:15:22Z
38,017,864
<p>I've come up with this... It's got some raw SQL but it still returns a QuerySet with normal QuerySet methods (although it uses the apparently deprecated <code>QuerySet.extra()</code> method)</p> <pre><code>def get_ending_premiums(day=None): """Get a queryset of Premiums for which a user has none following.""" ...
0
2016-06-24T16:16:22Z
[ "python", "django", "django-orm" ]
Django: object Id exists but the object has been deleted from media files
38,014,412
<p>I am a newbie with Django trying a simple code to upload and delete a file. Following the instructions given at the accepted answer of <a href="http://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example">Need a minimal Django file upload example</a>, I was able to create a successful versio...
0
2016-06-24T13:17:20Z
38,015,907
<p>They are stored in the database. You can access the database with <code>python manage.py dbshell</code>. If you haven't configured anything custom here it's probably SQLite. Here you can look up the correct table by entering <code>.tables</code>. Then you can use SQL to lookup and delete the model records which cont...
0
2016-06-24T14:33:01Z
[ "python", "django", "python-3.x" ]
XHR request fails in Scrapy but works in python-requests
38,014,426
<p>I'm trying to get data from a site using Ajax,I just smiulate the XHR request with headers and body, and I get a 400 response telling me that the request is not allowed. This is my code:</p> <pre><code>from scrapy import Spider from scrapy import Request, FormRequest import json class jsonSpider(Spider): name ...
3
2016-06-24T13:17:54Z
38,052,243
<p>This will work for you it gave 200 response for following code</p> <pre><code>from scrapy import Spider from scrapy import Request, FormRequest import json class jsonSpider(Spider): name = 'json_spider' start_urls = [ 'http://m.ctrip.com/restapi/soa2/10932/hotel/Product/domestichotelget'] def start...
2
2016-06-27T11:00:50Z
[ "python", "xmlhttprequest", "scrapy", "httprequest", "python-requests" ]
XHR request fails in Scrapy but works in python-requests
38,014,426
<p>I'm trying to get data from a site using Ajax,I just smiulate the XHR request with headers and body, and I get a 400 response telling me that the request is not allowed. This is my code:</p> <pre><code>from scrapy import Spider from scrapy import Request, FormRequest import json class jsonSpider(Spider): name ...
3
2016-06-24T13:17:54Z
38,083,370
<p>Remove <code>"Content-Length": "455",</code> in your headers and let scrapy calculates itself. Your <code>data</code> is 477 bytes long, so the server, i guess, takes first 455 bytes of the incoming data and fails to parse as json as it is not complete and returns 400 which means <code>Bad Request</code>.</p>
2
2016-06-28T18:08:31Z
[ "python", "xmlhttprequest", "scrapy", "httprequest", "python-requests" ]
"Clicking" HTML element with button tag
38,014,486
<p>I am trying to enter CEP in the field in the link below and then press the "calcular" button which is given by a tag and also of type "button." I think I've determined that mechanize won't get the job done, but even selenium isn't doing what I need it to. Below is my mechanize code.</p> <pre><code>br = mechanize.B...
0
2016-06-24T13:20:35Z
38,015,757
<p>Using selenium, you need to clear the placeholder then enter the postcode text with <code>send_keys</code>, to get the frete price etc.. we need to wait until that element is visible::</p> <pre><code>from selenium.webdriver.common.keys import Keys from selenium import webdriver from selenium.webdriver.common.by imp...
0
2016-06-24T14:25:42Z
[ "python", "web-scraping", "mechanize" ]
Error trying to connect the FCM CCS server with sleekxmpp
38,014,495
<p>I am trying to build a very simple python3 program using sleekxmpp 1.3.1 that would be able to connect the Firebase Cloud Messaging server. I have a strange <code>Error reading from XML stream</code> issue with the following code. How can I fix it?</p> <p>We can see from the console output that STARTTLS is enabled....
1
2016-06-24T13:21:09Z
38,015,195
<p>I found an answer <a href="https://groups.google.com/forum/#!topic/sleekxmpp-discussion/8UxC7sc-9V0" rel="nofollow">on the google list</a>. Replacing "use_tls = True" by "use_ssl = True", it works better.</p>
0
2016-06-24T13:57:56Z
[ "python", "google-cloud-messaging", "xmpp", "firebase-cloud-messaging" ]
Error trying to connect the FCM CCS server with sleekxmpp
38,014,495
<p>I am trying to build a very simple python3 program using sleekxmpp 1.3.1 that would be able to connect the Firebase Cloud Messaging server. I have a strange <code>Error reading from XML stream</code> issue with the following code. How can I fix it?</p> <p>We can see from the console output that STARTTLS is enabled....
1
2016-06-24T13:21:09Z
38,462,085
<p>Just for completeness, this would be an example of a working implementation:</p> <pre><code>from sleekxmpp.clientxmpp import ClientXMPP import logging import socket import json import uuid logging.basicConfig(level=logging.DEBUG, format="%(levelname)7s %(module)12s:%(lineno)-4s %(message)s") FCM_SERVER_URL = "fcm...
1
2016-07-19T14:58:07Z
[ "python", "google-cloud-messaging", "xmpp", "firebase-cloud-messaging" ]
Add geometry Column in sqlite (QGIS) by using python code
38,014,512
<p>I'm trying to create a geometry column in a table which I created.</p> <p>I found the following code:</p> <pre><code>cur.execute('SELECT addgeometrycolumn(%s, %s, %s, %s, %s)' %(table_name, geometry_column_name, EPSGcode, 'POLYGON', 'XYZ')) </code></pre> <p>but I always get the same error : no such column table_n...
0
2016-06-24T13:21:50Z
38,017,185
<p>This error looks familiar to me.</p> <p>Does the table exist? If so, use it in the argument list.</p> <p>Also, check that the data types are correct. Some may be integers.</p> <p>I looked here, but did not confirm:</p> <p><a href="https://www.gaia-gis.it/spatialite-2.3.0/spatialite-sql-2.3.0.html" rel="nofollo...
0
2016-06-24T15:40:13Z
[ "python", "sql", "qgis" ]
How to identify colors in a string with nltk in python?
38,014,539
<p>The question really speaks for itself, but my problem is I want to be able to identify colors in a string with nltk and all I can find is how to classify parts of speech. I know I could just make a list of all the colors I want to support but since I want to support all the colors available in css this would be quit...
1
2016-06-24T13:23:21Z
38,016,266
<p>I would not use nltk but regex. </p> <ol> <li>Get a list of all css colors (<a href="http://colours.neilorangepeel.com/" rel="nofollow">here</a>)</li> <li>extract the color names and build a list (using beautifulsoup)</li> <li>build a regex pattern </li> <li>use this regex pattern to match what you want in your str...
1
2016-06-24T14:50:59Z
[ "python", "python-3.x", "colors", "nltk" ]
How to identify colors in a string with nltk in python?
38,014,539
<p>The question really speaks for itself, but my problem is I want to be able to identify colors in a string with nltk and all I can find is how to classify parts of speech. I know I could just make a list of all the colors I want to support but since I want to support all the colors available in css this would be quit...
1
2016-06-24T13:23:21Z
38,019,359
<p>You can use <a href="https://pypi.python.org/pypi/webcolors/1.3" rel="nofollow">the <code>webcolors</code> package</a> to get all css color names that it recognizes, just check for membership of <code>webcolors.CSS3_NAMES_TO_HEX</code>:</p> <pre><code>&gt;&gt;&gt; import webcolors &gt;&gt;&gt; "green" in webcolors....
2
2016-06-24T17:50:09Z
[ "python", "python-3.x", "colors", "nltk" ]
How to identify colors in a string with nltk in python?
38,014,539
<p>The question really speaks for itself, but my problem is I want to be able to identify colors in a string with nltk and all I can find is how to classify parts of speech. I know I could just make a list of all the colors I want to support but since I want to support all the colors available in css this would be quit...
1
2016-06-24T13:23:21Z
38,023,086
<p><strong>Solution (for me anyway):</strong></p> <blockquote> <p><strong>Note:</strong> If you simply need the colors without spaces ('deepskyblue' instead of 'deep sky blue') any of the previous answers will work. However, since I'm using this in combination with speech recognition I need the colors seperated ...
1
2016-06-24T22:42:53Z
[ "python", "python-3.x", "colors", "nltk" ]
customize ticks label when sharex is on in matplotlib
38,014,571
<p>I have two stacked subplots which share the x axis, for both subplots visibility of ticks is set to false because I don't want to see tick labels. after having plotted both subplots, I would like to put some extra ticks on x-asis, only for second subplot, but they don't have to became the main ticks. I mean, doing ...
1
2016-06-24T13:25:05Z
38,021,638
<p>This works for removing the tick labels from a single axis when using <code>sharex</code>, but I don't see a solution to also remove the ticks..</p> <pre><code>import matplotlib.pylab as pl pl.figure() ax1=pl.subplot(211) ax1.plot([0,10],[0,10]) ax2=pl.subplot(212, sharex=ax1) ax2.plot([0,10],[10,0]) pl.setp(ax1...
1
2016-06-24T20:30:40Z
[ "python", "matplotlib" ]
Very simple demonstration of Backward Compatibility
38,014,574
<p>I just want to clarify my concept about backward compatibility, for which I have created a small example. This example is not intended to show any real use and I have ignored all other aspects of the program to keep it as simple as possible.</p> <p>If there is a function in the first version of an application:</p> ...
-1
2016-06-24T13:25:09Z
38,014,783
<p><a href="https://en.wikipedia.org/wiki/Backward_compatibility" rel="nofollow">See the wikipedia page about backward compatibilty.</a></p> <p>As far as your example is concerned, it would mean that data changes its format from <code>list</code> to <code>string</code> accross the whole software and for backward compa...
1
2016-06-24T13:36:55Z
[ "python", "backwards-compatibility" ]
Animating a pcolormesh with contours with maltpoltlib
38,014,587
<p>I am working on something : I need to vizualize the progress of, let us say heat, in time and on a surface.</p> <p>I'm having some troubles animating a pcolormesh with contours : the contour is indeed animated, but the pcolormesh is not ; I only get the first one that is never replaced.</p> <p>My code is quite lik...
1
2016-06-24T13:26:04Z
38,018,734
<p>Beyond some coding errors, I don't see why this functionally wouldn't work. This minimal example updates both the <code>pcolormesh</code> and <code>contour</code>'s without a problem. Could you test this to see if it works for you?</p> <pre><code>import numpy as np import matplotlib.pylab as plt import matplotlib.a...
1
2016-06-24T17:07:20Z
[ "python", "animation", "matplotlib" ]
How did I get this figure?
38,014,612
<p>I have this code:</p> <pre><code>"""Softmax.""" import math scores = [3.0, 1.0, 0.2] import numpy as np def softmax(x): """Compute softmax values for each sets of scores in x.""" pass # TODO: Compute and return softmax(x) sum_denominator = 0 powers = [] for item in x: powers.append(...
1
2016-06-24T13:28:11Z
38,015,007
<p>So I am not sure if this is an answer, but it is too short to post as a comment, so I am posting it as an answer.</p> <p>So when I run the above program, this is what I get:</p> <pre><code>In [12]: %run softmax.py [0.8360188027814407, 0.11314284146556014, 0.050838355752999165] </code></pre> <p>So this clearly pri...
4
2016-06-24T13:48:10Z
[ "python", "numpy", "deep-learning", "audacity", "softmax" ]
Feature importance for each modality
38,014,713
<p>I am doing a random forest with sklearn in Python.<br> I try to get the score of each modality for an attribute.<br> For example, in the titanic dataset, how can we get the score of each modality of the Pclass variable?<br> Thanks</p>
-2
2016-06-24T13:33:18Z
38,021,234
<p>The Pclass variable is a <em>categorical</em> variable. This means that it takes on 2 or more discrete values. For such variables, it is always recommended to represent them using <a href="https://www.quora.com/What-is-one-hot-encoding-and-when-is-it-used-in-data-science" rel="nofollow">One-Hot</a> encoding. For exa...
0
2016-06-24T20:00:42Z
[ "python", "scikit-learn", "random-forest" ]
Why is my ship not shooting bullets?
38,014,739
<p>I have made a game using Python and Pygame. My ship moves around but I am having trouble making it shoot bullets. I have defined a function called <code>shootBullets()</code> but it is not working. And now, if I press the space bar, my ship moves. It is only supposed to move when I press the left or right arrow keys...
0
2016-06-24T13:34:49Z
38,014,891
<p>In your main loop you are only checking for left and right, not for space. You check in the function <code>shootBullets</code> whether space is pressed, but that is too late, shootBullets will never be executes (actually it will get executed if the <code>for event in get()</code> loop is somehow exited but that is n...
1
2016-06-24T13:42:19Z
[ "python", "pygame" ]
How to access logs of another program ran on subprocess in Python
38,014,766
<p>I am having a difficulty in applying the logging module of Python to do what I want. Well, I am currently running <code>prog2.py</code> in <code>prog1.py</code> via subprocess module</p> <pre><code>input_args = ['python', '/path/to/prog2.py'] + self.chosen_args self.process = Popen((input_args), stdout=PIPE) </code...
1
2016-06-24T13:35:55Z
38,017,056
<p>If prog2.py prints to stdout, you can redirect output to your own log file.</p> <pre><code>input_args = ['python', '/path/to/prog2.py'] + self.chosen_args file = open("your own log file.txt",'w') self.process = Popen((input_args), stdout=file) </code></pre>
0
2016-06-24T15:33:21Z
[ "python", "logging" ]
Sublime Text: Hide all code and show only comments (with line break)
38,014,950
<p>Previously I asked a question on how to <a href="http://stackoverflow.com/questions/37282130/sublime-text-hide-all-code-and-show-only-comments">hide everything except comments</a> in Sublime Text 3.</p> <p><a href="http://stackoverflow.com/users/5963435/r-stein">r-stein</a> worked out a handy plugin that was able t...
1
2016-06-24T13:45:09Z
38,022,851
<p>You can change the previous plugin to keep leading "newlines" and "newlines and the indent" after the fold region:</p> <pre class="lang-py prettyprint-override"><code>import sublime import sublime_plugin def char_at(view, point): return view.substr(sublime.Region(point, point + 1)) def is_space(view, point)...
1
2016-06-24T22:15:13Z
[ "python", "sublimetext3", "sublimetext" ]
pandas - drop row based on first occurrence of condition
38,014,984
<p>Below is a sample of a larger dictionary</p> <pre><code> data ={'StudentId':['AAdams','AAdams','AAdams','AAdams','AAdams','AAdams', 'BBrooks','BBrooks','BBrooks','BBrooks','BBrooks',], 'year':[2015,2015,2015,2015,2015,2015,2015,2015,2015,2016,2016], 'month':[11,11,11,11,12,12,12,12,12,1,1], 'day':[...
1
2016-06-24T13:47:25Z
38,015,437
<p>Try this</p> <pre><code># sort and reindex df = df.sort('col').reset_index() #slice to first occurrence of your value df.loc[: df[(df['col'] == 'row')].index[0], :] </code></pre>
0
2016-06-24T14:09:28Z
[ "python", "pandas" ]
pandas - drop row based on first occurrence of condition
38,014,984
<p>Below is a sample of a larger dictionary</p> <pre><code> data ={'StudentId':['AAdams','AAdams','AAdams','AAdams','AAdams','AAdams', 'BBrooks','BBrooks','BBrooks','BBrooks','BBrooks',], 'year':[2015,2015,2015,2015,2015,2015,2015,2015,2015,2016,2016], 'month':[11,11,11,11,12,12,12,12,12,1,1], 'day':[...
1
2016-06-24T13:47:25Z
38,360,172
<p>Original Question (as stated above):</p> <p>Below is a sample of a larger dictionary which became dfdata</p> <pre><code>data ={'StudentId':['AAdams','AAdams','AAdams','AAdams','AAdams','AAdams', 'BBrooks','BBrooks','BBrooks','BBrooks','BBrooks',], 'year':[2015,2015,2015,2015,2015,2015,2015,2015,2015,2...
0
2016-07-13T19:28:33Z
[ "python", "pandas" ]
Python re.compile curly quotes issue
38,014,994
<p>I'm currently writing an application that uses a framework to match certain phrases, currently it is supposed to match the following regex pattern:</p> <pre><code>Say \"(.*)\" </code></pre> <p>However, I've notices that my users are complaining about the fact that their OS sometimes copies and pastes 'curly quotes...
2
2016-06-24T13:47:50Z
38,015,099
<p>You could just include the curly quotes in the regex:</p> <pre><code>Say [\"“”](.*)[\"“”] </code></pre> <p>As something you can replicate in the Python repl, it's like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; test_str = r'"Hello"' &gt;&gt;&gt; reg = r'["“”](.*)["“”]' &gt;&gt;&gt; m...
3
2016-06-24T13:52:59Z
[ "python", "regex" ]
Python re.compile curly quotes issue
38,014,994
<p>I'm currently writing an application that uses a framework to match certain phrases, currently it is supposed to match the following regex pattern:</p> <pre><code>Say \"(.*)\" </code></pre> <p>However, I've notices that my users are complaining about the fact that their OS sometimes copies and pastes 'curly quotes...
2
2016-06-24T13:47:50Z
38,015,234
<p>As an alternative to Kyle's answer you can prepare string to your current regex by replacing curly quotes: <code>string.replace('“', '"').replace('”', '"')</code></p>
1
2016-06-24T13:59:21Z
[ "python", "regex" ]
How to write specific length lines of a file?
38,015,097
<p>I have this sequences (over 9000) like this:</p> <pre><code>&gt;TsM_000224500 MTTKWPQTTVTVATLSWGMLRLSMPKVQTTYKVTQSRGPLLAPGICDSWSRCLVLRVYVDRRRPGGDGSLGRVAVTVVETGCFGSAASFSMWVFGLAFVVTIEEQLL &gt;TsM_000534500 MHSHIVTVFVALLLTTAVVYAHIGMHGEGCTTLQCQRHAFMMKEREKLNEMQLELMEMLMDIQTMNEQEAYYAGLHGAGMQQPLPMPIQ &gt;TsM_000355900 M...
0
2016-06-24T13:52:47Z
38,015,303
<p>In your for loop, <code>x</code> is an iterating integer due to using <code>range()</code> (i.e, <code>0,1,2,3,4...</code>). Try this instead:</p> <p><code>for x in ts:</code></p> <p>This will give you each element in <code>ts</code> as <code>x</code></p> <p>Also, you don't need the brackets around <code>x</code>...
1
2016-06-24T14:02:56Z
[ "python", "file" ]
How to write specific length lines of a file?
38,015,097
<p>I have this sequences (over 9000) like this:</p> <pre><code>&gt;TsM_000224500 MTTKWPQTTVTVATLSWGMLRLSMPKVQTTYKVTQSRGPLLAPGICDSWSRCLVLRVYVDRRRPGGDGSLGRVAVTVVETGCFGSAASFSMWVFGLAFVVTIEEQLL &gt;TsM_000534500 MHSHIVTVFVALLLTTAVVYAHIGMHGEGCTTLQCQRHAFMMKEREKLNEMQLELMEMLMDIQTMNEQEAYYAGLHGAGMQQPLPMPIQ &gt;TsM_000355900 M...
0
2016-06-24T13:52:47Z
38,015,350
<p>Try this, simple and easy to understand. It does not load the entire file into memory, instead iterates over the file line by line.</p> <pre><code>tsf=open('output.txt','w') # open the output file with open("yourfile",'r') as ts: # open the input file for line in ts: # iterate over each line of input file ...
0
2016-06-24T14:05:19Z
[ "python", "file" ]
Python cant find class attribute
38,015,104
<p>Why is not <code>Factory.rdyq</code> visible to inherited classes?</p> <p>bar.py</p> <pre><code>import Queue import threading class Factory: name = "" rdyQ = Queue.Queue() dispQ = Queue.Queue() def __init__(self): self.worker_count = 1 self.worker_thread = None def worker(s...
-1
2016-06-24T13:53:07Z
38,015,184
<p>You should use a <code>classmethod</code> instead of a <code>staticmethod</code> for joinQ.</p> <p>You also had a <code>rdyq</code> (bar.py last line) instead of the expected <code>rdyQ</code> and Python is case-sensitive.</p> <p>bar.py</p> <pre><code>import Queue import threading class Factory: name = "" ...
1
2016-06-24T13:57:39Z
[ "python", "python-multithreading" ]
Python cant find class attribute
38,015,104
<p>Why is not <code>Factory.rdyq</code> visible to inherited classes?</p> <p>bar.py</p> <pre><code>import Queue import threading class Factory: name = "" rdyQ = Queue.Queue() dispQ = Queue.Queue() def __init__(self): self.worker_count = 1 self.worker_thread = None def worker(s...
-1
2016-06-24T13:53:07Z
38,015,185
<p>Python variables and attributes are case sensitive, so "rdyq" is not the same as "rdyQ".</p>
1
2016-06-24T13:57:42Z
[ "python", "python-multithreading" ]
Python cant find class attribute
38,015,104
<p>Why is not <code>Factory.rdyq</code> visible to inherited classes?</p> <p>bar.py</p> <pre><code>import Queue import threading class Factory: name = "" rdyQ = Queue.Queue() dispQ = Queue.Queue() def __init__(self): self.worker_count = 1 self.worker_thread = None def worker(s...
-1
2016-06-24T13:53:07Z
38,015,210
<p>You set the name with a capital q, so maybe this will fix it?</p> <p>Factory.rdyQ.put(i)</p> <p>I recommend using_underscores_for_variables as you avoid issues camelCase can cause. </p>
1
2016-06-24T13:58:33Z
[ "python", "python-multithreading" ]
Scrape the return of a JS onclick function
38,015,106
<p>First question asked here.</p> <p>I need to scrape the url generated by a JS onclick function of a website. So, I think Selenium could do the job, but I can't figure out how to code that without opening other tabs/windows and don't even know if it's possible.</p> <p>Here's the onclick JS function:</p> <blockquote...
0
2016-06-24T13:53:12Z
38,023,988
<p>See an example about switching to new window and switch back below:</p> <pre><code>driver.get("your-application-URL") time.sleep(3) window_before = driver.window_handles[0] windowHandlesAllBefore = driver.window_handles linkElements = driver.find_elements_by_css_selector("[onclick='javascript:grv(']") for aLink in...
0
2016-06-25T01:02:21Z
[ "javascript", "python", "selenium", "onclick", "scrape" ]
Issue with UTF-/ encoding on csv file for excel
38,015,124
<h2>EDIT:</h2> <p>As suggested special chars are displayed correctly if I use notepad++ to open the csv file. They are displayed correctly too when I import the csv file into excel. How can I generate a csv file that is displayed correctly when opened by excel since file importing is not an option for the users</p> ...
0
2016-06-24T13:53:51Z
38,015,662
<p>I fixed this issue using UTF-8 BOM encoding.</p> <pre><code># -*- coding: utf-8-sig-*- import unicodecsv as csv import codecs import sys reload(sys) sys.setdefaultencoding("utf-8-sig") def write_csv(file,headers): resultFile =codecs.open(file, "w+", "utf-8-sig") #headers=[s.encode('utf-8') for s in heade...
0
2016-06-24T14:20:33Z
[ "python", "excel", "unicode", "utf-8" ]
Issue with UTF-/ encoding on csv file for excel
38,015,124
<h2>EDIT:</h2> <p>As suggested special chars are displayed correctly if I use notepad++ to open the csv file. They are displayed correctly too when I import the csv file into excel. How can I generate a csv file that is displayed correctly when opened by excel since file importing is not an option for the users</p> ...
0
2016-06-24T13:53:51Z
38,025,106
<p>Python 2 solution using <code>unicodecsv</code>. Note that the documentation for <code>unicodecsv</code> says the module should be opened in binary mode (<code>wb</code>). Make sure to write Unicode strings. <code>#coding</code> is required to support non-ASCII characters in the source file. Make sure to save th...
1
2016-06-25T04:55:48Z
[ "python", "excel", "unicode", "utf-8" ]
Subset a dictionary of dataframes through iteration
38,015,193
<p>I am creating a program to ingest a series of text files from 2001Q1 through 2016Q1 based upon name qualifiers which indicate the schedule/report type. The qualifiers are referred to as keys (for lack of a better name)</p> <pre><code>keys=[' RI ','RCD','RCF','RCG','RCH','RCL','RCO','RCRII'] </code></pre> <p>given...
1
2016-06-24T13:57:52Z
38,015,617
<p>You can't directly create a dictionary on <code>key.strip</code> nor <code>key.strip()</code>, because well they are functions. You can however create a temporary dictionary, and use the value returned by those functions as a key in the temporary dictionary. </p> <p>This is a relatively safer method:</p> <pre><cod...
1
2016-06-24T14:18:11Z
[ "python", "dictionary", "pandas", "iteration" ]
How to authenticate user via git pre-receive hook
38,015,205
<p>I am looking to write a <code>pre-receive</code> githook in Python. It is my understanding that no arguments are passed into <code>pre-receive</code> scripts but rather each reference is passed in using standard input on separate lines. I have been able to read the reference changes via:</p> <pre><code>!/usr/bin/...
0
2016-06-24T13:58:27Z
38,015,627
<p>If you are using git over ssh (or git in the local file system) the committing user will be available to the hook in the environment variable USER, so in python you can check against <code>os.environ['USER']</code></p> <p>It is possible to set up an environment (using git-daemon; there are other ways as well) where...
1
2016-06-24T14:18:44Z
[ "python", "git", "authentication", "githooks" ]
How to authenticate user via git pre-receive hook
38,015,205
<p>I am looking to write a <code>pre-receive</code> githook in Python. It is my understanding that no arguments are passed into <code>pre-receive</code> scripts but rather each reference is passed in using standard input on separate lines. I have been able to read the reference changes via:</p> <pre><code>!/usr/bin/...
0
2016-06-24T13:58:27Z
38,017,490
<p>From the stdin, we can get <code>&lt;old-value&gt; SP &lt;new-value&gt; SP &lt;ref-name&gt; LF</code>. Use <code>git cat-file -p $new-value</code> or <code>git cat-file -p $ref-name</code> in the hook, we can get info like this</p> <pre><code>tree d06734b17feff2faf22bcd7c0fac1587876e601d parent 524bd5e2fa72e6358a22...
2
2016-06-24T15:56:18Z
[ "python", "git", "authentication", "githooks" ]
Counting the number of nodes containing data at a specific level - nTree
38,015,250
<p>I have an nTree (n-dimensions) and I want to calculate the number of nodes containing data points at a particular depth. Here is the tree structure and the function that I am trying to use:</p> <pre><code>class nTree: def initialize(self, hypercube_coordinates, depth=0): self.data = [] #holds the data ...
0
2016-06-24T14:00:03Z
38,017,049
<p>Problem fixed. For anyone looking for a solution here is the method:</p> <pre><code>#countNodesAtLevel - returns the number of non-empty nodes at a given level #Parameters: # depth - depth at which we are counting def _countNodesAtLevel(self, depth, count=0): #root level = 0, return only 1 for the data ...
0
2016-06-24T15:32:59Z
[ "python", "data-structures", "tree", "tree-traversal" ]
can someone explain how to use str.index and str.find and why the following code is wrong
38,015,270
<p>I'm very new to python and have been trying out codewars. Some problems pretty difficult for me. What I'm trying to accomplish is,"to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters)." I don't really understand how to use index and/or f...
-7
2016-06-24T14:00:56Z
38,015,343
<p><strong>str.index:</strong></p> <blockquote> <p>Like <strong>S.find()</strong> but raise ValueError when the substring is not found.</p> </blockquote> <p>To find the vowels in a given word you need to take one note as you already mentioned in your question, some words can have more than one vowel (i.e.,"enumerat...
1
2016-06-24T14:04:55Z
[ "python" ]
can someone explain how to use str.index and str.find and why the following code is wrong
38,015,270
<p>I'm very new to python and have been trying out codewars. Some problems pretty difficult for me. What I'm trying to accomplish is,"to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters)." I don't really understand how to use index and/or f...
-7
2016-06-24T14:00:56Z
38,015,536
<p>Check the documentation</p> <ul> <li><a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#string-methods</a></li> <li><a href="https://docs.python.org/3/library/stdtypes.html#str.index" rel="nofollow">https://docs.python.org/3/librar...
0
2016-06-24T14:13:50Z
[ "python" ]
can someone explain how to use str.index and str.find and why the following code is wrong
38,015,270
<p>I'm very new to python and have been trying out codewars. Some problems pretty difficult for me. What I'm trying to accomplish is,"to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters)." I don't really understand how to use index and/or f...
-7
2016-06-24T14:00:56Z
38,016,792
<p>You don't call <a href="https://docs.python.org/3/library/stdtypes.html#str.find" rel="nofollow"><code>str.find</code></a> or <a href="https://docs.python.org/3/library/stdtypes.html#str.find" rel="nofollow"><code>str.index</code></a> like that. They both take arguments of the form</p> <pre><code>(sub[, start[, end...
4
2016-06-24T15:17:49Z
[ "python" ]
How to create a numpy array from a pydub AudioSegment?
38,015,319
<p>I'm aware of the following question: <a href="http://stackoverflow.com/questions/35735497/how-to-create-a-pydub-audiosegment-using-an-numpy-array">How to create a pydub AudioSegment using an numpy array?</a></p> <p>My question is the right opposite. If I have a pydub AudioSegment how can I convert it to a numpy ar...
2
2016-06-24T14:03:37Z
38,021,664
<p>Pydub has a facility for getting the <a href="https://github.com/jiaaro/pydub/blob/master/API.markdown#audiosegmentget_array_of_samples" rel="nofollow">audio data as an array of samples</a>, it is an <code>array.array</code> instance (not a numpy array) but you should be able to convert it to a numpy array relativel...
1
2016-06-24T20:32:32Z
[ "python", "arrays", "numpy", "wave", "pydub" ]
Python - requests.exceptions.SSLError - dh key too small
38,015,537
<p>I'm scraping some internal pages using Python and requests. I've turned off SSL verifications and warnings. </p> <pre><code>requests.packages.urllib3.disable_warnings() page = requests.get(url, verify=False) </code></pre> <p>On certain servers I receive an SSL error I can't get past.</p> <pre><code>Traceback (mos...
2
2016-06-24T14:13:53Z
38,016,392
<p>Disabling warnings or certificate validation will not help. The underlying problem is a weak DH key used by the server which can be misused in the <a href="https://weakdh.org/" rel="nofollow">Logjam Attack</a>. </p> <p>To work around this you need to chose a cipher which does not make any use of Diffie Hellman Key ...
2
2016-06-24T14:58:02Z
[ "python", "ssl", "python-requests" ]
ttk progress bar stops whilst running sql query within GUI
38,015,587
<p>I'm building a GUI which at some point(s) will query a SQL database. Whilst the query is running, I wanted to show the user an indeterminate progress bar (ttk) which would indicate this. See below for simple example.</p> <pre><code>from Function_Sheet import * from Tkinter import * import ttk root = Tk() s = ttk.S...
0
2016-06-24T14:16:47Z
38,015,796
<p>For <code>tkinter</code> to draw anything, it must be in the mainloop. The mainloop is exactly as it sounds- an infinite loop which handles events. As such, commands after the mainloop are not done until the mainloop completes.</p> <p>To solve your issue, you need to setup the SQL query to happen in the mainloop wh...
1
2016-06-24T14:27:23Z
[ "python", "python-2.7", "user-interface", "tkinter", "ttk" ]
TypeError: 'str' object does not support item assigment
38,015,628
<p>I'm new at python and I have this problem while making a simple battleship game. Here is my code:</p> <pre><code>board = [] row = ['O'] * 5 #&lt;&lt;&lt;&lt;determine the board size here joined_O = ' '.join(row) for i in range(5): #&lt;&lt;&lt;&lt;determine the board size here board.append(joined_O) pri...
0
2016-06-24T14:18:44Z
38,015,727
<p>Look at:</p> <pre><code>board = [] row = ['O'] * 5 #&lt;&lt;&lt;&lt;determine the board size here joined_O = ' '.join(row) </code></pre> <ul> <li>board is a list. </li> <li>row is a list. </li> <li>joined_O is a string formed by concatenating the elements of row.</li> </ul> <p>AND:</p> <pre><code>for i in ra...
1
2016-06-24T14:24:15Z
[ "python", "typeerror" ]
TypeError: 'str' object does not support item assigment
38,015,628
<p>I'm new at python and I have this problem while making a simple battleship game. Here is my code:</p> <pre><code>board = [] row = ['O'] * 5 #&lt;&lt;&lt;&lt;determine the board size here joined_O = ' '.join(row) for i in range(5): #&lt;&lt;&lt;&lt;determine the board size here board.append(joined_O) pri...
0
2016-06-24T14:18:44Z
38,015,765
<pre><code>for i in range(5): #&lt;&lt;&lt;&lt;determine the board size here board.append(joined_O) </code></pre> <p>This doesn't look right to me. You should be appending lists to <code>board</code>, not strings. I'm guessing that you previously had something like:</p> <pre><code>for i in range(5): board.app...
1
2016-06-24T14:25:59Z
[ "python", "typeerror" ]
How to send data through parallel port in Python?
38,015,764
<p>I need to send some data via parallel port using Python. And for this I am using <strong><a href="http://www.psychopy.org/api/parallel.html" rel="nofollow">psychopy.parallel</a></strong> module. </p> <p>I have two Windows 7 x64 machines connected via parallel port. This connection is tested and working because it ...
0
2016-06-24T14:25:55Z
38,050,870
<p>There are a few options:</p> <ul> <li>Maybe you haven't got the right driver for pyparallel/psychopy to talk to. You'll need a 32bit parallel port driver if you're using the Standalone PsychoPy (which includes 32bit python). The answer in the link below tells you how to download another test utility that will inser...
1
2016-06-27T09:54:00Z
[ "python", "psychopy", "parallel-port" ]
python replace not working
38,015,830
<p>I am trying to do multiple replaces in python but the replace is not working, it only replaces the <code>&lt;UNK&gt;</code> but not <code>&lt;/s&gt;</code>. Can anybody tell me where the error is?</p> <pre><code>text=text.replace(":&lt;UNK&gt;","") text=text.replace("&lt;/s&gt;","") </code></pre>
0
2016-06-24T14:29:05Z
38,016,281
<p>Your code worked correctly but You can use regular expression to find and replace the text.</p> <pre><code>import re text = '1.595879e-04(Kan) 7.098440e-08(Şekerini:&lt;UNK&gt;) 2.558586e-06(Etkileyen) 7.671361e-07(Besinler) 3.731427e-02(&lt;/s&gt;) (ailehekimligi-0000000001)' output = re.sub(r':&lt;UNK&gt;', '', ...
1
2016-06-24T14:51:41Z
[ "python", "replace" ]
How to produce xml structure up to certain xml node ussing Python?
38,015,841
<p>I am new for this stuff. Because of my original xml is about 8GB it is hard to explore all parents, grandparents, grandgrandparents, etc. for the interested child in the original xml manually. I am trying to look through all the nodes until interested child is found. So I want to create "skeleton" structure of xml u...
1
2016-06-24T14:29:44Z
38,016,442
<p>If I understand you correctly you want something like:</p> <pre><code>look_through_structure(parent, my_tag): for node in parent.iter("*"): out_str.write('Parent tag: %s\n' % node.tag) for nxt in node: if nxt.tag == my_tag: out_str.write('child tag: %s\n' % my_tag) ...
1
2016-06-24T15:01:25Z
[ "python", "xml", "lxml" ]
How to produce xml structure up to certain xml node ussing Python?
38,015,841
<p>I am new for this stuff. Because of my original xml is about 8GB it is hard to explore all parents, grandparents, grandgrandparents, etc. for the interested child in the original xml manually. I am trying to look through all the nodes until interested child is found. So I want to create "skeleton" structure of xml u...
1
2016-06-24T14:29:44Z
38,102,508
<p>@Padraic. Thanks a lot! Your code is mostly what I want. But if I insert additional node (for example attributes) which is child of country node and parent for the neighbor node it gives unexpected results: </p> <pre><code>&lt;data&gt; &lt;country name="Liechtenstein"&gt; &lt;attributes&gt; &lt;rank&gt;1&lt;/ra...
1
2016-06-29T14:24:17Z
[ "python", "xml", "lxml" ]