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
Using logistic regression to predict the parameter value
39,444,955
<p>I have written vary basic sklearn code using logistic regression to predict the value. </p> <p>Training data looks like - </p> <p><a href="https://gist.github.com/anonymous/563591e0395e8d988277d3ce63d7438f" rel="nofollow">https://gist.github.com/anonymous/563591e0395e8d988277d3ce63d7438f</a></p> <pre><code>date ...
0
2016-09-12T07:05:21Z
39,469,278
<p>Use following code to get predicted labels:</p> <pre><code>predicted_labels= model.predict(test[x1]) </code></pre> <p>Also try following example to understand logistic regression in sklearn:</p> <pre><code># Logistic Regression from sklearn import datasets from sklearn import metrics from sklearn.linear_model imp...
1
2016-09-13T11:47:22Z
[ "python", "machine-learning", "scikit-learn", "classification", "logistic-regression" ]
Python Tkinter in Docker .TclError: couldn't connect to display
39,445,047
<p>I am new to python and am trying to build a small app. It needs to be a GUI app and I was wanting to containerise it with docker. I am getting the following error and can not find a solution</p> <pre><code>No protocol specified No protocol specified Traceback (most recent call last): File "tkinker.py", line 7, in...
2
2016-09-12T07:11:56Z
39,445,113
<p>As <a href="https://hub.docker.com/r/dorakorpar/nsgui/" rel="nofollow">described here</a>, you would need an X11 graphic layer.<br> But since you are already on an '(X)Ubuntu, setting the DISPLAY should be enough:</p> <pre><code>export DISPLAY=127.0.0.1:0.0 docker run -it -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp...
1
2016-09-12T07:16:20Z
[ "python", "ubuntu", "docker", "tkinter", "xfce" ]
Python Tkinter in Docker .TclError: couldn't connect to display
39,445,047
<p>I am new to python and am trying to build a small app. It needs to be a GUI app and I was wanting to containerise it with docker. I am getting the following error and can not find a solution</p> <pre><code>No protocol specified No protocol specified Traceback (most recent call last): File "tkinker.py", line 7, in...
2
2016-09-12T07:11:56Z
39,445,114
<p>You'll have to set DISPLAY in the container. You can add it as an argument to the docker run command like this:</p> <pre><code>docker run -ti -e DISPLAY=$DISPLAY blah-image blah-command </code></pre> <p>DISPLAY should be set in the Xubuntu shell you are running the command from.</p>
1
2016-09-12T07:16:29Z
[ "python", "ubuntu", "docker", "tkinter", "xfce" ]
How do I properly combine numerical features with text (bag of words) in scikit-learn?
39,445,051
<p>I am writing a classifier for web pages, so I have a mixture of numerical features, and I also want to classify the text. I am using the bag-of-words approach to transform the text into a (large) numerical vector. The code ends up being like this:</p> <pre><code>from sklearn.feature_extraction.text import CountVe...
0
2016-09-12T07:12:03Z
39,446,018
<p>You can weight the counts by using the <a href="http://scikit-learn.org/stable/modules/feature_extraction.html#tfidf-term-weighting" rel="nofollow">Tf–idf</a>:</p> <pre><code>import numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer np.set_printoptions(linewidth=200) corpu...
0
2016-09-12T08:19:35Z
[ "python", "scikit-learn", "classification", "text-classification" ]
Pandas INT column datatype changes depending on how the data is called (BUG?)
39,445,080
<p>I have a dataframe <code>XY</code> with two columns, one is an integer column, the other one a float column.</p> <p>The integer column is called <code>Count</code> (with a capital C to avoid problems) and its unique values are these:</p> <pre><code>XY["Count"].unique() array([ 38, 7, 1, 13, 3, 28, 5, 6...
1
2016-09-12T07:14:02Z
39,446,361
<p>I think you get back a float because each row of your dataframe contains a mix of integer and float types. Upon selecting a row index with <code>ix</code> or <code>loc</code>, integers are being converted to floats. To get around this, you could use loc to select from just the required column and not the whole dataf...
0
2016-09-12T08:41:05Z
[ "python", "pandas", "numpy" ]
How to sum values of a row of a pandas dataframe efficiently
39,445,111
<p>I have a <code>python dataframe</code> with 1.5 million rows and 8 columns. I want combine few columns and create a new column. I know how to do this but wanted to know which one is faster and efficient. I am reproducing my code here </p> <pre><code>import pandas as pd import numpy as np df=pd.Dataframe(columns=['A...
2
2016-09-12T07:16:09Z
39,445,186
<p>First method is faster, because is vectorized:</p> <pre><code>df=pd.DataFrame(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]]) print (df) #[30000 rows x 3 columns] df = pd.concat([df]*10000).reset_index(drop=True) df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C'] #similar timings with mul function #df['D1']=df['A...
3
2016-09-12T07:21:06Z
[ "python", "performance", "pandas", "numpy", "vectorization" ]
How to sum values of a row of a pandas dataframe efficiently
39,445,111
<p>I have a <code>python dataframe</code> with 1.5 million rows and 8 columns. I want combine few columns and create a new column. I know how to do this but wanted to know which one is faster and efficient. I am reproducing my code here </p> <pre><code>import pandas as pd import numpy as np df=pd.Dataframe(columns=['A...
2
2016-09-12T07:16:09Z
39,446,173
<p>Using @jezrael's setup</p> <pre><code>df=pd.DataFrame(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]]) df = pd.concat([df]*30000).reset_index(drop=True) </code></pre> <p>Far more efficient to use a <code>dot</code> product.</p> <pre><code>np.array([[.5, .3, .2]]).dot(df.values.T).T </code></pre> <hr> <h3>T...
3
2016-09-12T08:28:45Z
[ "python", "performance", "pandas", "numpy", "vectorization" ]
Does SQLAlchemy's expire_all actually expire cached data?
39,445,203
<p>So, I've read a lot of conflicting reports on how sqlalchemy works. I've read that it doesn't cache queries, etc. None of it seems to match my experience.</p> <p>I'll give an example:</p> <pre><code> &gt;&gt;&gt; x = Session.query(statusStorage).all() &gt;&gt;&gt; for i in x: ... print i.id ... 1 ... - rec...
-1
2016-09-12T07:22:15Z
39,445,445
<p>I answered this on IRC, but the issue is simply that InnoDB's default transaction isolation level is "REPEATABLE READ", which means the second and third query are not permitted (by the database) to see your change.</p>
3
2016-09-12T07:39:20Z
[ "python", "sqlalchemy" ]
Running R script with subprocess on Windows, subprocess seems missing
39,445,422
<p>I am using python on windows. I want to call an R script in my python code.</p> <p>My script R is :</p> <pre><code>c &lt;- 3 print(paste("hello", c)) </code></pre> <p>My python code calls the Rscript like this:</p> <pre><code>import subprocess subprocess.call(['Rscript', "sb.R"]) </code></pre> <p>Unfortunately ...
1
2016-09-12T07:38:03Z
39,447,359
<p>Check your python script and Rscript in are the same file location.</p> <p>Example: Create a file named sb.R and subprocess_demo.py under Desktop location. Change directory to Desktop in command prompt and run following command <strong>python subprocess_demo.py</strong></p> <p><strong><em>sb...
0
2016-09-12T09:36:26Z
[ "python", "windows", "powershell", "subprocess" ]
trouble finding the right django queryset for this
39,445,579
<p>I have two models like this:</p> <pre><code>class Foo(): name = CharField frequency = IntegerField class Bar(): thing = ForeignKey(Foo) content = TextField </code></pre> <p>I want to get a queryset that will be <code>Bar</code> objects sorted by a range of <code>Foo</code> objects. It obviously do...
0
2016-09-12T07:47:37Z
39,447,904
<p>if I am getting right what would you like to achieve, try this:</p> <pre><code>objs = Bar.objects.filter(thing__pk__in=Foo.objects.all().order_by('-frequency').values_list('pk', flat=True)[:10]) </code></pre>
1
2016-09-12T10:07:51Z
[ "python", "django" ]
JAVA interaction with CPython
39,445,593
<p><strong>My Objective:</strong></p> <p>When I run Python (CPython) from command line (not Jython since it does not support some packages like NumPy) I can interactively write lines of code and see results from its output.</p> <p>My objective is to do this programmatically in JAVA. Here is my attempt to do so:</p> ...
0
2016-09-12T07:49:01Z
39,449,515
<p>Direct interaction with Python process is unfortunately not possible. Instead of it is a solution using TCP sockets:</p> <p><strong>PythonServer.java</strong></p> <pre><code>package pythonexample; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PythonServ...
0
2016-09-12T11:42:22Z
[ "java", "python", "process", "cpython" ]
Softlayer API: How to do image capture with specify certain data disk?
39,445,620
<p>I have a vm with disk 1,2,3,4, I want to do some image operations: </p> <ul> <li>Q1: How can i capture the image only contain system disk and disk 3?</li> <li>Q2: If I achieve the image production described in Q1, can I use this image install or reload a vm? How SL api to do with the disk 3 in the image ?</li> <li>...
0
2016-09-12T07:50:16Z
39,451,323
<p>at moment to create the image template you can specify the block devices that you want in the image template you can do that using the API and the portal.</p> <p>this is an example using the API</p> <pre><code>""" Create image template. The script creates a standard image template, it makes a call to the SoftLaye...
0
2016-09-12T13:20:04Z
[ "python", "api", "softlayer" ]
String formatting in output
39,445,758
<p>I have a python script that looks like this:</p> <pre><code> print "Header 1" print "\t Sub-header 1" print "\t\t (*) Sentence 1 begins here and goes on... and ends here." </code></pre> <p>The sentences are being printed in a loop with the similar format, and it gives an output like this in the terminal...
0
2016-09-12T08:00:24Z
39,447,706
<p>with the help of the <a href="https://docs.python.org/2/library/textwrap.html" rel="nofollow">textwrap</a> module, it could be done quite easily:</p> <pre><code>import textwrap LINE_LENGTH = 80 TAB_LENGTH = 8 def indent(text, indent="\t", level=0): return "{}{}".format(indent * level, text) def indent_sente...
1
2016-09-12T09:55:16Z
[ "python", "python-2.7", "formatting", "string-formatting" ]
How can I make python script(X) reload dynamically changing variables in another module(Y) and then re-import updated module(Y) in same script(X)?
39,445,798
<p>I'm new to Python, I'm stuck with a code. I have tried my best to show my problem with below sample code. I'm playing with 4 files.</p> <p>This is the runme file. That I'm running.</p> <p>command > python runme.py</p> <pre><code>import os with open("schooldata.txt", "r") as filestream: #opening schooldata.txt ...
0
2016-09-12T08:03:01Z
39,455,962
<p>Why don't you try to combine the school_info.py and mainfile.py. If you can run a combined loop.</p> <pre><code>import os import schoollib #(internal school lib) with open("schooldata.txt", "r") as filestream: #opening schooldata.txt file for line in filestream: currentline = line.split(",") a ...
0
2016-09-12T17:49:45Z
[ "python", "python-3.x" ]
Lambda function: why do I need a parameter in eventhandlers but not in Button-commands?
39,445,915
<p>In the following case of a Python lambda call, I need to set a parameter for the function to work properly:</p> <pre><code>name = Entry(self.new_jobtile, width=30) ... name.bind('&lt;Return&gt;', lambda x:self.create_tile(name.get())) </code></pre> <p>However, if I use a Button instead, the very same lambda call w...
0
2016-09-12T08:11:51Z
39,446,219
<p>In Python you can create lambda function without arguments:</p> <pre><code>bar = lambda : 4*2 bar() # 8 </code></pre> <p>I do not know what library are you using but I think that in <code>name.bind</code> second argument should be function with one parameter (like <code>lambda x:</code> or <code>def foo(x):</code>...
0
2016-09-12T08:31:17Z
[ "python", "lambda" ]
Lambda function: why do I need a parameter in eventhandlers but not in Button-commands?
39,445,915
<p>In the following case of a Python lambda call, I need to set a parameter for the function to work properly:</p> <pre><code>name = Entry(self.new_jobtile, width=30) ... name.bind('&lt;Return&gt;', lambda x:self.create_tile(name.get())) </code></pre> <p>However, if I use a Button instead, the very same lambda call w...
0
2016-09-12T08:11:51Z
39,446,235
<p>I have no idea about API of that <code>Entry</code> and <code>Button</code> classes, but here is my guess. Probably <code>bind</code> method of the <code>Entry</code> requires a callback function (your lambda) to has one parameter, in other words, somewhere in the <code>bind</code> method can be a piece of code like...
0
2016-09-12T08:32:51Z
[ "python", "lambda" ]
SQLite Query with Python 1
39,445,923
<p>I have generated a list and able to generate the result:</p> <pre><code>l = [2, 3, 5, 2009 ] cur1 = cur.execute('SELECT * from table where + or '.join(('Code = ' + str(n) for n in l))) </code></pre> <p>However, I want to put in another query in the same statement as follows:</p> <pre><code>cur1 = cur.execute('SE...
-1
2016-09-12T08:12:22Z
39,446,238
<p>Your first was false and the second is of course false too.</p> <pre><code>&gt;&gt;&gt; 'SELECT * from table where + or '.join(('Code = ' + str(n) for n in l)) &gt;&gt;&gt; 'Code = 2SELECT * from table where + or Code = 3SELECT * from table where + or Code = 5SELECT * from table where + or Code = 2009' </code></pre...
1
2016-09-12T08:33:01Z
[ "python", "sqlite", "python-3.x", "sqlite3" ]
Python3.5 erorr when import easygui
39,445,931
<p>I got below error when import easygui in Python3.5</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import easygui File "C:\Users\bhongtip\AppData\Local\Programs\Python\Python35-32\lib\site-packages\easygui-0.98.0-py3.5.egg\easygui\__init__.py", line 50, ...
0
2016-09-12T08:13:33Z
39,446,053
<p>EasyGUI 0.98 <a href="https://github.com/robertlugg/easygui/commit/b5eab34c021d1d6eb5e51b67b81da6dbee56e94a" rel="nofollow">introduced a change incompatible with Python 3</a>.</p> <p>You'll need to either downgrade to 0.97.4 (<code>pip install -U EasyGUI==0.97.4</code>) or fix that change.</p> <p>Fixing that line ...
2
2016-09-12T08:21:20Z
[ "python", "easygui" ]
Python Pyqt QComboBox show options
39,445,975
<p>I am trying to create a GUI with button, text box and combo box. I have problems with the combo box. I can create it but once I click on it it does not display the options. I am not getting any error which makes me hard to find the problem. This is the code so far:</p> <pre><code>from PyQt4.QtGui import * from PyQt...
0
2016-09-12T08:16:17Z
39,446,122
<p>You are redefining <code>self.cb</code> here:</p> <pre><code>self.cb = QComboBox() </code></pre> <p>By removing this line it works for me.<br> Both definitions work because of are your <code>import</code> statements. With <code>from PyQt4.QtGui import *</code> you import everythin within the module <code>QtGui</co...
1
2016-09-12T08:25:28Z
[ "python", "pyqt" ]
Kivy--how to bind a function to a checkbox when activated
39,446,148
<p>I have a Python program in wich I use kivy's checkboxes.</p> <p>Is there a way to let the program call a function the instant when the checkbox is disabled/enabled? please note, the active property wont work since this is only once, one would have to use a infinite while loop to check whether the user activated it ...
-1
2016-09-12T08:26:52Z
39,446,291
<p>You could do something like this:</p> <pre><code>from kivy.uix.checkbox import CheckBox </code></pre> <h1>...</h1> <pre><code>def do_something(checkbox, value): # Do something checkbox = CheckBox() checkbox.bind(active=do_something) </code></pre>
1
2016-09-12T08:36:35Z
[ "python", "checkbox", "kivy" ]
In NumPy, how do I set array b's data to reference the data of array a?
39,446,199
<p>Say I have ndarray a and b of compatible type and shape. I now wish for the data of b to be referring to the data of a. That is, without changing the array b object itself or creating a new one. (Imagine that b is actually an object of a class derived from ndarray and I wish to set its data reference after construct...
0
2016-09-12T08:30:29Z
39,448,774
<p>Every variable in python is a pointer so you can use directly <code>=</code> as follow</p> <pre><code>import numpy as np a = np.array([1,2,3]) b = a </code></pre> <p>You can check that <code>b</code> refers to <code>a</code> as follow</p> <pre><code>assert a[1] == b[1] a[1] = 4 assert a[1] == b[1] </code></pre>
0
2016-09-12T10:57:21Z
[ "python", "python-3.x", "numpy" ]
In NumPy, how do I set array b's data to reference the data of array a?
39,446,199
<p>Say I have ndarray a and b of compatible type and shape. I now wish for the data of b to be referring to the data of a. That is, without changing the array b object itself or creating a new one. (Imagine that b is actually an object of a class derived from ndarray and I wish to set its data reference after construct...
0
2016-09-12T08:30:29Z
39,457,690
<p>NumPy does not support this operation. If you controlled the creation of <code>b</code>, you might be able to create it in such a way that it uses <code>a</code>'s data buffer, but after <code>b</code> is created, you can't swap its buffer out for <code>a</code>'s.</p>
1
2016-09-12T19:44:29Z
[ "python", "python-3.x", "numpy" ]
In NumPy, how do I set array b's data to reference the data of array a?
39,446,199
<p>Say I have ndarray a and b of compatible type and shape. I now wish for the data of b to be referring to the data of a. That is, without changing the array b object itself or creating a new one. (Imagine that b is actually an object of a class derived from ndarray and I wish to set its data reference after construct...
0
2016-09-12T08:30:29Z
39,458,085
<p>Usually when functions are not always supposed to create their own buffer they implement an interface like</p> <pre><code>def func(a, b, c, out=None): if out is None: out = numpy.array(x, y) # ... return out </code></pre> <p>that way the caller can control if an existing buffer is used or not.<...
0
2016-09-12T20:11:47Z
[ "python", "python-3.x", "numpy" ]
Python regex with \w does not work
39,446,341
<p>I want to have a regex to find a phrase and two words preceding it if there are two words. For example I have the string (one sentence per line):</p> <blockquote> <p>Chevy is my car and Rusty is my horse. My car is very pretty my dog is red.</p> </blockquote> <p>If i use the regex:</p> <pre><code>re.finditer(...
2
2016-09-12T08:39:41Z
39,446,390
<p>In your <code>r'[\w+\b|^][\w+\b]my car</code> regex, <code>[\w+\b|^]</code> matches 1 symbol that is either a word char, a <code>+</code>, a backdpace, <code>|</code>, or <code>^</code> and <code>[\w+\b]</code> matches 1 symbol that is either a word char, or <code>+</code>, or a backspace.</p> <p>The point is that ...
7
2016-09-12T08:43:01Z
[ "python", "regex", "python-3.x" ]
Unable to import python packages in Ubuntu (ImportError : undefined symbol)
39,446,543
<p>I recently installed python on my Ubuntu 14.04. I downloaded tensorflow by <code>pip</code>. When I tried to <code>import tensorflow</code> it said <code>ImportError:No module named tensorflow</code>. Then I edited <code>PYTHONPATH</code> by adding <code>/usr/local/lib/python2.7/dist-packages</code>. Now when I try ...
0
2016-09-12T08:52:52Z
39,452,302
<p>Best way to install packages if you have more than one python installed is:</p> <pre><code>path_to_your_python_executable -m pip install package_name </code></pre> <p>This way, you can make sure that you have installed package for proper python.</p> <p>And don't forget about sudo ;)</p>
0
2016-09-12T14:07:33Z
[ "python", "python-2.7", "ubuntu", "ubuntu-14.04", "tensorflow" ]
Difference between devpi and pypi server
39,446,579
<p>Had a quick question here, am used to devpi and was wondering what is the difference between devpi and pypi server ?</p> <p>Is on better than another? Which of this one scale better?</p> <p>Cheers</p>
0
2016-09-12T08:55:14Z
39,466,093
<p><strong>PyPI</strong> (Python Package Index)- is the official repository for third-party Python software packages. Every time you use e.g. <code>pip</code> to install a package that is not in the standard it will get downloaded from the PyPI server.</p> <p>All of the packages that are on PyPI are publicly visible....
0
2016-09-13T09:02:23Z
[ "python", "pypi", "devpi", "python-packaging" ]
Find an element in a list with tuple in Python
39,446,607
<p>I have a little complicated data and want to find specific element with <em>key</em> tuple. <em>target</em> tuple is a little different from <em>key</em>, because it has an <em>id</em> property. So I cannot use <strong><em>key in target</em></strong>.</p> <p>So what's the best way to implement smart searching in th...
-3
2016-09-12T08:56:45Z
39,446,927
<p>If the key-value pairs must match exactly, you can use <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects" rel="nofollow"><em>Dictionary view objects</em></a> to treat the key-value pairs as <em>sets</em>. You want to find a <a href="https://docs.python.org/2/library/stdtypes.html#set.i...
2
2016-09-12T09:14:47Z
[ "python", "tuples" ]
tkinter in tkinter makes value disappear (python 3.4.3)
39,446,694
<p>I wrote this piece of code, which is supposed to ask a user if all of his files have the same date and if yes, that he should write his date into a grid. After entering the dates both windows should disappear and i want to keep the date. Unfortunately I don't manage to let the first Input-Box disappear and after thi...
-1
2016-09-12T09:01:51Z
39,447,757
<p>As the outer <code>master</code> variable is re-assigned in the function <code>setdate()</code>, the call <code>master.destroy()</code> will only close the new <code>master</code>, not the outer <code>master</code>. Try modifying the function <code>setdate()</code> as below:</p> <pre><code>def setdate(): def a...
1
2016-09-12T09:58:31Z
[ "python", "tkinter", "python-3.4" ]
ImportError when importing elasticsearch.helpers in Python
39,446,705
<p>I am using a docker container with <strong>Ubuntu 16.04 Xenial</strong> with a <strong>Python 3.5.2</strong> virtual environment. Every time I am trying to initialize the server uWSGI I am getting the following Python error:</p> <pre><code> File "/env/lib/python3.5/site-packages/elasticsearch_dsl/__init__.py", lin...
0
2016-09-12T09:02:09Z
39,457,911
<p>ouch... just a rookie mistake. One of the folders of my project was called elasticsearch and that was causing the issue.</p> <p>Running the following command I found out that my app was simply loading the elasticsearch module from a different location. </p> <pre class="lang-python prettyprint-override"><code>impor...
0
2016-09-12T20:00:08Z
[ "python", "docker", "elasticsearch-py" ]
print dir(XXX) gives out blank attributes
39,446,732
<p>In short, I work with an xlsx file and while checking some list with <code>print dir(alist)</code> get blank attributes.</p> <pre><code>neglist = neglist.tolist() </code></pre> <p>At this point I want to check whether evth is Ok: </p> <pre><code>def check_variab (variab): print "The type is %s" % type(variab...
-2
2016-09-12T09:03:14Z
39,446,808
<p>You forgot to use a <code>%s</code> placeholder, so <em>nothing</em> will be interpolated. Add <code>%s</code> or <code>%r</code>: </p> <pre><code>print "Its attributes are %s:" % dir(variab) # ^^ A placeholder for the value </code></pre> <p>Without that placeholder, you won't see anyth...
0
2016-09-12T09:07:34Z
[ "python", "list", "xlsx" ]
Double for loop in Python3
39,446,881
<p>There is list named L. Which contains others list: L=[A,B,C,...N] I want to for-loop, where B is no equal A (see #2) Something like: for B is not A in L:</p> <pre><code>for A in L: #1 for B in L: #2 </code></pre> <p>How can I do that?</p>
-1
2016-09-12T09:12:36Z
39,446,997
<p>Just access the rest of the list by index:</p> <pre><code>for i in xrange(len(L)-1): for j in xrange(i+1, len(L)): #L[i] != L[j] always, and will check just one list against the others once </code></pre>
0
2016-09-12T09:18:16Z
[ "python", "python-3.x", "permutation" ]
Double for loop in Python3
39,446,881
<p>There is list named L. Which contains others list: L=[A,B,C,...N] I want to for-loop, where B is no equal A (see #2) Something like: for B is not A in L:</p> <pre><code>for A in L: #1 for B in L: #2 </code></pre> <p>How can I do that?</p>
-1
2016-09-12T09:12:36Z
39,461,025
<p>Better solution using <code>itertools</code>, either <a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="nofollow">with <code>permutations</code></a> or <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow">with <code>combinations</code></...
0
2016-09-13T01:37:06Z
[ "python", "python-3.x", "permutation" ]
Double for loop in Python3
39,446,881
<p>There is list named L. Which contains others list: L=[A,B,C,...N] I want to for-loop, where B is no equal A (see #2) Something like: for B is not A in L:</p> <pre><code>for A in L: #1 for B in L: #2 </code></pre> <p>How can I do that?</p>
-1
2016-09-12T09:12:36Z
39,461,063
<p>You can use an <code>if</code> statement to filter out the cases you don't want:</p> <pre><code>for A in L: for B in L: if A == B: continue # skip # do stuff ... </code></pre>
0
2016-09-13T01:43:10Z
[ "python", "python-3.x", "permutation" ]
pyqtgraph: simplest way to pause ipython script until user has placed a roi object
39,446,925
<p>I would like to implement the following sequence in a script and keep it as simple as possible (i.e., if possible avoid explicit multi-threading):</p> <ol> <li><p>Process some data. The result is a 2d numpy array, say <code>a</code></p></li> <li><p>Show <code>a</code> using <code>pw = pg.show(a)</code> (after <code...
0
2016-09-12T09:14:35Z
39,597,226
<h1>1. raw_input('') in an IPython console</h1> <p>If the script is running in an IPython console, you could try adding a </p> <pre><code>raw_input("Press Enter to continue...") </code></pre> <p>or <code>input()</code> in python3 to pause the script. The user has to go back and press enter in the ipython console but...
1
2016-09-20T14:48:06Z
[ "python", "ipython", "jupyter-notebook", "pyqtgraph" ]
Element wise comparison in an array of arrays in Numpy
39,446,944
<p>I have the following array of <code>shape(5,2,3)</code>, which is a collection of <code>2 * 3</code> arrays.</p> <pre><code>a = array([[[ 0, 2, 0], [ 3, 1, 1]], [[ 1, 1, 0], [ 2, 2, 1]], [[ 0, 1, 0], [ 3, 2, 1]], [[-1, 2, 0], [ 4, 1, 1]], [[ 1, 0, 0], [ 2, 3, ...
2
2016-09-12T09:15:28Z
39,447,013
<p>You could do -</p> <pre><code>a[~(a&lt;0).any(axis=(1,2))] </code></pre> <p>Or the equivalent with <code>.all()</code> and thus avoid the <code>inverting</code> -</p> <pre><code>a[(a&gt;=0).all(axis=(1,2))] </code></pre> <p>Sample run -</p> <pre><code>In [35]: a Out[35]: array([[[ 0, 2, 0], [ 3, 1, ...
2
2016-09-12T09:18:51Z
[ "python", "arrays", "numpy", "multidimensional-array", "vectorization" ]
Element wise comparison in an array of arrays in Numpy
39,446,944
<p>I have the following array of <code>shape(5,2,3)</code>, which is a collection of <code>2 * 3</code> arrays.</p> <pre><code>a = array([[[ 0, 2, 0], [ 3, 1, 1]], [[ 1, 1, 0], [ 2, 2, 1]], [[ 0, 1, 0], [ 3, 2, 1]], [[-1, 2, 0], [ 4, 1, 1]], [[ 1, 0, 0], [ 2, 3, ...
2
2016-09-12T09:15:28Z
39,447,024
<p>Use <code>any</code>:</p> <pre><code>In [10]: np.any(a&lt;0,axis=-1) Out[10]: array([[False, False], [False, False], [False, False], [ True, False], [False, False]], dtype=bool) </code></pre> <p>Or more complete, if you want the corresponding index for (2,3) array:</p> <pre><code>In [...
2
2016-09-12T09:19:12Z
[ "python", "arrays", "numpy", "multidimensional-array", "vectorization" ]
How to extract an arbitrary line of values from a numpy matrix?
39,447,041
<p>i want to extract an interpolated straight line between two arbitrary points from a equidistant 3D matrix, such as:</p> <pre><code>data_points_on_line=extract_line_from_3D_matrix(matrix,point1,point2,number_of_data_values_needed) </code></pre> <p>with the 3D matrix <code>matrix</code>, start and end point <code>po...
0
2016-09-12T09:20:23Z
39,450,450
<p>it works for me using InterpolatingFunction, for example:</p> <pre><code>#!/usr/bin/python import numpy as np from Scientific.Functions.Interpolation import InterpolatingFunction def linear_interp_3d(point1,point2,spacing): xi=np.linspace(point1[0],point2[0],spacing) yi=np.linspace(point1[1],point2[1],spa...
0
2016-09-12T12:34:19Z
[ "python", "numpy", "scipy" ]
How can I identify buttons, created in a loop?
39,447,138
<p>I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list of 10x10. Then I created each button using a loop just so I don't have to manually create every single button and clip them on. </p> <pre><code>self.b=[[0 for x in range(1,12)]...
0
2016-09-12T09:24:57Z
39,448,154
<p>Try modifying your code as below:</p> <pre><code>self.b=[[0 for x in range(10)] for y in range(10)] #The 2 dimensional list xp = yp = 0 for i in range(10): for j in range(10): self.b[i][j]=tkinter.Button(root,text=" ",command=lambda i=i,j=j: self.delete(i,j)) # creating the button self.b[i][...
1
2016-09-12T10:22:32Z
[ "python", "tkinter", "minesweeper" ]
How can I identify buttons, created in a loop?
39,447,138
<p>I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list of 10x10. Then I created each button using a loop just so I don't have to manually create every single button and clip them on. </p> <pre><code>self.b=[[0 for x in range(1,12)]...
0
2016-09-12T09:24:57Z
39,448,908
<p>If you just want to destroy the Button widget, the simple way is to add the callback after you create the button. Eg,</p> <pre><code>import Tkinter as tk grid_size = 10 root = tk.Tk() blank = " " * 3 for y in range(grid_size): for x in range(grid_size): b = tk.Button(root, text=blank) b.config...
2
2016-09-12T11:04:45Z
[ "python", "tkinter", "minesweeper" ]
How can I identify buttons, created in a loop?
39,447,138
<p>I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list of 10x10. Then I created each button using a loop just so I don't have to manually create every single button and clip them on. </p> <pre><code>self.b=[[0 for x in range(1,12)]...
0
2016-09-12T09:24:57Z
39,449,125
<p>While creating buttons in a loop, we <em>can</em> create (actually get) the unique identity. </p> <p>For example: if we create a button:</p> <pre><code>button = Button(master, text="text") </code></pre> <p>we can identify it immediately:</p> <pre><code>print(button) &gt; &lt;tkinter.Button object .14027832692237...
1
2016-09-12T11:18:45Z
[ "python", "tkinter", "minesweeper" ]
Is Numpy's argsort deterministic?
39,447,162
<p>Let's say I have a bunch of objects to sort, some of them having the same sorting criteria. Can I be certain <code>numpy.argsort()</code> will yield the same return every time ?</p> <p>For example, If I call <code>argsort([0,0,1])</code>, will it return:</p> <ul> <li><p><code>[0,1,2]</code>?</p></li> <li><p><code>...
1
2016-09-12T09:26:04Z
39,447,202
<p>This is documented for the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html#numpy.sort" rel="nofollow"><code>numpy.sort()</code> function</a> (linked from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow"><code>numpy.argsort()</code> page<...
6
2016-09-12T09:28:22Z
[ "python", "sorting", "numpy" ]
Get only stderr output from subprocess.check_output
39,447,238
<p>I want to run an external process in python, and process its <code>stderr</code> only.</p> <p>I know I can use <code>subprocess.check_output</code>, but how can I redirect the stdout to <code>/dev/null</code> (or ignore it in any other way), and receive only the <code>stderr</code>?</p>
1
2016-09-12T09:30:10Z
39,447,963
<p>Unfortunately you have tagged this <a href="/questions/tagged/python-2.7" class="post-tag" title="show questions tagged &#39;python-2.7&#39;" rel="tag">python-2.7</a>, as in python 3.5 and up this would be simple using <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow"><code>ru...
1
2016-09-12T10:10:46Z
[ "python", "python-2.7", "subprocess", "stderr" ]
Get only stderr output from subprocess.check_output
39,447,238
<p>I want to run an external process in python, and process its <code>stderr</code> only.</p> <p>I know I can use <code>subprocess.check_output</code>, but how can I redirect the stdout to <code>/dev/null</code> (or ignore it in any other way), and receive only the <code>stderr</code>?</p>
1
2016-09-12T09:30:10Z
39,449,965
<p>I found a simple trick:</p> <pre><code>import subprocess stderr_str = subprocess.check_output('command 2&gt;&amp;1 &gt;/dev/null') </code></pre> <p>This will filter out the stdout, and keeps only the stderr.</p>
0
2016-09-12T12:08:41Z
[ "python", "python-2.7", "subprocess", "stderr" ]
Python json schema that extracts parameters
39,447,263
<p>I need to parse requests to a single url that are coming in JSON, but in several different formats. For example, some have timestamp noted as <code>timestamp</code> attr, others as <code>unixtime</code> etc. So i want to create json schemas for all types of requests that not only validate incoming JSONs but also ext...
0
2016-09-12T09:31:37Z
39,449,386
<p>See <a href="http://json-schema.org" rel="nofollow">http://json-schema.org</a></p> <p>This doesn't look like a Python question. </p>
0
2016-09-12T11:34:50Z
[ "python", "json" ]
Python json schema that extracts parameters
39,447,263
<p>I need to parse requests to a single url that are coming in JSON, but in several different formats. For example, some have timestamp noted as <code>timestamp</code> attr, others as <code>unixtime</code> etc. So i want to create json schemas for all types of requests that not only validate incoming JSONs but also ext...
0
2016-09-12T09:31:37Z
39,454,653
<p>The following code may help. It supports nested dict as well.</p> <pre><code>import json def valid_type(type_name, obj): if type_name == "number": return isinstance(obj, int) or isinstance(obj, float) if type_name == "int": return isinstance(obj, int) if type_name == "float": ...
0
2016-09-12T16:16:37Z
[ "python", "json" ]
Equivalent ways to json.load a file in python?
39,447,362
<p>I often see this in code:</p> <pre><code>with open(file_path) as f: json_content = json.load(f) </code></pre> <p>And less often this:</p> <pre><code>json_content = json.load(open(file_path)) </code></pre> <p>I was wondering if the latter is an anti pattern or what the difference between the two versions is.<...
2
2016-09-12T09:36:50Z
39,447,419
<p>When you use a context manager, it guarantees that your file will be close automatically at the end of block. The <a href="https://docs.python.org/3.5/reference/compound_stmts.html#with" rel="nofollow"><code>with</code> statement</a> does this by calling the <code>close</code> attribute of the file object, using its...
1
2016-09-12T09:39:57Z
[ "python", "contextmanager" ]
Equivalent ways to json.load a file in python?
39,447,362
<p>I often see this in code:</p> <pre><code>with open(file_path) as f: json_content = json.load(f) </code></pre> <p>And less often this:</p> <pre><code>json_content = json.load(open(file_path)) </code></pre> <p>I was wondering if the latter is an anti pattern or what the difference between the two versions is.<...
2
2016-09-12T09:36:50Z
39,448,128
<p>In addition to other answers, a context manager is very similar to the try-finally clause.</p> <p>This code:</p> <pre><code>with open(file_path) as f: json_content = json.load(f) </code></pre> <p>can be written as:</p> <pre><code>f = open(file_path) try: json_content = json.load(f) finally: f.close()...
0
2016-09-12T10:21:25Z
[ "python", "contextmanager" ]
Equivalent ways to json.load a file in python?
39,447,362
<p>I often see this in code:</p> <pre><code>with open(file_path) as f: json_content = json.load(f) </code></pre> <p>And less often this:</p> <pre><code>json_content = json.load(open(file_path)) </code></pre> <p>I was wondering if the latter is an anti pattern or what the difference between the two versions is.<...
2
2016-09-12T09:36:50Z
39,449,488
<p><code>json.load(open(file_path))</code> relies on the GC to close the file. That's not a good idea: If someone doesn't use CPython the garbage collector might not be using refcounting (which collects unreferenced objects immediately) but e.g. collect garbage only after some time.</p> <p>Since file handles are close...
1
2016-09-12T11:40:52Z
[ "python", "contextmanager" ]
How to convert non-numeric entries to NaN in read_csv
39,447,559
<p>I am reading in a file with</p> <pre><code>pd.read_csv("file.csv", dtype={'ID_1':float}) </code></pre> <p>The file looks like</p> <pre><code>ID_0, ID_1,ID_2 a,002,c b,004,d c, ,e n,003,g </code></pre> <p>Unfortunately read_csv fails complaining it can't convert ' ' to a float.</p> <p>What is the right...
2
2016-09-12T09:47:19Z
39,447,681
<p>This is my understanding of reading the documentation:</p> <pre><code>def my_func(x): try: converted_value = float(x) except ValueError: converted_value = 'NaN' return converted_value pd.read_csv("file.csv", dtype={'ID_1':float}, converters={'ID_1':my_func}) </code></pre> <p>As i am at...
2
2016-09-12T09:54:07Z
[ "python", "pandas" ]
How to convert non-numeric entries to NaN in read_csv
39,447,559
<p>I am reading in a file with</p> <pre><code>pd.read_csv("file.csv", dtype={'ID_1':float}) </code></pre> <p>The file looks like</p> <pre><code>ID_0, ID_1,ID_2 a,002,c b,004,d c, ,e n,003,g </code></pre> <p>Unfortunately read_csv fails complaining it can't convert ' ' to a float.</p> <p>What is the right...
2
2016-09-12T09:47:19Z
39,447,702
<p>If you don't specify the <code>dtype</code> param and pass <code>skipinitialspace=True</code> then it will just work:</p> <pre><code>In [4]: t="""ID_0,ID_1,ID_2 a,002,c b,004,d c, ,e n,003,g""" pd.read_csv(io.StringIO(t), skipinitialspace=True) Out[4]: ID_0 ID_1 ID_2 0 a 2.0 c 1 b 4.0 d 2 c...
4
2016-09-12T09:55:06Z
[ "python", "pandas" ]
How do I search for a saved fingerprint using sensor R305?
39,447,610
<p><strong>What am I doing?</strong> I have GUI interface built using PyQt, which grants access to the users by validating their Fingerprint.</p> <p>I am using Fingerprint sensor R305, for my module.</p> <p><strong>My issue?</strong> I have my code available on GIT, and it saves the data at a particular ID. But it fa...
1
2016-09-12T09:49:29Z
39,475,777
<p>After going through your code, I get that in your GUI code you are using new() to generate random id values for saving fingerprint template data. But in your search code you are checking the value of r[2] in array [0,1] which is actually your currently stored id list. This is why your search program cant find your f...
1
2016-09-13T17:26:17Z
[ "python", "pyqt", "fingerprint" ]
How to delete column from .csv file without reading the whole file
39,447,644
<p>I generate very big .csv file but now it doesn't fit the RAM. So i decided to delete some inefficient columns to reduce the file size. How can I do that? </p> <p>I tried data = <code>pd.read_csv("file.csv", index_col=0, usecols=["id", "wall"])</code> but it still doesn't fit the RAM.</p> <p>File is about 1.5GB, RA...
0
2016-09-12T09:51:18Z
39,448,247
<p>Instead of deleting columns, you can also read specific columns from csv file using a <code>DictReader</code> (if you're not using <code>Pandas</code> ).</p> <pre><code>import csv from StringIO import StringIO columns = 'AAA,DDD,FFF,GGG'.split(',') testdata ='''\ AAA,bbb,ccc,DDD,eee,FFF,GGG,hhh 1,2,3,4,50,3,20,4...
1
2016-09-12T10:27:45Z
[ "python", "csv", "pandas" ]
How to delete column from .csv file without reading the whole file
39,447,644
<p>I generate very big .csv file but now it doesn't fit the RAM. So i decided to delete some inefficient columns to reduce the file size. How can I do that? </p> <p>I tried data = <code>pd.read_csv("file.csv", index_col=0, usecols=["id", "wall"])</code> but it still doesn't fit the RAM.</p> <p>File is about 1.5GB, RA...
0
2016-09-12T09:51:18Z
39,448,415
<p>I am not sure if this is possible in pandas. You can try to do it in the Command Line. On Linux it will look like: </p> <pre><code>cut -f1,2,5- inputfile </code></pre> <p>if you want to delete columns with indexes 3 and 4.</p>
0
2016-09-12T10:37:33Z
[ "python", "csv", "pandas" ]
How to remove newline characters from csv file
39,447,740
<p>I have the below part of code that reads values from the csv file "prom output.csv" and writes them sorted in a new one "sorted output.csv".</p> <pre><code>import collections import csv with open("prom output.csv","r") as f: cr = csv.reader(f,delimiter=",") d=collections.defaultdict(lambda : list()) he...
0
2016-09-12T09:57:21Z
39,448,049
<p>The Python newline character is, '\n'. Therefore to remove the newline character (and hence the blank lines that are being printed) from your string, try:</p> <pre><code>cr.writerow([k, (",".join(v)), .strip("\n")]) </code></pre>
-1
2016-09-12T10:16:00Z
[ "python", "excel", "csv" ]
How to remove newline characters from csv file
39,447,740
<p>I have the below part of code that reads values from the csv file "prom output.csv" and writes them sorted in a new one "sorted output.csv".</p> <pre><code>import collections import csv with open("prom output.csv","r") as f: cr = csv.reader(f,delimiter=",") d=collections.defaultdict(lambda : list()) he...
0
2016-09-12T09:57:21Z
39,451,664
<p>apparently changing the line: <code>cr = csv.writer(f,lineterminator='\n')</code> into: <code>cr = csv.writer(f,sys.stdout, lineterminator='\n')</code> and adding <code>import sys</code> to the imports solves the problem.</p>
0
2016-09-12T13:37:26Z
[ "python", "excel", "csv" ]
How to remove newline characters from csv file
39,447,740
<p>I have the below part of code that reads values from the csv file "prom output.csv" and writes them sorted in a new one "sorted output.csv".</p> <pre><code>import collections import csv with open("prom output.csv","r") as f: cr = csv.reader(f,delimiter=",") d=collections.defaultdict(lambda : list()) he...
0
2016-09-12T09:57:21Z
39,488,432
<p>This is a simple feasible solution:</p> <pre><code>import collections import csv with open('prom output.csv') as f: header = next(csv.reader(f)) d = collections.OrderedDict() for r in csv.reader(f): try: d[r[0]] += ','+r[1] except: d[r[0]] = ','+r[1] with open('...
0
2016-09-14T10:42:42Z
[ "python", "excel", "csv" ]
Pycharm expected type 'optional[bytes]' got 'str' instead
39,447,741
<p>I am using <code>rsplit</code> to split up a path name, </p> <pre><code>rootPath = os.path.abspath(__file__) rootPath = (rootPath.rsplit('/', 1)[0]).rsplit('/', 1)[0] </code></pre> <p>But <strong>Pycharm</strong> warns,</p> <blockquote> <p>expected type <code>optional [bytes]</code>, got <code>str</code> instea...
2
2016-09-12T09:57:25Z
39,450,149
<p>I'm guessing <code>rootPath</code> is a bytes object and PyCharm is warning you that the <code>sep</code> parameter on <code>rsplit</code> has to either be <code>None</code> or <code>bytes</code>. That's specified in the beginning of the Documentation on <a href="https://docs.python.org/3/library/stdtypes.html#bytes...
1
2016-09-12T12:18:47Z
[ "python", "python-3.x", "split", "pycharm" ]
NameError: global name 'UserProfile' is not defined
39,447,797
<pre><code># getting error while i am running my register user code </code></pre> <p><a href="http://i.stack.imgur.com/QBzxZ.png" rel="nofollow">enter image description here</a></p> <pre><code>from django.shortcuts import render from .forms import * from django.core.context_processors import csrf from django.shortcut...
-3
2016-09-12T10:00:48Z
39,449,995
<p>You must have created class <code>UserProfile</code> in your models.py. You need to import this into your views to get the code working. </p>
0
2016-09-12T12:10:04Z
[ "python", "django" ]
Use module as class instance in Python
39,447,800
<h2>TL; DR</h2> <p>Basically the question is about hiding from the user the fact that my modules have class implementations so that the user can use the module as if it has direct function definitions like <code>my_module.func()</code></p> <h2>Details</h2> <p>Suppose I have a module <code>my_module</code> and a clas...
2
2016-09-12T10:00:55Z
39,447,948
<p>Not Sure why this wouldn't work.</p> <pre><code>say = MyClass().say() from my_module import * say &gt;&gt;Hello! </code></pre>
0
2016-09-12T10:10:04Z
[ "python", "class", "module" ]
Use module as class instance in Python
39,447,800
<h2>TL; DR</h2> <p>Basically the question is about hiding from the user the fact that my modules have class implementations so that the user can use the module as if it has direct function definitions like <code>my_module.func()</code></p> <h2>Details</h2> <p>Suppose I have a module <code>my_module</code> and a clas...
2
2016-09-12T10:00:55Z
39,448,048
<p>In module <code>my_module</code> do the following:</p> <pre><code>class MyThing(object): ... _inst = MyThing() say = _inst.say move = _inst.move </code></pre> <p>This is <em>exactly</em> the pattern used by the <a href="https://github.com/python/cpython/blob/master/Lib/random.py#L736" rel="nofollow"><code>ran...
3
2016-09-12T10:15:59Z
[ "python", "class", "module" ]
Use module as class instance in Python
39,447,800
<h2>TL; DR</h2> <p>Basically the question is about hiding from the user the fact that my modules have class implementations so that the user can use the module as if it has direct function definitions like <code>my_module.func()</code></p> <h2>Details</h2> <p>Suppose I have a module <code>my_module</code> and a clas...
2
2016-09-12T10:00:55Z
39,448,114
<p>You could just replace:</p> <pre><code>def say(): return default_thing.say() </code></pre> <p>with:</p> <pre><code>say = default_thing.say </code></pre> <p>You still have to list everything that's forwarded, but the boilerplate is fairly concise.</p> <p>If you want to replace that boilerplate with something...
2
2016-09-12T10:20:27Z
[ "python", "class", "module" ]
How to write output file in CSV format in python?
39,447,817
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p> <p>Getting error in Python 3.5:</p> <pre><code>wr.writerow(var) TypeError: a bytes-like object is required, not 'str' </code></pre> <p>and </p> <p>In Python 2.7, I am getti...
1
2016-09-12T10:01:57Z
39,447,867
<p>On Python 3, <code>csv</code> <em>requires</em> that you open the file in text mode, not binary mode. Drop the <code>b</code> from your file mode. You should really use <code>newline=''</code> too:</p> <pre><code>resultFile = open("out.csv", "w", newline='') </code></pre> <p>Better still, use the file object as a ...
3
2016-09-12T10:04:56Z
[ "python", "csv" ]
How to write output file in CSV format in python?
39,447,817
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p> <p>Getting error in Python 3.5:</p> <pre><code>wr.writerow(var) TypeError: a bytes-like object is required, not 'str' </code></pre> <p>and </p> <p>In Python 2.7, I am getti...
1
2016-09-12T10:01:57Z
39,447,892
<p>open file without b mode</p> <p>b mode open your file as binary</p> <p>you can open file as w</p> <pre><code>open_file = open("filename.csv", "w") </code></pre>
1
2016-09-12T10:06:41Z
[ "python", "csv" ]
How to write output file in CSV format in python?
39,447,817
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p> <p>Getting error in Python 3.5:</p> <pre><code>wr.writerow(var) TypeError: a bytes-like object is required, not 'str' </code></pre> <p>and </p> <p>In Python 2.7, I am getti...
1
2016-09-12T10:01:57Z
39,448,055
<p>You are opening the input file in normal read mode but the output file is opened in binary mode, correct way</p> <pre><code>resultFile = open("out.csv", "w") </code></pre> <p>As shown above if you replace "wb" with "w" it will work.</p>
1
2016-09-12T10:16:25Z
[ "python", "csv" ]
How to write output file in CSV format in python?
39,447,817
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p> <p>Getting error in Python 3.5:</p> <pre><code>wr.writerow(var) TypeError: a bytes-like object is required, not 'str' </code></pre> <p>and </p> <p>In Python 2.7, I am getti...
1
2016-09-12T10:01:57Z
39,448,412
<p>Others have answered that you should open the output file in text mode when using Python 3, i.e.</p> <pre><code>with open('out.csv', 'w', newline='') as resultFile: ... </code></pre> <p>But you also need to parse the incoming CSV data. As it is your code reads each line of the input CSV file as a single string...
0
2016-09-12T10:37:18Z
[ "python", "csv" ]
Django: AJAX and path params
39,448,032
<p>I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.</p> <p>Say we have an url with a path param that maps to a particular view:</p> <pre><code>url(r'^post/(?P&lt;post_id&gt;\d+)/$', TemplateView.as_view('post.html')) </code></pre> <p>And then the <code...
0
2016-09-12T10:15:06Z
39,448,183
<p>You can pass a post_id variable to django template. However if you don't want it to "hurt", put your .js code (script) in you html file, rendered by django. So you can use django template tags.</p> <p>For example:</p> <pre><code> var url = "/post/{{post_id}}"; $.ajax({ type: 'POST', ...
0
2016-09-12T10:23:59Z
[ "python", "json", "ajax", "django" ]
Django: AJAX and path params
39,448,032
<p>I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.</p> <p>Say we have an url with a path param that maps to a particular view:</p> <pre><code>url(r'^post/(?P&lt;post_id&gt;\d+)/$', TemplateView.as_view('post.html')) </code></pre> <p>And then the <code...
0
2016-09-12T10:15:06Z
39,448,346
<p>To get urls from your template you should use <code>{% url %}</code> template tag, for that you should add a name to your url: </p> <p><code>url(r'^post/(?P&lt;post_id&gt;\d+)/$', TemplateView.as_view('post.html'), name='my_name)</code></p> <p>then in your can template call that url in this way <code>{% url 'my_na...
0
2016-09-12T10:33:14Z
[ "python", "json", "ajax", "django" ]
several forms on the same page with django
39,448,079
<p>i have a very simple model... something like this:</p> <pre><code>class MachineTransTable(models.Model): ... file = models.ForeignKey('File', related_name='the_file') source = models.TextField() target = models.TextField() ... </code></pre> <p>What I'd like to do is to have a page where the use...
0
2016-09-12T10:17:59Z
39,451,224
<p>I think your choice is correct, you should not use <strong>several (hundreds eventually) forms</strong> here if the field in the same model. For two reasons:</p> <ul> <li><p>You have to do a lot of repeat job to write so many forms and that is easy to make mistake and hard to maintain.</p></li> <li><p>You still ha...
0
2016-09-12T13:14:54Z
[ "python", "django", "django-forms", "formset" ]
Python FTP filename invalid error
39,448,121
<p>I'm trying to upload a file using ftp in python, but I get an error saying:</p> <pre><code>ftplib.error_perm: 550 Filename invalid </code></pre> <p>when I run the following code:</p> <pre><code>ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '') ftp.cwd("/incoming") file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb...
0
2016-09-12T10:21:03Z
39,448,185
<p>The argument to STOR needs to be the destination file name, not the source path. You should just do <code>ftp.storbinary('STOR MaxErrors1.json', file)</code>.</p>
0
2016-09-12T10:24:01Z
[ "python", "ftp" ]
Python FTP filename invalid error
39,448,121
<p>I'm trying to upload a file using ftp in python, but I get an error saying:</p> <pre><code>ftplib.error_perm: 550 Filename invalid </code></pre> <p>when I run the following code:</p> <pre><code>ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '') ftp.cwd("/incoming") file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb...
0
2016-09-12T10:21:03Z
39,448,193
<p>The problem is that on the server, the path <code>c:\Automation\FTP_Files\MaxErrors1.json</code> is not valid. Instead try just doing: </p> <pre><code>ftp.storbinary('STOR MaxErrors1.json', file) </code></pre>
1
2016-09-12T10:24:26Z
[ "python", "ftp" ]
Python FTP filename invalid error
39,448,121
<p>I'm trying to upload a file using ftp in python, but I get an error saying:</p> <pre><code>ftplib.error_perm: 550 Filename invalid </code></pre> <p>when I run the following code:</p> <pre><code>ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '') ftp.cwd("/incoming") file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb...
0
2016-09-12T10:21:03Z
39,448,509
<p>you should upload file without absolute path in ftp server for example :</p> <pre><code>import ftplib session = ftplib.FTP('server.address.com','USERNAME','PASSWORD') file = open('kitten.jpg','rb') # file to send session.storbinary('STOR kitten.jpg', file) # send the file file.close() ...
1
2016-09-12T10:42:45Z
[ "python", "ftp" ]
Python parsing an ugly configuration file
39,448,135
<p>I have an application generating a weird config file</p> <pre><code>app_id1 { key1 = val key2 = val ... } app_id2 { key1 = val key2 = val ... } ... </code></pre> <p>And I am struggling on how to parse this in python. The keys of each app may vary too. I can't change the application to generate the configuration fi...
-1
2016-09-12T10:21:39Z
39,448,288
<p>Try something like this:</p> <p>I assumed you read the content of the file to a string</p> <pre><code>config_file_string = '''app_id1 { key1 = val key2 = val key3 = val } app_id2 { key1 = val key2 = val }''' config = {} appid = '' for line in config_file_string.splitlines(): print(line) if line.endswith('...
2
2016-09-12T10:29:38Z
[ "python", "parsing" ]
Python parsing an ugly configuration file
39,448,135
<p>I have an application generating a weird config file</p> <pre><code>app_id1 { key1 = val key2 = val ... } app_id2 { key1 = val key2 = val ... } ... </code></pre> <p>And I am struggling on how to parse this in python. The keys of each app may vary too. I can't change the application to generate the configuration fi...
-1
2016-09-12T10:21:39Z
39,448,322
<p>You could use regex: <code>(\w+)\s*\{([^}]*)</code> will find a <code>name { values }</code> construct, and <code>([^\s=]+)\s*=\s*([^\n]*)</code> will find <code>key = value</code> pairs.</p> <p>As a one-liner, assuming the contents of the file are in the variable <code>s</code>:</p> <pre><code>config= {key:dict(r...
2
2016-09-12T10:31:29Z
[ "python", "parsing" ]
Python parsing an ugly configuration file
39,448,135
<p>I have an application generating a weird config file</p> <pre><code>app_id1 { key1 = val key2 = val ... } app_id2 { key1 = val key2 = val ... } ... </code></pre> <p>And I am struggling on how to parse this in python. The keys of each app may vary too. I can't change the application to generate the configuration fi...
-1
2016-09-12T10:21:39Z
39,451,752
<p>You can use <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> for less strict grammar:</p> <pre><code>from pyparsing import alphanums, restOfLine, OneOrMore, Word, Suppress from copy import copy lbrace,rbrace,eq = map(Suppress,"{}=") configitem = {} configall = {} wd = Word(alphanums+'_') kw...
1
2016-09-12T13:41:42Z
[ "python", "parsing" ]
Simple sijax exapmle dont work
39,448,147
<p>I'm learning Python and Flask, I have very little experience, but something that is impossible. With the usual AJAX does not have any problems, but I decided to try sijax, and even a simple example does not work. I'm sure this is due to incorrect connection and initialization, because I did git clone from the offici...
0
2016-09-12T10:22:09Z
39,539,456
<p>The reason was not working sijax, it was the fact that the {{csrf_token ()}} was not active</p> <p>It is necessary to do so either: <code>&lt;a href="javascript://" onclick="Sijax.request('say_hi', { data: { csrf_token: '{{ csrf_token() }}' } });"&gt;Say Hi!&lt;/a&gt;</code></p> <p>Either connect to the html file:...
0
2016-09-16T20:15:10Z
[ "python", "flask", "sijax" ]
How to install all APT dependencies needed in python project?
39,448,253
<p>I am new to python. And just got a question, I know pip can manage the python package needed in a project, but what about the APT needed in the project?</p>
-2
2016-09-12T10:28:01Z
39,448,605
<p>Off course some python packages require libs or development sources (like MySQLdb). You will not be able to install them without dev libraries (source code) or binary libs and you will be notified about that during pip install. You can easily google error string and check what dependency you miss and install it. Fo...
0
2016-09-12T10:47:58Z
[ "python" ]
assertRaises in unittest not catching Exception properly
39,448,269
<p>I have a file testtest.py that i contains the code</p> <pre><code>import unittest def add(self, a, b): return a + b class Test(unittest.TestCase): def test_additon(self): self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed") #self.assertRaises(TypeError, lambda: add(1 + '1'), m...
0
2016-09-12T10:28:42Z
39,448,348
<p>You should be passing arguments to the callable <em>separately</em>, as separate arguments:</p> <pre><code>self.assertRaises(TypeError, add, 1, '1', msg="Additon failed") </code></pre>
2
2016-09-12T10:33:16Z
[ "python", "unit-testing", "lambda", "python-3.5", "python-unittest" ]
assertRaises in unittest not catching Exception properly
39,448,269
<p>I have a file testtest.py that i contains the code</p> <pre><code>import unittest def add(self, a, b): return a + b class Test(unittest.TestCase): def test_additon(self): self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed") #self.assertRaises(TypeError, lambda: add(1 + '1'), m...
0
2016-09-12T10:28:42Z
39,448,370
<p>Try</p> <pre><code>def test_additon(self): with self.assertRaises(TypeError): add(1 + '1') </code></pre> <p>The problem is that the exception is raised during argument evaluation before self.assertRaises can kick in.</p>
1
2016-09-12T10:34:33Z
[ "python", "unit-testing", "lambda", "python-3.5", "python-unittest" ]
Sort by (unstructured) dates in Pandas DataFrame
39,448,442
<p>I have an Excel table with the following data</p> <p>Please note that I have a single column where the date, month, and time are given in the following format.</p> <p>I wish to sort out the rows with respect to the date and time (i.e Jan-1-1.0, Jan-2-2.0, Jan-1-3.0) and looking for ways to do in Python Pandas Data...
1
2016-09-12T10:39:11Z
39,449,015
<p>OK you can use <a href="https://pypi.python.org/pypi/dateparser" rel="nofollow"><code>dateparser</code></a> to parse your strings and then construct a TimedeltaIndex to add the hour component:</p> <pre><code>In [36]: import dateparser t="""Date-heure Vendredi 03 novembre 10.0 Vendredi 03 novembre 5.0 Vendredi 03 no...
0
2016-09-12T11:11:20Z
[ "python", "python-2.7", "sorting", "pandas", "dataframe" ]
Embed Plotly HTML in PyCharm IDE
39,448,549
<p>I would like to see Plotly's HTML output in the PyCharm IDE. It currently says: </p> <p>Process finished with exit code 0</p> <p>for the output. However, I receive a graphical result in Jupyter</p>
0
2016-09-12T10:44:48Z
39,581,736
<p>To see the Plotly html output use the offline feature. For example, like this:</p> <pre><code>plotly.offline.plot(*yourplotname*, filename='file.html') </code></pre> <p>Run the code in pycharm and it will save the .html file locally in your work folder and open the .html in your browser to view.</p>
1
2016-09-19T20:40:32Z
[ "python", "html", "pycharm", "jupyter", "plotly" ]
Can you dynamically add class variables to subclass python?
39,448,551
<p>I have a large amount of auto-generated classes in python that essentially represent enums for part of a communication protocol, they look like so</p> <pre><code># definitions.py class StatusCodes(ParamEnum): Success = 1 Error = 2 UnexpectedAlpaca = 3 class AlpacaType(ParamEnum): Fuzzy = 0 Rea...
6
2016-09-12T10:44:51Z
39,448,643
<p>Use a class decorator</p> <pre><code>def add_metadata(cls): cls._metadata = get_class_metadata(cls) return cls @add_metadata class StatusCodes(ParamEnum): Success = 1 Error = 2 UnexpectedAlpaca = 3 </code></pre> <p>What you want to do is in fact the very motivation to have decorators: The modi...
5
2016-09-12T10:49:48Z
[ "python", "inheritance" ]
Python Selenium click function does not perform any action, test is not failing
39,448,587
<p>I write automated test in Python using Selenium webdriver and for one element the function click() does not perform any action. But the test does not even fail (e.g. for no such element or not clickable,..)</p> <p>My code:</p> <pre><code>def fill_applications_tab(self): wait = WebDriverWait(self.driver, 20) ...
0
2016-09-12T10:46:41Z
39,489,846
<p>So it started to work when I add another different action after save_button.click() So the code is like:</p> <pre><code>element_xpath.click() save_button.click() navigate_to_another_tab.click() </code></pre> <p>After that the checkbox is chosen and the True is saved</p>
0
2016-09-14T11:55:42Z
[ "python", "selenium", "xpath", "automation", "webdriver" ]
Only passing the first letter into the dictionary. (python 3.x)
39,448,604
<pre><code> print(single_website) print(status_str) print(contact_link) for link, status_code, contact_info in zip(single_website, status_str, contact_link): data = { "Link": link, "Status": status_code, "Contact": contact_info } </code></pre> <p>thi...
-3
2016-09-12T10:47:56Z
39,448,645
<p>because strings are iterable, that is why it takes 1st later in your zip, you should wrap it into tuple or list</p>
0
2016-09-12T10:49:53Z
[ "python", "dictionary" ]
Only passing the first letter into the dictionary. (python 3.x)
39,448,604
<pre><code> print(single_website) print(status_str) print(contact_link) for link, status_code, contact_info in zip(single_website, status_str, contact_link): data = { "Link": link, "Status": status_code, "Contact": contact_info } </code></pre> <p>thi...
-3
2016-09-12T10:47:56Z
39,449,010
<pre><code>&gt;&gt;&gt; single_website = 'http://wizters.com' &gt;&gt;&gt; status_str = '200' &gt;&gt;&gt; contact_link = 'Contact Info Not Available' &gt;&gt;&gt; list(zip(single_website, status_str, contact_link)) [('h', '2', 'C'), ('t', '0', 'o'), ('t', '0', 'n')] &gt;&gt;&gt; list(zip((single_website, ), (status_st...
0
2016-09-12T11:10:57Z
[ "python", "dictionary" ]
Only passing the first letter into the dictionary. (python 3.x)
39,448,604
<pre><code> print(single_website) print(status_str) print(contact_link) for link, status_code, contact_info in zip(single_website, status_str, contact_link): data = { "Link": link, "Status": status_code, "Contact": contact_info } </code></pre> <p>thi...
-3
2016-09-12T10:47:56Z
39,449,169
<pre><code> management_links = [get_management_link(source, soup, single_website)] contact_link = [get_contact_link(source, soup, single_website)] status_str = [str(status)] single_link = [single_website] for link, status_code, management_info, contact_info in zip(single_link, status_str, management_...
0
2016-09-12T11:20:35Z
[ "python", "dictionary" ]
while loop in Python3
39,448,622
<p>This is what I have to do:</p> <blockquote> <p>Create a while-loop that adds 6 to the number 27, 73 times. Answer with the result. </p> <p>Write your code below and put the answer into the variable ANSWER.</p> </blockquote> <p>And this is what I have done, </p> <pre><code>n = 6 while n &lt; 73: 27 + n n ...
-7
2016-09-12T10:48:53Z
39,448,698
<p>While you literally nearly do what was requested (adding 6 to the 27 a number of times), this is not what was wanted.</p> <p>What they want you to do is</p> <blockquote> <p>Initialize a variable with 27 and add 6 to it, 73 times.</p> </blockquote> <p>So just do</p> <pre><code>value = 27 i = 0 while i &lt; 73: ...
3
2016-09-12T10:52:49Z
[ "python", "loops", "while-loop" ]
Django: accessing variable value from TemplateView
39,448,640
<p>Say I have the following url that maps to a <code>TemplateView</code>:</p> <pre><code>url(r'^path/(?P&lt;var1&gt;\d+)/(?P&lt;var2&gt;\d+)/$', TemplateView.as_view('a_view.html')) </code></pre> <p>I thought in the template view <code>a_view.html</code> I could access the values of <code>var1</code> and <code>var2</...
0
2016-09-12T10:49:40Z
39,448,788
<p>From template you can access the instance of <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#django.urls.ResolverMatch" rel="nofollow">ResolverMatch</a> representing the resolved URL</p> <pre><code>&lt;p&gt;var1 value = {{ request.resolver_match.kwargs.var1 }}&lt;/p&gt; &lt;p&gt;var2 value = {{ re...
0
2016-09-12T10:58:19Z
[ "python", "django" ]
Django: accessing variable value from TemplateView
39,448,640
<p>Say I have the following url that maps to a <code>TemplateView</code>:</p> <pre><code>url(r'^path/(?P&lt;var1&gt;\d+)/(?P&lt;var2&gt;\d+)/$', TemplateView.as_view('a_view.html')) </code></pre> <p>I thought in the template view <code>a_view.html</code> I could access the values of <code>var1</code> and <code>var2</...
0
2016-09-12T10:49:40Z
39,448,821
<p>I think something like this should work.</p> <p>Change you urls.py to use a named view:</p> <pre><code>url(r'^path/(?P&lt;var1&gt;\d+)/(?P&lt;var2&gt;\d+)/$', YourNamedView.as_view('a_view.html')) </code></pre> <p>Create a TemplateView and let it grab your vars and add it to the context:</p> <pre><code>class You...
0
2016-09-12T11:00:00Z
[ "python", "django" ]
Parsing date in JSON format using Python
39,448,713
<p>I have a set of news articles in JSON format and I am having problems parsing the date of the data. The problem is that once the articles were converted in JSON format, the date successfully got converted but also did the edition. Here is an illustration:</p> <pre><code>{"date": "December 31, 1995, Sunday, Late Edi...
2
2016-09-12T10:53:48Z
39,448,874
<p>You can split column <code>date</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a>, concanecate first and second column - <code>month</code>, <code>day</code> and <code>year</code> together (<code>December 31</code> and <co...
2
2016-09-12T11:02:47Z
[ "python", "json", "parsing", "datetime", "pandas" ]
Only one usage of each socket address is normally permitted Python
39,448,720
<p>I wrote a basic program in to create a socket with a server and a client. But the problem is that when I run the code, it gives me an error saying that only one usage of each socket address is normally permitted. So I think the problem is due to the port, I changed the port and it still don't work. How do I get this...
0
2016-09-12T10:54:13Z
39,448,814
<p>I think there's a fundamental misunderstanding of how sockets work here.</p> <p>The <a href="https://docs.python.org/2/library/socket.html#socket.socket.bind" rel="nofollow"><code>socket.bind()</code></a> call is used to bind to a particular port on a particular interface, the pair specified using a network address...
1
2016-09-12T10:59:36Z
[ "python", "sockets" ]
Only one usage of each socket address is normally permitted Python
39,448,720
<p>I wrote a basic program in to create a socket with a server and a client. But the problem is that when I run the code, it gives me an error saying that only one usage of each socket address is normally permitted. So I think the problem is due to the port, I changed the port and it still don't work. How do I get this...
0
2016-09-12T10:54:13Z
39,448,823
<p>Rather than </p> <pre><code>&gt; connection_to_server.bind(('localhost',3200)) </code></pre> <p>you should have </p> <pre><code>connection_to_server.connect(('localhost',3200)) </code></pre>
0
2016-09-12T11:00:10Z
[ "python", "sockets" ]
Only one usage of each socket address is normally permitted Python
39,448,720
<p>I wrote a basic program in to create a socket with a server and a client. But the problem is that when I run the code, it gives me an error saying that only one usage of each socket address is normally permitted. So I think the problem is due to the port, I changed the port and it still don't work. How do I get this...
0
2016-09-12T10:54:13Z
39,448,830
<p>For SOCK_STREAM sockets, your client should connect, not bind. From the <a href="https://docs.python.org/2/howto/sockets.html" rel="nofollow">Sockets HOWTO</a>:</p> <pre><code>import socket connection_to_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) connection_to_server.connect(('localhost',3200)) msg =...
0
2016-09-12T11:00:24Z
[ "python", "sockets" ]
Python - File to Dictionary with specific substrings for key value pairs
39,448,760
<p>I have a text file that looks like :</p> <pre><code>AAAAA123123423452452BBBASDASAS323423423432 BBBBB453453453466123AAAAADDFFG6565656565665 </code></pre> <p>...</p> <p>I want to create a dictionary out of this, with keys the slices of each line like this :</p> <p>file.txt :</p> <pre><code>hash[123123] = "BBBASD"...
0
2016-09-12T10:56:27Z
39,448,861
<p>You should use:</p> <pre><code>myhash = {} with open('file.txt') as fi: for line in fi.readlines(): key = line[5:11] value = line[20:26] myhash[key] = value print(myhash) </code></pre> <p>You can get <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">mo...
2
2016-09-12T11:02:10Z
[ "python", "compare", "comparison", "substring" ]
When we submit a form, what happened?
39,448,872
<p>Actually, I just want to get a very simple web application:</p> <ol> <li>a form in a webpage that I can upload a file within some parameters;</li> <li>submit the form when I choose a proper file;</li> <li>do some calculation using these parameters in uploaded file;</li> <li>redirect to a new webpage with the calcul...
0
2016-09-12T11:02:43Z
39,448,957
<p>The problem is that your form is posting directly to the result view. This means that the calculations that happen on POST in your index view are never called, and the result value is always empty.</p> <p>Your form should post to just <code>/index/</code>, or even better to <code>{% url "index_view" %}</code>; and ...
1
2016-09-12T11:07:50Z
[ "python", "django" ]
When we submit a form, what happened?
39,448,872
<p>Actually, I just want to get a very simple web application:</p> <ol> <li>a form in a webpage that I can upload a file within some parameters;</li> <li>submit the form when I choose a proper file;</li> <li>do some calculation using these parameters in uploaded file;</li> <li>redirect to a new webpage with the calcul...
0
2016-09-12T11:02:43Z
39,449,958
<p>Q1: urls.py only maps the urls to the views used to render them. When you submit a form to <code>/index/result/</code>, Django will try to find a view, that matches the url, in this case <code>results_view</code>.</p> <p>Q2: Instead of passing the result from <code>index_view</code> to <code>result_view</code>, you...
1
2016-09-12T12:07:49Z
[ "python", "django" ]
Is it possible to catch data streams other than stdin, stdout and stderr in a Popen call?
39,448,884
<p>I am working on incorporating a program (samtools) into a pipeline. FYI samtools is a program used to manipulate DNA sequence alignments that are in a SAM format. It takes input and generates an output file via stdin and stdout, so it is quite easily controlled via pythons subprocess.Popen().</p> <p>When it runs, i...
0
2016-09-12T11:03:37Z
39,449,018
<p>There is no other console output than stdout and stderr (assuming that samtools does not write to the terminal directly via a tty device). So, if the output is not captured with the subprocesses stdout, it must have been written to stderr, which can be captured as well using <code>Popen()</code> with <code>stderr=su...
2
2016-09-12T11:11:38Z
[ "python", "stream", "subprocess", "stdout", "stderr" ]
(Python) Generating Numbers then Printing them on One Line
39,449,026
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p> <p>This is my code below:</p> <pre><code...
-1
2016-09-12T11:12:07Z
39,449,063
<p>To convert numbers to a string for concatenation use <code>str()</code>.</p> <pre><code>print str(number1) + ", " + str(number2) </code></pre> <p>or using natural delimiter</p> <pre><code>print number1, number2 </code></pre> <p><em>(The <code>,</code> tells python to output them one after the other with space. <...
1
2016-09-12T11:14:25Z
[ "python", "random", "numbers", "sum" ]
(Python) Generating Numbers then Printing them on One Line
39,449,026
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p> <p>This is my code below:</p> <pre><code...
-1
2016-09-12T11:12:07Z
39,449,073
<p>Try this, </p> <pre><code>print number1, '+', number2 </code></pre>
1
2016-09-12T11:15:09Z
[ "python", "random", "numbers", "sum" ]
(Python) Generating Numbers then Printing them on One Line
39,449,026
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p> <p>This is my code below:</p> <pre><code...
-1
2016-09-12T11:12:07Z
39,449,150
<p>Your following line first computes the sum of the two numbers, then prints it</p> <pre><code>print (number1 + number2) </code></pre> <p>you have to print a string:</p> <pre><code>print(str(number1) + " + " + str(number2)) </code></pre> <hr> <p>or prefer formating features instead of concatenation:</p> <pre><co...
1
2016-09-12T11:19:55Z
[ "python", "random", "numbers", "sum" ]
(Python) Generating Numbers then Printing them on One Line
39,449,026
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p> <p>This is my code below:</p> <pre><code...
-1
2016-09-12T11:12:07Z
39,449,159
<p>This should do the job:</p> <pre><code>from random import randint for i in range(10): num1 = randint(0,20) num2 = randint(0,20) answer = input('Sum of %i + %i?: ' % (num1,num2) </code></pre> <p>Perhaps you know what to do with the rest? (e.g. handling the answer section)</p>
0
2016-09-12T11:20:13Z
[ "python", "random", "numbers", "sum" ]