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
Testing ModelSerializers
39,180,100
<p>I am trying to learn the best way to test my serializers but having some issues. In the below example I am testing to see if creating new users works correctly. ie can hash the password. The error i am getting is:</p> <blockquote> <p>TypeError: create() missing 1 required positional argument: 'validated_data'</...
0
2016-08-27T10:29:43Z
39,201,791
<p>You called <code>create</code> in your test. You should call <code>is_valid</code> and then <code>save</code>.</p> <pre><code>user = UserSerializer(data=data, context=self.serializer_context) user.is_valid(raise_exception=True) user.save() </code></pre>
0
2016-08-29T08:33:09Z
[ "python", "django", "django-rest-framework" ]
Python, bs4: Tags in inspection are nowhere to be found when parsing
39,180,183
<p>I run into an unexpected problem, I am using Python 3.5 and BeautifulSoup. I want to parse the following link:</p> <pre><code>url = 'https://www.leboncoin.fr/chaussures/627533472.htm?ca=16_s' import requests, bs4 res = requests.get(url) res.raise_for_status() DicoSoup = bs4.BeautifulSoup(res.text, "lxml") </code></...
1
2016-08-27T10:39:36Z
39,180,247
<p>As I commented the thumbnails are dynamically generated using JS but you can get the script and parse the paths:</p> <pre><code>soup = BeautifulSoup(requests.get("https://www.leboncoin.fr/chaussures/627533472.htm?ca=16_s").content) script = soup.select_one("div.thumbnails").find_next("script") print(script.text.st...
1
2016-08-27T10:47:55Z
[ "python", "parsing", "tags", "beautifulsoup" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</...
0
2016-08-27T10:48:04Z
39,180,261
<p>You can use <a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow">filter</a></p> <pre><code>&gt;&gt;&gt; mylist = [1,2,1,2,1,2,3,4,5,1,2,3] &gt;&gt;&gt; filter(lambda x:x!=2, mylist) [1, 1, 1, 3, 4, 5, 1, 3] </code></pre> <p>Or simple list comprehension.</p> <pre><code>my_list = [i for...
3
2016-08-27T10:49:37Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</...
0
2016-08-27T10:48:04Z
39,180,278
<pre><code>mylist = [x for x in mylist if x != 2] </code></pre> <p>This is simpler than a filter.</p>
1
2016-08-27T10:51:20Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</...
0
2016-08-27T10:48:04Z
39,180,279
<p>Using a list comprehension is probably the most pythonic way of doing this:</p> <pre><code>mylist = [number for number in mylist if number != 2] </code></pre> <p>This is because <code>list.remove(x)</code> only removes the first occurrence of <code>x</code> in the list. The above solution will create a new list ba...
1
2016-08-27T10:51:30Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</...
0
2016-08-27T10:48:04Z
39,180,286
<p><a href="https://docs.python.org/3.5/tutorial/datastructures.html" rel="nofollow">According to docs</a>, this behavior is expected:</p> <blockquote> <p><code>list.remove(x)</code></p> <p><strong>Remove the first item from the list whose value is x</strong>. It is an error if there is no such item.</p> </bloc...
1
2016-08-27T10:52:03Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</...
0
2016-08-27T10:48:04Z
39,180,363
<p>From python help:</p> <pre><code>help(list.remove) </code></pre> <p>you can get this explanation:</p> <blockquote> <p>L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present.</p> </blockquote> <p>You can achieve it by using list comprehension:</p> <pre><code>my...
1
2016-08-27T11:00:15Z
[ "python", "python-2.7" ]
Python List and remove a variable
39,180,248
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p> <pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3] print mylist mylist.remove(2) print mylist </code></pre> <p>It is supposed to remove 2 from the list. It does but the first one only. The output is like:</...
0
2016-08-27T10:48:04Z
39,180,396
<p>another way(if you wont create new list):</p> <pre><code>while 2 in mylist: mylist.remove(2) </code></pre>
0
2016-08-27T11:04:25Z
[ "python", "python-2.7" ]
Finding solution of differential equation
39,180,301
<p>I want to find a root X of equation below</p> <p><a href="http://i.stack.imgur.com/CClq1.png" rel="nofollow"><img src="http://i.stack.imgur.com/CClq1.png" alt="equation"></a></p> <p>Given Ls is length of something,f is frequency, X is a function of frequency, tgn is group delay and λ_0 is free space wavelength. I...
0
2016-08-27T10:53:49Z
39,202,795
<p>If you want to solve a differential equation, you need some initial state information. Then you can either write your own solver, simplest solution would probably be explicit euler, alternatively you can look into this:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html#...
0
2016-08-29T09:28:32Z
[ "python", "scipy", "differential-equations" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want t...
0
2016-08-27T10:57:03Z
39,180,411
<p>You can make use of both <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> and <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a>, simply like this:</p> <pre><code>string = "week32_Aug_24_2016" o...
4
2016-08-27T11:05:31Z
[ "python" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want t...
0
2016-08-27T10:57:03Z
39,180,560
<pre><code>str = "week32_Aug_24_2016" wk = str.split('_') i=0; newstr=""; while(i&lt;len(wk)): newstr=newstr+wk[i]+" " i=i+1 print newstr </code></pre> <p><strong>Something like that. If you want to keep last string in the middle it can be done.</strong></p>
0
2016-08-27T11:20:54Z
[ "python" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want t...
0
2016-08-27T10:57:03Z
39,180,655
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; string = "week32_Aug_24_2016" &gt;&gt;&gt; re.sub(r'_(.*)_(.*)_(.*)', r' \3 \1 \2', string) 'week32 2016 Aug 24' </code></pre>
0
2016-08-27T11:32:20Z
[ "python" ]
Re format a python string after splitting
39,180,334
<p>I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this. </p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2] </code></pre> <p>My expected output is "week32 2016 Aug 24". I already got that but I want t...
0
2016-08-27T10:57:03Z
39,180,680
<p>You can make use str.split() and format() as well:</p> <pre><code>str = "week32_Aug_24_2016" wk = str.split('_') newstr = "{} {} {} {}".format(wk[0], wk[3], wk[1], wk[2]) </code></pre>
0
2016-08-27T11:35:01Z
[ "python" ]
Storm missing resources folder when deploying JAR topology
39,180,503
<p>I'm trying to deploy a topology that uses a MultiLang Bolt (written in Python):</p> <pre><code>builder.setBolt("avro-parser", new AvroBolt(), 3).shuffleGrouping("main-kafka-spout"); builder.setBolt("nlp-analyzer", new NLPBolt("/python/analyzer/audio_parser.py"), 2).shuffleGrouping("avro-parser"); </code></pre> <p>...
1
2016-08-27T11:15:31Z
39,184,888
<p>So, this is basically what I did to get it working:</p> <ol> <li>Create folder ${basedir}/multilang/resources --> copy python code inside.</li> <li>Remove python code from ${basedir}/src/main/resources and leave only the Avro schemes.</li> <li>Add to the build.sbt file:</li> </ol> <blockquote> <p>unmanagedResour...
1
2016-08-27T19:23:08Z
[ "java", "python", "sbt", "apache-storm" ]
Textblob module in python is not working for me
39,180,551
<p>Here is the code...</p> <pre><code>import textblob While True: print("Ok...") print("Enter the text....") text = input() blob = textblob.TextBlob(text) blob.translate(to = "de") </code></pre> <p>It ask for text and then tells me Nothing. Any help is appreciated! </p>
-1
2016-08-27T11:20:05Z
39,181,558
<p>Here's a working example:</p> <pre><code>import textblob while True: text = input("Which text you want to translate:") blob = textblob.TextBlob(text) print("--&gt; {0}".format(blob.translate(to = "de"))) </code></pre> <p>You forgot to print the German translated string</p>
1
2016-08-27T13:16:00Z
[ "python" ]
How to display parent table columns in django template
39,180,566
<p>I have two models in django as below:</p> <pre><code>class Directorates(models.Model): entrydate = models.DateTimeField(auto_now=True) directoratename = models.CharField("Directorate", max_length=1000) note = models.CharField("Note", max_length=2000, null=True) insertedby = models.IntegerField(null=False) ...
0
2016-08-27T11:21:34Z
39,181,113
<p>You're making things harder for yourself by using a <code>values()</code> query. Just pass the objects themselves:</p> <pre><code>departments = Departments.objects.filter(deletedby=0) </code></pre> <p>and now you can do:</p> <pre><code>{% for d in data %} &lt;tr&gt; &lt;td&gt;{{ d.departmentname }}&lt;/td&g...
0
2016-08-27T12:24:05Z
[ "python", "django", "django-models", "django-forms", "django-templates" ]
SQLAlchemy Build selectable query with multiple tables
39,180,608
<p>I created a materialized view for my flask web application with the help of <a href="http://www.jeffwidman.com/blog/847/using-sqlalchemy-to-create-and-manage-postgresql-materialized-views/" rel="nofollow">Jeff Widman</a>.</p> <p>Unfortunately he only describe how to join two tables. I would like to create a materia...
2
2016-08-27T11:26:47Z
39,182,008
<p>Just add another join</p> <pre><code>select_from(db.join(Table1, Table2, isouter=True).join(Table3, isouter=True)) </code></pre>
1
2016-08-27T14:04:06Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
ImportError: No module named 'cryptography'
39,180,609
<p>I installed python 3.4 on windows 7 and when trying to use paramiko I get this error :</p> <pre><code>import paramiko File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\__init__.py", line 30, in module File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\transport.py", line 32,...
1
2016-08-27T11:26:48Z
39,180,737
<p>It's not <a href="https://pypi.python.org/pypi/pycrypto" rel="nofollow">pycrypto</a> the package you need in order to import paramiko, try this:</p> <blockquote> <p>pip install <a href="https://pypi.python.org/pypi/paramiko/" rel="nofollow">paramiko</a></p> </blockquote>
2
2016-08-27T11:41:22Z
[ "python", "windows", "paramiko" ]
ImportError: No module named 'cryptography'
39,180,609
<p>I installed python 3.4 on windows 7 and when trying to use paramiko I get this error :</p> <pre><code>import paramiko File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\__init__.py", line 30, in module File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\transport.py", line 32,...
1
2016-08-27T11:26:48Z
39,180,780
<p>You need to install the <a href="https://pypi.python.org/pypi/cryptography" rel="nofollow">cryptography module</a>.</p> <p>Normally, dependencies would've automatically got pulled in when you install paramiko using a package manager like pip. How did you install paramiko? Are you installing manually? </p>
0
2016-08-27T11:46:03Z
[ "python", "windows", "paramiko" ]
ImportError: No module named 'cryptography'
39,180,609
<p>I installed python 3.4 on windows 7 and when trying to use paramiko I get this error :</p> <pre><code>import paramiko File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\__init__.py", line 30, in module File "C:\Python34\lib\site-packages\paramiko-2.0.2-py3.4.egg\paramiko\transport.py", line 32,...
1
2016-08-27T11:26:48Z
39,194,068
<p>It turned out that it was a proxy problem. It was blocking download. I did </p> <pre><code>pip install cryptography pip install paramiko </code></pre> <p>from a direct internet connection and it worked. Thanks everyone !</p>
0
2016-08-28T17:38:42Z
[ "python", "windows", "paramiko" ]
Loop through array stops increasing index (Orig: Message widget text randomly not refreshing)
39,180,689
<p>I have an automatically generated report in txt file that gets update every 5 or so seconds and looks like this:</p> <pre><code>Report Data Start Time:;00:00 25/08/2016Report;Va1;Val2;Val3;Val4;Val5;Val6;Val7 X;6;4;0;0;32;3;0.8125 Y;2;1;0;0;0;0;0 Z;5;1;0;0;0;0;0 [empty last line] </code></pre> <p>In tkinter, I cre...
0
2016-08-27T11:35:58Z
39,186,132
<p>I believe your problem lies in the incorrect use of the <code>for</code> loop, specifically</p> <pre><code>for sSkItem in SkItems: iSkCol = SkItems.index(sSkItem)+1 </code></pre> <p>Will give you index of <em>first occurence</em> of <code>sSkItem</code> in <code>SkItems</code> and NOT the index of current item...
0
2016-08-27T21:59:55Z
[ "python", "tkinter", "widget", "refresh" ]
speech_recognition module stuck in "say something" - python
39,180,695
<p>I am trying a python script for speech recognition, i have installed the required pyaudio and SpeechRecognition modules in my enivronment.</p> <p>The program was running fine till yesterday, but now it is stuck in "say something". Below is my code.</p> <pre><code>import speech_recognition as sr print "say somethin...
1
2016-08-27T11:36:53Z
39,189,620
<p>I have had the same problem with me, i ended up installing jack2d and pulseaudio and what not.</p> <p>That was the problem, I then uninstalled the jack2d by running </p> <pre><code>sudo apt-get remove --auto-remove jack </code></pre> <p>Then restarted the system, and then ran </p> <pre><code>jack_control stop ...
0
2016-08-28T09:05:55Z
[ "python", "python-2.7", "speech-recognition" ]
speech_recognition module stuck in "say something" - python
39,180,695
<p>I am trying a python script for speech recognition, i have installed the required pyaudio and SpeechRecognition modules in my enivronment.</p> <p>The program was running fine till yesterday, but now it is stuck in "say something". Below is my code.</p> <pre><code>import speech_recognition as sr print "say somethin...
1
2016-08-27T11:36:53Z
39,231,994
<p>When I tried your code as it is I got following <code>attribute</code> error.</p> <pre><code>AttributeError: 'Recognizer' object has no attribute 'recognize' </code></pre> <p>Upon going through <a href="https://pypi.python.org/pypi/SpeechRecognition/" rel="nofollow">documentation</a> it looks like the <code>Recog...
2
2016-08-30T15:47:22Z
[ "python", "python-2.7", "speech-recognition" ]
Product of two equals numpy arrays are different
39,180,779
<p>I'm facing very strange problem with arrays in python and numpy. First of all what Im trying to archive is : </p> <p>1) Get an MxN matrix from KxTxN matrix 2) Transpose this matrix and calculate product of this transposed matrix and the original one</p> <p>What I get is some what strange, here comes the code : </...
0
2016-08-27T11:45:50Z
39,181,052
<p>As @Aguy said, your problem comes from the data-type of your array. The dot product of a uint8 array with an other uint8 array gives an array that is also uint8 hence the data-type is overflowed in your case. Here's an example that shows the effect of overflow on your values:</p> <pre><code>import numpy as np a = ...
3
2016-08-27T12:17:14Z
[ "python", "arrays", "numpy" ]
python: mutually exclusive positional arguments
39,180,785
<p>I want my program to accept mutually exclusive positional arguments, <em>and</em> the usage to be displayed as a group of arguments.<br> Currently I could only achieve one or the other, but not both... </p> <p>This is what I currently have: </p> <pre><code>def parse_arguments(): arg_parser = argparse.Argumen...
3
2016-08-27T11:46:24Z
39,183,029
<p>In the first scenario, you could give <code>-p</code> choices</p> <pre><code>build_parser.add_argument('-p', '--project', action = 'store', # default required = True, choices = ['project_A','project_B','project_C'], # type = project_name, # doesn't ma...
0
2016-08-27T15:58:01Z
[ "python", "argparse" ]
What's the use of "flag" in pandas
39,180,793
<p>When i was training with an exercise for predictive modeling, I couldn't understand the use of flags. I googled it but I couldn't find the best explanation.</p> <pre><code>train = pd.read_csv('C:/Users/Analytics Vidhya/Desktop/challenge/Train.csv') test = pd.read_csv('C:/Users/Analytics Vidhya/Desktop/challenge/Tes...
1
2016-08-27T11:47:36Z
39,181,128
<p>I guess it's easier and faster to show it as an example:</p> <pre><code>In [102]: train = pd.DataFrame(np.random.randint(0, 5, (5, 3)), columns=list('abc')) In [103]: test = pd.DataFrame(np.random.randint(0, 5, (3, 3)), columns=list('abc')) In [104]: train Out[104]: a b c 0 3 4 0 1 0 0 1 2 2 4 1 3 ...
2
2016-08-27T12:26:30Z
[ "python", "pandas", "flags" ]
Pandas dataframe: ValueError: num must be 1 <= num <= 0, not 1
39,180,873
<p>I am getting the following error while I am trying to plot a <code>pandas dataframe</code>:</p> <blockquote> <p>ValueError: num must be 1 &lt;= num &lt;= 0, not 1</p> </blockquote> <p>Code:</p> <pre><code>import matplotlib.pyplot as plt names = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety'] cust...
1
2016-08-27T11:56:01Z
39,181,446
<p>So I'm pretty sure your issue is something to do with the format of the array train_x. I tried your program with an array of 10,000 rows and 6 cols and it worked fine so the issue is not size. For some reason, one of <code>len(x_train)</code> or <code>len(x_train[0])</code> is 0. What makes me think this is thus:</p...
1
2016-08-27T13:01:30Z
[ "python", "pandas", "histogram" ]
Python threading sync
39,180,883
<p>I have a base class that has an empty method called <code>Update</code>. This <code>Update</code> method is inherited by X amount of different subclasses The base class calls the <code>Update</code> method once every 30 ticks (right now it's not. It's just doing it in a loop right now, but I plan to make it get call...
0
2016-08-27T11:57:38Z
39,181,041
<p>What you need is a <code>semaphore</code>, which is a multi-threaded lock object. <a href="https://en.wikipedia.org/wiki/Semaphore_(programming)" rel="nofollow">https://en.wikipedia.org/wiki/Semaphore_(programming)</a>.</p> <p>You sometimes see the same principle in kindergarten or pre-schools where to go to the to...
1
2016-08-27T12:16:25Z
[ "python", "multithreading", "class" ]
ValueError: need more than 2 values to unpack
39,181,014
<p>I am doing this operation:</p> <pre><code>for model, dict in fullCostDict.items(): if dict['cost_matrix']: for i, (costDict, normalCostDict, normalCostDict1, normalCostDict2,normalCostDict3,normalCostDict4) in enumerate( zip(dict['cost_matrix'], dict['normalised_matrix'],dic...
0
2016-08-27T12:12:39Z
39,181,068
<p>You are missing a paranthesis in last <code>for</code> loop. Though you expect a <code>count</code> and a tuple of tuples, you are getting a bunch of tuple. So, the fix would be adding a pair of <code>()</code> over the tuples.</p> <pre><code> for count, ((lb, cost),(lb1, cost1),(lb2, cost2),(lb3, co...
1
2016-08-27T12:18:46Z
[ "python", "loops", "dictionary", "zip", "enumerate" ]
Python print next line while printing from for loop
39,181,088
<p>I am performing a for loop on a list and would like to find a match and print the next line. However, when I try to use the next() method I keep getting a failure. Can I please get some help in extracting the next line after a specified match?</p> <p>string (for loop output):</p> <pre><code>item_0 0 item_1 0 ...
0
2016-08-27T12:21:44Z
39,181,121
<p><code>line</code> is a <code>lxml.etree._ElementStringResult</code> (a modified <code>str</code>) in your code. <code>lxml.etree._ElementStringResults</code> do not have a <code>next</code> method which is why you are getting an <code>AttributeError</code>. </p> <p>You can set a flag indicating that the next line s...
2
2016-08-27T12:25:18Z
[ "python", "match" ]
Python print next line while printing from for loop
39,181,088
<p>I am performing a for loop on a list and would like to find a match and print the next line. However, when I try to use the next() method I keep getting a failure. Can I please get some help in extracting the next line after a specified match?</p> <p>string (for loop output):</p> <pre><code>item_0 0 item_1 0 ...
0
2016-08-27T12:21:44Z
39,181,151
<p>Haven't tested this, but try:</p> <pre><code>result = tree.xpath('//tr/td/font/text()') iter_result = iter(result) for line in iter_result: if 'item_3' in line: print(next(iter_result)) </code></pre>
1
2016-08-27T12:29:41Z
[ "python", "match" ]
Changing variable on another module for functions
39,181,091
<p>I have made two py files, in which <strong>main.py</strong> contains:</p> <pre><code>import module module.Print("This should not appear.") module.Silence = False module.Print("This should appear.") </code></pre> <p>The module imported is <strong>module.py</strong> which contains:</p> <pre><code>Silence = True ...
0
2016-08-27T12:21:55Z
39,181,210
<p>The issue is that you've defined your <code>Print</code> function with a default argument of True (since <code>Silent == True</code> when this module is imported, and the function created). Changing the module variable, <code>Silent</code> to False later isn't going to affect this function definition in any way. I...
1
2016-08-27T12:36:03Z
[ "python", "python-3.x", "variables", "import" ]
Changing variable on another module for functions
39,181,091
<p>I have made two py files, in which <strong>main.py</strong> contains:</p> <pre><code>import module module.Print("This should not appear.") module.Silence = False module.Print("This should appear.") </code></pre> <p>The module imported is <strong>module.py</strong> which contains:</p> <pre><code>Silence = True ...
0
2016-08-27T12:21:55Z
39,192,340
<p>I think you are looking for a function with a default setting that can be dynamically changed. This will use the global <code>Silence</code> only if the <code>sil</code> argument is omitted in <code>Print()</code> function call.</p> <pre><code>def Print(input, sil=None): if sil is None: sil = Silence ...
0
2016-08-28T14:32:20Z
[ "python", "python-3.x", "variables", "import" ]
Do locally set Cython compiler directives affect one or all functions?
39,181,180
<p>I am working on speeding up some Python/Numpy code with Cython, and am a bit unclear on the effects of "locally" setting (as defined <a href="http://docs.cython.org/en/latest/src/reference//compilation.html" rel="nofollow">here</a> in the docs) compiler directives. In my case I'd like to use:</p> <pre><code>@cython...
2
2016-08-27T12:32:44Z
39,181,291
<p>The manual does not say explicitly, but these directives are using <a href="https://www.python.org/dev/peps/pep-0318/" rel="nofollow">decorator notation</a>. In plain Python,</p> <pre><code>@decorator2 @decorator1 def fn(args): body </code></pre> <p>is syntactic sugar for</p> <pre><code>def fn(args): bod...
1
2016-08-27T12:43:41Z
[ "python", "numpy", "cython" ]
Do locally set Cython compiler directives affect one or all functions?
39,181,180
<p>I am working on speeding up some Python/Numpy code with Cython, and am a bit unclear on the effects of "locally" setting (as defined <a href="http://docs.cython.org/en/latest/src/reference//compilation.html" rel="nofollow">here</a> in the docs) compiler directives. In my case I'd like to use:</p> <pre><code>@cython...
2
2016-08-27T12:32:44Z
39,183,975
<p>The <a href="http://cython.readthedocs.io/en/latest/src/reference/compilation.html#globally" rel="nofollow">documentation</a> states that if you want to set a compiler directive globally, you need to do so with a comment at the top of the file. eg.</p> <pre><code>#!python #cython: language_level=3, boundscheck=Fals...
2
2016-08-27T17:38:33Z
[ "python", "numpy", "cython" ]
Attempt to call an undefined function glutInit
39,181,192
<p>I need a glut window in python. I have the following exception using Python 3.5 and PyOpenGL.GLUT</p> <pre><code>Traceback (most recent call last): File "D:\...\Test.py", line 47, in &lt;module&gt; if __name__ == '__main__': main() File "D:\...\Test.py", line 9, in main glutInit(sys.argv) File "C:\.....
0
2016-08-27T12:34:12Z
39,181,193
<p><strong>Problems:</strong></p> <ul> <li>There was no problem with <code>pip install</code> or <code>easy_install</code></li> <li>The <code>glut.dll</code> and <code>glut32.dll</code> were missing. (They are not part of the PyPI package) you have to install them separately or <a href="ftp://ftp.sgi.com/opengl/glut/g...
0
2016-08-27T12:34:12Z
[ "python", "python-3.x", "glut", "pyopengl" ]
Flask-Migrate having issue with enum class in models
39,181,294
<p>Using flask-migrate before I was able to create enums by using flask-sqlalchemy's db.Enum and entering the values in as strings like so.</p> <pre><code>reservation_status = db.Enum('pending', 'confirmed, name='reservation_status_enum') </code></pre> <p>I decided to start using enum classes like the following. Acco...
1
2016-08-27T12:43:53Z
39,181,900
<p>Thanks to user @dim, I was able to resolve the issue by upgrading just sqlalchemy to beta 1.1.0b3. As is most cases, it was user error(me).</p> <p>All i did was </p> <pre><code>pip uninstall sqlalchemy pip install sqlalchemy==1.1.0b3 </code></pre>
1
2016-08-27T13:52:52Z
[ "python", "flask", "enums", "sqlalchemy", "alembic" ]
Using `map` to write lines to files
39,181,323
<p>I have a list of lines:</p> <pre><code>lines = [a,b,c,d] </code></pre> <p>And a list of files (created via <code>open(path string,'w')</code>:</p> <pre><code>files = [e,f,g,h] </code></pre> <p>What I am trying to do is write each line to its respective file (line <code>a</code> should go with file <code>e</code>...
0
2016-08-27T12:47:57Z
39,181,344
<p>Did you mean to do:</p> <pre><code>map(lambda (x,y): y.write(x + "\n"), zip(lines,files)) </code></pre> <p>But I'd rather do it as:</p> <pre><code>for l, f in zip(lines,files): f.write(l + "\n") </code></pre>
4
2016-08-27T12:50:15Z
[ "python", "python-2.7", "function", "dictionary", "lambda" ]
How do I change a value of a variable using an if else statement?
39,181,330
<p>I've been on it for days but nothing is helping. The value of smallest does not change no matter what i do. it does not happen with the value of largest although it uses almost the same line of code.</p> <pre><code>smallest = None largest = None while True: num = raw_input("Enter a number: ") if num == "don...
0
2016-08-27T12:48:23Z
39,181,381
<p>The problem is that you are, in both cases, comparing numbers to <code>None</code> in the first iteration. In Python 2, every number will come out as "greater" when compared to <code>None</code>, thus the code works for finding the maximum, but fails for finding the minimum.</p> <p>BTW, in Python 3, the same would ...
4
2016-08-27T12:54:49Z
[ "python", "python-2.7", "python-3.x" ]
How do I change a value of a variable using an if else statement?
39,181,330
<p>I've been on it for days but nothing is helping. The value of smallest does not change no matter what i do. it does not happen with the value of largest although it uses almost the same line of code.</p> <pre><code>smallest = None largest = None while True: num = raw_input("Enter a number: ") if num == "don...
0
2016-08-27T12:48:23Z
39,181,750
<p>First, (almost) never use a bare <code>except</code> statement. You will catch exceptions you can't or don't want to handle (like <code>SystemExit</code>). At the very least, use <code>except Exception</code>.</p> <p>Second, your <code>except</code> block implies you only want to handle the <code>ValueError</code> ...
1
2016-08-27T13:37:10Z
[ "python", "python-2.7", "python-3.x" ]
for-loop Python 3.5. Creating a quiz for students I tutor
39,181,543
<p>Hello I'm currently trying to make a quiz application for year english students. I'm using Python 3.5. and I'm kinda new. The quizz is supposed to work like below I'll include the code as well. </p> <blockquote> <p>WELCOME TO YOUR QUIZ</p> <p>Word 1/5: Potato How many consanants does the word contain?</p> ...
1
2016-08-27T13:14:22Z
39,181,637
<p>I'm proposing a way to select a question, and associate a test function, which allows to define as many questions you want easily:</p> <pre><code>print('WELCOME TO YOUR QUIZ') # Import the random module to allow us to select the word list and questions at random. import random quizWords = ['WOMBAT', 'COMPUTER', 'B...
0
2016-08-27T13:25:01Z
[ "python", "python-3.x", "for-loop" ]
for-loop Python 3.5. Creating a quiz for students I tutor
39,181,543
<p>Hello I'm currently trying to make a quiz application for year english students. I'm using Python 3.5. and I'm kinda new. The quizz is supposed to work like below I'll include the code as well. </p> <blockquote> <p>WELCOME TO YOUR QUIZ</p> <p>Word 1/5: Potato How many consanants does the word contain?</p> ...
1
2016-08-27T13:14:22Z
39,181,680
<p>Here's a possible solution:</p> <pre><code># Import the random module to allow us to select the word list and # questions at random. import random quizWords = [ 'WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', '...
0
2016-08-27T13:29:34Z
[ "python", "python-3.x", "for-loop" ]
for-loop Python 3.5. Creating a quiz for students I tutor
39,181,543
<p>Hello I'm currently trying to make a quiz application for year english students. I'm using Python 3.5. and I'm kinda new. The quizz is supposed to work like below I'll include the code as well. </p> <blockquote> <p>WELCOME TO YOUR QUIZ</p> <p>Word 1/5: Potato How many consanants does the word contain?</p> ...
1
2016-08-27T13:14:22Z
39,182,052
<p>This is how I would go about creating a quiz. Obviously you can update the print statements to follow your own desired format. Hope that this helps!</p> <pre><code>import random import string def consonant_count(word): word = word.lower() return len([x for x in word if x in consonants]) def vowel_count(wo...
1
2016-08-27T14:09:42Z
[ "python", "python-3.x", "for-loop" ]
'python' is not recognized as an internal or external command, operable program or batch file.Even though path is added
39,181,560
<p>I am on Windows 10, 64. </p> <p>When I run python in cmd, I got the message: 'python' is not recognized as an internal or external command, operable program or batch file.</p> <p>Even though I have added C:\Python27 to the environment variables. Please help </p>
-2
2016-08-27T13:16:03Z
39,181,598
<p>:( Turns out. I just need to restart the PC. </p>
-1
2016-08-27T13:19:51Z
[ "python", "windows", "batch-file" ]
'python' is not recognized as an internal or external command, operable program or batch file.Even though path is added
39,181,560
<p>I am on Windows 10, 64. </p> <p>When I run python in cmd, I got the message: 'python' is not recognized as an internal or external command, operable program or batch file.</p> <p>Even though I have added C:\Python27 to the environment variables. Please help </p>
-2
2016-08-27T13:16:03Z
39,181,625
<p>You can add the python folder to the <code>PATH</code> environment variable but I would suggest to install <a href="https://bitbucket.org/vinay.sajip/pylauncher" rel="nofollow">the launcher</a> (see <a href="https://www.python.org/dev/peps/pep-0397/" rel="nofollow">PEP 397</a>) instead (it is the same one that is in...
0
2016-08-27T13:23:39Z
[ "python", "windows", "batch-file" ]
Find all n-dimensional lines and diagonals with NumPy
39,181,600
<p>Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.</p> <hr> <p>Take the case of the following three-dimensional array with lengths of three.</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], ...
11
2016-08-27T13:20:07Z
39,183,487
<pre><code>In [1]: x=np.arange(27).reshape(3,3,3) </code></pre> <p>Selecting individual <code>rows</code> is easy:</p> <pre><code>In [2]: x[0,0,:] Out[2]: array([0, 1, 2]) In [3]: x[0,:,0] Out[3]: array([0, 3, 6]) In [4]: x[:,0,0] Out[4]: array([ 0, 9, 18]) </code></pre> <p>You could iterate over dimensions with an...
3
2016-08-27T16:45:38Z
[ "python", "arrays", "numpy", "diagonal", "n-dimensional" ]
Find all n-dimensional lines and diagonals with NumPy
39,181,600
<p>Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.</p> <hr> <p>Take the case of the following three-dimensional array with lengths of three.</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], ...
11
2016-08-27T13:20:07Z
39,185,702
<p><strong>This solution generalized over <code>n</code></strong></p> <p>Lets rephrase this problem as "find the list of indices".</p> <p>We're looking for all of the 2d index arrays of the form</p> <pre><code>array[i[0], i[1], i[2], ..., i[n-1]] </code></pre> <p>Let <code>n = arr.ndim</code></p> <p>Where <code>i<...
5
2016-08-27T20:59:01Z
[ "python", "arrays", "numpy", "diagonal", "n-dimensional" ]
Find all n-dimensional lines and diagonals with NumPy
39,181,600
<p>Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.</p> <hr> <p>Take the case of the following three-dimensional array with lengths of three.</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], ...
11
2016-08-27T13:20:07Z
39,185,743
<p>np.einsum can be used to build all these kind of expressions; for instance:</p> <pre><code># 3d diagonals print(np.einsum('iii-&gt;i', a)) # 2d diagonals print(np.einsum('iij-&gt;ij', a)) print(np.einsum('iji-&gt;ij', a)) </code></pre>
2
2016-08-27T21:04:54Z
[ "python", "arrays", "numpy", "diagonal", "n-dimensional" ]
how to iterate over files in neighbouring dir
39,181,647
<p>I have a project structure like this</p> <pre><code>test/foo.py test/bar (directory with 10 files) src/ README.MD </code></pre> <p>From <code>foo.py</code> (which is in <code>test</code> dir), I wish to iterate over the 10 files in the <code>bar</code> dir (which is also in <code>test</code> dir). I tried to do th...
0
2016-08-27T13:25:55Z
39,181,765
<p>Use functions in <code>os.path</code> to do this (works only from a script, not REPL):</p> <pre><code>import os # retrieve path to directory with script script_dir = os.path.dirname(os.path.realpath(__file__)) bar_dir = os.path.join(script_dir, 'bar') for f in os.listdir(bar_dir): print(f) </code></pre>
1
2016-08-27T13:38:43Z
[ "python" ]
Sometimes request.session.session_key is None
39,181,655
<p>I hit a problem when get session_key from <code>request.session</code>.</p> <p>I am using Django1.8 and Python2.7.10 to set up a RESTful service.</p> <p>Here is snippet of my login view:</p> <pre><code>user = authenticate(username=userName, password=passWord) if user is not None: # the password verified for t...
0
2016-08-27T13:27:04Z
39,188,274
<p>According to John's suggestion.</p> <p>I fixed the problem by this snippet:</p> <pre><code>if not request.session.session_key: request.session.save() session_id = request.session.session_key </code></pre>
0
2016-08-28T05:24:33Z
[ "python", "django", "session", "django-sessions" ]
Django : how to pass event.id/package.id in a template
39,181,669
<p>I have three jobs to be done 1) Read Packages related to an event 2) Update Packages related to that event one by one. 3) Or delete the same package related to that event. I have my views.py like this : </p> <pre><code>@login_required def update_package(request, pk ): package = Packages.objects.get(pk = pk...
0
2016-08-27T13:28:05Z
39,181,925
<p>You need to add an <code>id</code> argument to your <code>update_package</code> and <code>delete_package</code> views.</p> <pre><code>def update_package(request, id, pk): def delete_package(request, id, pk): </code></pre> <p>These arguments must match the ones you have on your urls.</p> <p>Your <code>delete_packa...
0
2016-08-27T13:54:45Z
[ "python", "django", "django-templates", "django-views" ]
can I use Numpy genfromtxt to get names then skip a specifc row before continuing?
39,181,748
<p>I have a series of large CSV files contain sensor data samples.</p> <p>The format of each file is</p> <pre><code>Row 0 Column names Row 1 Column unit of measurement. Row 2 to EOF: time-stamp of sample was taken,voltage measurement from all sensors..... </code></pre> <p>I cannot modify the original file</p> <p>...
1
2016-08-27T13:37:01Z
39,183,110
<p>I can see several options:</p> <ul> <li><p>Open the file to read just the header line, parse the names yourself; run <code>genfromtxt</code> with the custom names and skip_header</p></li> <li><p>trick <code>genfromtxt</code> into treating the 2nd line as a comment line</p></li> <li><p>open the file yourself; pass l...
0
2016-08-27T16:06:02Z
[ "python", "numpy" ]
Using Python libraries in Racket
39,181,788
<p>Can I use Python code and libraries in Racket? I have installed PyonR (<a href="https://github.com/pedropramos/PyonR" rel="nofollow">https://github.com/pedropramos/PyonR</a>) in DrRacket so I can choose "#lang python" and run Python code. But how can I combine Racket and Python language codes for my application?</p...
2
2016-08-27T13:41:23Z
39,186,289
<p><a href="https://github.com/pedropramos/PyonR" rel="nofollow">Accoring to the readme</a> you can import python 2.7 packages, but you need to use <code>cpyimport</code>. One of the examples looks like this:</p> <pre><code>#lang python cpyimport numpy as np from "racket" import time def add_arrays(n): re...
3
2016-08-27T22:19:16Z
[ "python", "racket", "ffi" ]
Using Python libraries in Racket
39,181,788
<p>Can I use Python code and libraries in Racket? I have installed PyonR (<a href="https://github.com/pedropramos/PyonR" rel="nofollow">https://github.com/pedropramos/PyonR</a>) in DrRacket so I can choose "#lang python" and run Python code. But how can I combine Racket and Python language codes for my application?</p...
2
2016-08-27T13:41:23Z
39,194,018
<p>The PyonR project is the closest ready-to-use way of using Python libraries from Racket that I know of. However note that there is a difference between Python libraries written in Python and Python libraries that are a thin Python layer on top of a C library. As you have experienced the latter type is not working (t...
2
2016-08-28T17:33:33Z
[ "python", "racket", "ffi" ]
Remove u' in json list
39,181,791
<p>I have a python script that queries servers that comes back with a set of information. Which i need to put into a database which is used by a php website. How ever there is a specific field that i get returned the <code>description</code> field which is user input and in some cases a few ASCII characters are used b...
0
2016-08-27T13:41:45Z
39,181,874
<p>If <code>status.description</code> is returning a dict and you want it to be JSON, you should call <code>json.dumps()</code> on it, not <code>unicode()</code>.</p> <p>However, the presence of <code>u</code> characters in a dict is <em>not</em> a problem and does not need to be fixed.</p>
2
2016-08-27T13:49:18Z
[ "php", "python", "database", "encoding", "user-input" ]
Remove u' in json list
39,181,791
<p>I have a python script that queries servers that comes back with a set of information. Which i need to put into a database which is used by a php website. How ever there is a specific field that i get returned the <code>description</code> field which is user input and in some cases a few ASCII characters are used b...
0
2016-08-27T13:41:45Z
39,181,899
<p><code>print(some_dict)</code> print string representation of a dict object. You need to convert dict object to a JSON.</p> <pre><code>import json print(json.dumps(some_dict)) </code></pre>
0
2016-08-27T13:52:51Z
[ "php", "python", "database", "encoding", "user-input" ]
Spark job aborted
39,181,884
<p>I would like to add a prediction column to my dataframe given the logistic regression model. The function is below:</p> <pre><code>def add_probability(df, model): coefficients_broadcast = sc.broadcast(model.coefficients) intercept = model.intercept def get_p(features): # Compute the raw value raw...
-1
2016-08-27T13:50:25Z
39,185,927
<p>You will absolutely love the reason why it fails:</p> <pre><code>return (1+exp(-raw_prediction))^(-1) </code></pre> <p>should be</p> <pre><code>return (1+exp(-raw_prediction))**(-1) </code></pre> <p>Glad I could help</p>
0
2016-08-27T21:31:45Z
[ "python", "apache-spark" ]
Keras Convolutional Autoencoder: Layer Shapes
39,181,976
<p>I've got a list of about 70,000 training images, each shaped (no. of colour channels, height width) = (3, 30, 30), and about 20,000 testing images. My convolutional autoencoder is defined as:</p> <pre><code> # Same as the code above, but with some params changed # Now let's define the model. # Set input dimension...
1
2016-08-27T14:00:52Z
39,551,007
<p>You forgot to add border_mode='same' in the last convnet layer of the decoder . </p>
0
2016-09-17T19:42:49Z
[ "python", "autoencoder" ]
Urwid colored Text simplified
39,182,074
<p>This is my broken code (technically works but doesn't change color)</p> <pre><code>import urwid txt = urwid.AttrMap(urwid.Text(u"Hello World"), 'dark blue') fill = urwid.Filler(txt, 'top') loop = urwid.MainLoop(fill) loop.run() </code></pre> <p>Honestly all I want to do is change the color of the text, it seems so...
0
2016-08-27T14:11:33Z
39,182,318
<p>From the <a href="http://urwid.org/reference/widget.html#text" rel="nofollow">manual</a>, there is no argument for color:</p> <blockquote> <p>class urwid.Text(markup, align='left', wrap='space', layout=None)</p> </blockquote> <p>You have to define a pallet, example:</p> <pre><code>import urwid palette = [("tex...
0
2016-08-27T14:39:51Z
[ "python", "python-2.7" ]
Subplots mess with my plot
39,182,249
<p>I have the following plot function that saves a random walk input <em>(the random walk is supposed to mimic a stock and bond portfolio that rebalances between each other given specific inputs, the exposure is supposed to show the exposure to the stock portfolio)</em>: </p> <pre><code>def stock_save_img_run(k): ...
0
2016-08-27T14:32:12Z
39,183,501
<p>Obtaining handles over separate <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">Axes</a> instances might be a step in a helpful direction:</p> <pre><code>def stock_save_img_run(k): stock_vals = pd.read_csv('stock_vals_run_' + str(k) + '.csv', sep=';', encoding='utf-8-sig') fig, (top_axes, b...
2
2016-08-27T16:47:55Z
[ "python", "matplotlib", "stacked-area-chart" ]
How to delay a python program in progress through another python code (in Raspberry Pi)
39,182,251
<p>I want to know how to delay and execute a python program in progress in Raspberry Pi through another python code. For example, I have a python file named example.py which contains GPIO commands and the python file is in progress. But I want the GPIO process to be delayed or stop, so I want a python file named delay....
1
2016-08-27T14:32:28Z
39,183,322
<p>Every python script run on python.exe process. Just find the process name(it's better to find PID) that you want to pause or stop and by using system library you can stop that. But here is a link which solve your problem in Pi:</p> <p><a href="http://Every%20python%20script%20run%20on%20python.exe%20process.%20Jus...
0
2016-08-27T16:28:46Z
[ "python", "process", "raspberry-pi" ]
How to set a class attribute a specified number of times in Python
39,182,321
<p>Suppose we have a class <code>Node</code> which is initialized as follows:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node </code></pre> <p>and we create an instance <code>he...
0
2016-08-27T14:40:04Z
39,182,432
<blockquote> <p>It seems like the next_n_times method works as a 'getter', but not as a 'setter'. How can I make it work as a 'setter'?</p> </blockquote> <p>What you get back is a <code>Node</code> object, and you want to set its <code>next</code> attribute: </p> <pre><code>head.next_n_times(3).next = Node(data=8) ...
1
2016-08-27T14:52:07Z
[ "python" ]
How to set a class attribute a specified number of times in Python
39,182,321
<p>Suppose we have a class <code>Node</code> which is initialized as follows:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node </code></pre> <p>and we create an instance <code>he...
0
2016-08-27T14:40:04Z
39,182,492
<p>You're trying to implement the append method for the Node class. You can easily do so with recursion:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def append(self, nod...
2
2016-08-27T14:59:06Z
[ "python" ]
How to set a class attribute a specified number of times in Python
39,182,321
<p>Suppose we have a class <code>Node</code> which is initialized as follows:</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node </code></pre> <p>and we create an instance <code>he...
0
2016-08-27T14:40:04Z
39,182,500
<p>Try this</p> <pre><code>class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node def next_n_times(self, n, value): next_node = self.next # loop to the penultimate Node fo...
0
2016-08-27T15:00:10Z
[ "python" ]
Indexing Matrix in TensorFlow
39,182,337
<p>For example, in Numpy I can get some values like this. </p> <pre><code>d = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) # array([[0, 1, 2], # [3, 4, 5], # [6, 7, 8]]) d[[0, 1, 2], [2, 1, 0]] # array([2, 4, 6]) </code></pre> <p>So I can retrieve [2, 4, 6]. </p> <p>how can I do the same thing in Tenso...
0
2016-08-27T14:41:29Z
39,182,415
<p>One solution I found is to use gather_nd function. </p> <pre><code>sess.run([tf.gather_nd(x, [[0, 2], [1, 1], [2, 0]])]) # [3 5 7] </code></pre> <p>Is there any other functions? a function more similar to Numpy in TensorFlow?</p>
0
2016-08-27T14:49:45Z
[ "python", "numpy", "neural-network", "tensorflow" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pyg...
1
2016-08-27T14:46:44Z
39,182,491
<p>Your code work perfectly well on my platform. My platform: Scientific Linux 7 (RHEL 7) Python: 3.4.3 Pygame Version: 1.9.2b8 Window Manager: Gnome3</p> <p>There is also probably bug in your code. The "/img/bg_img.png" suggest absolute path, it possible, but very uncommon :).</p>
0
2016-08-27T14:58:59Z
[ "python", "pygame" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pyg...
1
2016-08-27T14:46:44Z
39,182,504
<p>Works pretty nicely for me. See the demo below:</p> <p><a href="http://i.stack.imgur.com/0CsC8.gif" rel="nofollow"><img src="http://i.stack.imgur.com/0CsC8.gif" alt="enter image description here"></a></p>
0
2016-08-27T15:01:08Z
[ "python", "pygame" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pyg...
1
2016-08-27T14:46:44Z
39,182,635
<p>Not only does your code work as expected on linux Mate 17, python 2.7.6 but it also works with <code>sys.exit()</code> instead of <code>pygame.quit()</code> or nothing at all i.e. no <code>sys.exit()</code> or <code>pygame.quit()</code></p>
0
2016-08-27T15:13:26Z
[ "python", "pygame" ]
Pygame Freezes on Exit/Quit
39,182,385
<p>I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button. And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.</p> <pre><code>#!/usr/bin/python import sys import pyg...
1
2016-08-27T14:46:44Z
39,182,681
<p>So it turns out that the IDLE is what was causing the problem... I tried to run the code from commandline and it worked perfectly!</p> <p>The IDLE that I (was) using is called Wing101.</p>
0
2016-08-27T15:18:46Z
[ "python", "pygame" ]
tar files and download with flask app
39,182,405
<p>I have one tex file and three images and I want that the user can click a button and download all three of them. It would be ideal if the four files would be as one tar file. My download works as follows right now</p> <pre><code>@app.route('/download_tex', methods=['GET', 'POST']) @login_required def download_tex()...
1
2016-08-27T14:49:16Z
39,183,457
<p>You should use the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.send_from_directory" rel="nofollow">send_from_directory</a> method that Flask provides for this =) It is the perfect use case for what you're doing.</p> <p>What you can do is something like this:</p> <pre><code>from flask import send_from_dire...
1
2016-08-27T16:43:12Z
[ "python", "flask" ]
Catch Google Endpoint Response Error
39,182,536
<p>It's very hard to track Google Endpoints error, which raised at the time response:</p> <pre><code>Encountered unexpected error from ProtoRPC method implementation: ValidationError (Message MatchCenterResponseMessage is missing required field sport) (/base/data/home/runtimes/python27/python27_lib/versions/third_part...
0
2016-08-27T15:03:58Z
39,183,235
<p>You can use try except structure to catch the error. Also tracing may help you alot. </p> <pre><code>try: //your code Except ValidationError: raiseError </code></pre>
0
2016-08-27T16:19:06Z
[ "python", "google-app-engine", "google-cloud-endpoints" ]
Python Flask Login login_required redirecting
39,182,650
<p>I am working on a Flask app and using Flask-Login for authentication. Everything is set up and running. However when the user logins in and attempts to visit a page that requires login, they are redirected to the login page. </p> <p>When watching the console, I get a 200 for the GET login page, a 200 for the POST o...
2
2016-08-27T15:15:21Z
39,307,130
<p>So it turns out that when working with Peewee and Flask-Login, you need to let Peewee supply its default primary key for the User model instead of using a custom one. Removing <code>user_id = PrimaryKeyField()</code>, dropping the table, and restarting fixed it.</p>
0
2016-09-03T12:55:16Z
[ "python", "flask", "flask-login" ]
Why if the id = '0' in "InlineQueryResultArticle" the element chosen doesn't trigger the "on_chosen_inline_result" code?
39,182,676
<p>I'm new to Python and new to Stack Overflow, sorry for my mistakes...</p> <p>I'm using Telepot to write a bot for Telegram.<br> When dealing with inline results I can only make the code in <code>on_chosen_inline_result</code> execute for every article I choose other than the first created.</p> <pre><code>def on_in...
2
2016-08-27T15:18:30Z
39,188,148
<p>From my own test, it seems your suspicion is correct. I have tried a variety of id strings and chosen each of them in turn:</p> <ul> <li><code>00</code> → Yes (<code>chosen_inline_result</code> gotten)</li> <li><code>$0</code> → Yes</li> <li><code>0</code> → No</li> <li><code>1</code> → Yes</li> </ul> <p>A...
1
2016-08-28T04:56:57Z
[ "python", "telegram-bot" ]
Solve for roots in given interval using scipy.optimize
39,182,713
<p>I have the function <code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02)</code>, and I wish to solve for its roots in the interval (0, 1). I have tried using the <code>scipy.optimize.brentq</code> and <code>scipy.optimize.fsolve</code> to do this, but both methods run into issues. Based on some experimentati...
0
2016-08-27T15:23:07Z
39,186,066
<p>fsolve does not support root-finding on an interval. It likely wanders off to either x&lt;0 or x>1, hence RuntimeWarning (once) and garbage for the answer. You can check it by instrumenting your function with print(x).</p> <p>Brentq's behavior is undefined if the interval contains more then one root.</p> <p>If you...
2
2016-08-27T21:52:11Z
[ "python", "optimization", "scipy", "polynomial-math" ]
Solve for roots in given interval using scipy.optimize
39,182,713
<p>I have the function <code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02)</code>, and I wish to solve for its roots in the interval (0, 1). I have tried using the <code>scipy.optimize.brentq</code> and <code>scipy.optimize.fsolve</code> to do this, but both methods run into issues. Based on some experimentati...
0
2016-08-27T15:23:07Z
39,188,106
<p>If you take the derivative of your function and set it equal to 0, after a little algebra you'll find that the derivative is 0 at x0 = 0.5/0.52. (In a calculus class, this point is called a <em>critical point</em>, not an inflection point.) The function has a minimum at this point, and the value there is negative....
2
2016-08-28T04:47:04Z
[ "python", "optimization", "scipy", "polynomial-math" ]
Solve for roots in given interval using scipy.optimize
39,182,713
<p>I have the function <code>f1 = lambda x: 1 - 1.12 * (x ** 0.5) * ((1-x) ** 0.02)</code>, and I wish to solve for its roots in the interval (0, 1). I have tried using the <code>scipy.optimize.brentq</code> and <code>scipy.optimize.fsolve</code> to do this, but both methods run into issues. Based on some experimentati...
0
2016-08-27T15:23:07Z
39,194,788
<p>As you already know, a direct answer to part of your question is that fsolve doesn't find a root in the interval [0.97,0.98] because there's no root there. As for a systematic way, why not use <strong>plot</strong>?</p> <p>Once you've defined the function as a <strong>lambda</strong>, ready for use with Brent or va...
1
2016-08-28T19:01:47Z
[ "python", "optimization", "scipy", "polynomial-math" ]
Applying Decay Factor to Return Data in Pandas and Saving as New Variable
39,182,747
<p>I have return data for stocks (thousands of them but am only showing 4 here) as below:</p> <pre><code>In[3]:ret Out[3]: Symbol AAPL DE IBM MSFT Date 2016-01-19 NaN NaN NaN NaN 2016-01-20 -0.021780 -0.019701 -0.078557 ...
1
2016-08-27T15:26:33Z
39,183,014
<p>Adding column row_index:</p> <pre><code>In [229]: df['row_index'] = df.apply(lambda x: x.name, axis = 1) In [230]: df Out[230]: Date AAPL DE IBM MSFT row_index 0 2016-01-19 NaN NaN NaN NaN 0 1 2016-01-20 -0.021780 -0.019701 -0.078557 -0.019177 ...
1
2016-08-27T15:56:18Z
[ "python", "pandas" ]
Applying Decay Factor to Return Data in Pandas and Saving as New Variable
39,182,747
<p>I have return data for stocks (thousands of them but am only showing 4 here) as below:</p> <pre><code>In[3]:ret Out[3]: Symbol AAPL DE IBM MSFT Date 2016-01-19 NaN NaN NaN NaN 2016-01-20 -0.021780 -0.019701 -0.078557 ...
1
2016-08-27T15:26:33Z
39,184,540
<p>Try This: </p> <pre><code>df = df.set_index("Date") retFac = np.fromfunction(lambda i,j : .97**(i), df.values.shape)[::-1] df*retFac df['ret_decay'] = retFac[:,0] df AAPL DE IBM MSFT ret_decay Date 2016-01-19 NaN ...
0
2016-08-27T18:41:10Z
[ "python", "pandas" ]
Moving Character in pygame Without Repeatedly Copying Image
39,182,813
<p>My character, like most characters, is supposed to be repeatedly replaced by the same image a few pixels over to simulate movement. Instead, my code causes the image to be copied when I move it, and right now it's more like a drawing application than a moving character. Can someone please tell me why this is happe...
1
2016-08-27T15:33:27Z
39,183,251
<p>Before you enter the main loop, add a statement like</p> <pre><code>background = pygame.Surface(DISPLAYSURF.get_size()) </code></pre> <p>and then blit background onto DISPLAYSURF. At each iteration, after everything has been updated but before anything else has been drawn, blit your background onto the DISPLAYSURF...
1
2016-08-27T16:20:46Z
[ "python", "pygame" ]
Round-off / round-up criteria in Python
39,182,861
<p>I'm porting a MATLAB code to Python 3.5.1 and I found a float round-off issue.</p> <p>In MATLAB, the following number is rounded <strong>up</strong> to the 6th decimal place:</p> <pre><code>fprintf(1,'%f', -67.6640625); -67.664063 </code></pre> <p>In Python, on the other hand, the following number is rounded <str...
5
2016-08-27T15:37:33Z
39,187,125
<p>The reason for the python behavior has to do with how floating point numbers are stored in a computer and the standardized rounding rules defined by IEEE, which defined the standard number formats and mathematical operations used on pretty much all modern computers.</p> <p>The need to store numbers efficiently in b...
4
2016-08-28T01:02:08Z
[ "python", "matlab", "rounding" ]
How to define start value for ID column in SQLAlchemy for SQLServer?
39,182,924
<p>I interfacing SQLAlchemy between Flask and SQLServer.</p> <p>I have an ID column which I would like to start from 10000. I couldn't find the answer.</p> <p>Below is the SQL code, I am trying to convert to SQLAlchemy.</p> <p>Please let me know.</p> <p>Thx</p> <pre><code>create TABLE [dbo].[Product]( [ID] [in...
1
2016-08-27T15:45:23Z
39,207,014
<p>You'll need to do some changes after SQLAlchemy creates the table, as shown in the links above for MySQL, but with SQL Server.</p> <pre><code>from sqlalchemy import event from sqlalchemy import DDL event.listen( Article.__table__, "after_create", DDL("DBCC checkident (%(table)s, reseed, 9999)") ) </code...
0
2016-08-29T13:01:55Z
[ "python", "sql-server", "sqlalchemy", "pymssql" ]
I am trying to download data from Yahoo Finance using pandasb but nothing happens?
39,183,147
<pre><code>import pandas_datareader.data as web import datetime start = datetime.datetime(2010, 1, 1) end = datetime.datetime(2013, 1, 27) f = web.DataReader("ugaz", 'yahoo', start, end) f.ix['2010-01-04'] </code></pre> <p>The above is the code I am currently trying to use to get data from Yahoo Finance. when I run...
-1
2016-08-27T16:10:17Z
39,183,262
<p>The first datapoint is </p> <pre><code>f.ix['2012-02-08'] Open 48.360002 High 48.360002 Low 48.360002 Close 48.360002 Volume 0.000000 Adj Close 6045.000287 Name: 2012-02-08 00:00:00, dtype: float64 </code></pre>
0
2016-08-27T16:22:43Z
[ "python", "pandas", "yahoo-finance" ]
I am trying to download data from Yahoo Finance using pandasb but nothing happens?
39,183,147
<pre><code>import pandas_datareader.data as web import datetime start = datetime.datetime(2010, 1, 1) end = datetime.datetime(2013, 1, 27) f = web.DataReader("ugaz", 'yahoo', start, end) f.ix['2010-01-04'] </code></pre> <p>The above is the code I am currently trying to use to get data from Yahoo Finance. when I run...
-1
2016-08-27T16:10:17Z
39,274,713
<p>There are so many ways to download financial data, or any kind of data, from the web. The script below downloads stock prices and saves everything to a CSV file.</p> <pre><code>import urllib2 listOfStocks = ["AAPL", "MSFT", "GOOG", "FB", "AMZN"] urls = [] for company in listOfStocks: urls.append('http://rea...
0
2016-09-01T14:48:56Z
[ "python", "pandas", "yahoo-finance" ]
Django with HTML Forms
39,183,155
<p>I know how to set up Django forms to have Django render them. Unfortunately styling forms then becomes a little less straight forward. I am interested in finding a way to have the HTML form pass its entered values to Django. The HTML form is completely programmed in HTML and CSS. Just for context, please find below ...
0
2016-08-27T16:10:49Z
39,183,460
<p>Ok, I figured it out. </p> <p>The trick was to realize that Django will already render its form tags (i.e. {{form.firstName}}) to an input tag. We can then add class attributes to this tag in in forms.py where we define this form:</p> <p><strong>HTML:</strong></p> <p><div class="snippet" data-lang="js" data-hide=...
0
2016-08-27T16:43:21Z
[ "python", "html", "css", "django" ]
remove the screen in back of the Tkinter message box
39,183,177
<p>I want to show a message box, but without the parent window behind it in Python. This is my code:</p> <pre><code>import Tkinter, tkFileDialog ,tkMessageBox from fileManagerModule import fileManager def load(): global myFile,flag,msg flag=True options = {} options["title"] = "choose a text File" ...
-1
2016-08-27T16:13:10Z
39,183,779
<p>You can use the <code>withdraw()</code> function to remove the <code>window</code> being displayed in the background to just show the dialog box only.</p> <p><strong>try this:</strong></p> <pre><code>import Tkinter, tkFileDialog ,tkMessageBox from fileManagerModule import fileManager def load(): global myFile,...
1
2016-08-27T17:17:56Z
[ "python", "python-2.7", "tkinter" ]
C++ OOP: how to create a random number generator object?
39,183,275
<p>So this question is sort of one of translation. I am new to C++, and was looking through the class documentation. However, it looks like finding the answer to my question is a bit hard via the documentation. </p> <p>I have code for generating a random number between 0 and 1 in C++: (obtained from <a href="http://...
-1
2016-08-27T16:24:00Z
39,183,348
<p>You can create a class that holds a random number generator as a private member variable (like <code>std::mt19937</code>) and seeds it in the constructor. Your <code>next</code> function could just invoke the stored generator to get the next value (applying whatever distribution you want (if any) of course).</p> <p...
2
2016-08-27T16:31:16Z
[ "python", "c++", "oop" ]
C++ OOP: how to create a random number generator object?
39,183,275
<p>So this question is sort of one of translation. I am new to C++, and was looking through the class documentation. However, it looks like finding the answer to my question is a bit hard via the documentation. </p> <p>I have code for generating a random number between 0 and 1 in C++: (obtained from <a href="http://...
-1
2016-08-27T16:24:00Z
39,183,450
<p>Seems like you just need some form of probability generation class, see below for a basic implementation which meets your question requirements:</p> <pre><code>template&lt;class Ty = double, class = std::enable_if_t&lt;std::is_floating_point&lt;Ty&gt;::value&gt; &gt; class random_probability_generator { public:...
3
2016-08-27T16:42:29Z
[ "python", "c++", "oop" ]
I get the error, list indices must be integers, do not know why?
39,183,310
<pre><code>for i in inpt: for j in inpt[i]: print j, </code></pre> <p>I want to access a 2D array, for each array i in inpt, I want to print each number j in the array i. I do not have any formal background in python and also I could not already find a solution on the internet.</p>
0
2016-08-27T16:27:33Z
39,183,324
<p>Python <code>for</code> loops are <a href="https://en.wikipedia.org/wiki/Foreach_loop" rel="nofollow"><em>foreach</em> loops</a>, in that you get the actual elements from the list and not an index. You are trying to use those elements as indices to <code>inpt</code> again.</p> <p>Loop over <code>i</code>, not <code...
1
2016-08-27T16:28:54Z
[ "python", "python-2.7" ]
Finding anchor tags within a table using selenium chromedriver
39,183,383
<p>I am trying to build an application that automates the process of downloading several anime episodes and i am stuck. So far i've been able to locate the episode links using the following code:</p> <pre><code>def get_episodes(driver): WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a...
2
2016-08-27T16:34:46Z
39,183,490
<p>Try to make your <code>XPath</code> more specific:</p> <pre><code>//tr/td/a[starts-with(@href,'/Anime/')] </code></pre>
1
2016-08-27T16:46:24Z
[ "python", "selenium", "selenium-chromedriver" ]
Finding anchor tags within a table using selenium chromedriver
39,183,383
<p>I am trying to build an application that automates the process of downloading several anime episodes and i am stuck. So far i've been able to locate the episode links using the following code:</p> <pre><code>def get_episodes(driver): WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a...
2
2016-08-27T16:34:46Z
39,183,508
<p>You're on the right track, but you may be over-thinking this a bit. Why not just target the table that we know has the episodes, then use a list comprehension to grab all the episode links?</p> <pre><code>def get_episodes(): episode_table = driver.find_element_by_class_name('listing') episode_links = [i.g...
0
2016-08-27T16:48:17Z
[ "python", "selenium", "selenium-chromedriver" ]
Python Save a (Sparse) Matrix with a variable inside
39,183,417
<p>I have some matrices of decent size (2000*2000) and I wish to have symbolic expressions in the elements of the matrices - i.e. <code>.9**b + .8**b + .7**b ...</code> is an example of an element. The matrices are quite sparse.</p> <p>I am creating these matrices by adding up intermediate calculations. I would like t...
6
2016-08-27T16:38:11Z
39,214,491
<p>The problem is likely coming from the fact that you are taking a symbolic power. But, for whatever reason, SymPy tries to find an explicit form for a symbolic power. For example:</p> <pre><code>In [12]: x = Symbol('x') In [13]: print(Matrix([[1, 2], [3, 4]])**x) Matrix([[-2*(5/2 + sqrt(33)/2)**x*(-2/((-3/2 + sqrt(...
0
2016-08-29T20:16:49Z
[ "python", "sympy", "symbolic-math" ]
Write multiple Numpy arrays of different dtype as columns of CSV file
39,183,471
<p>What would be the best way to write multiple numpy arrays of different dtype as different columns of a single CSV file?</p> <p>For instance, given the following arrays:</p> <pre><code>array([[1, 2], [3, 4], [5, 6]]) array([[ 10., 20.], [ 30., 40.], [ 50., 60.]]) </code></pre> <p>I ...
2
2016-08-27T16:44:30Z
39,183,525
<p>use <code>np.concatenate</code> in order to concatenate the arrays along the second axis then use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html#numpy.savetxt" rel="nofollow"><code>np.savetxt</code></a> inorder to save your array in a a text format.</p> <pre><code>import numpy as np...
1
2016-08-27T16:50:41Z
[ "python", "csv", "numpy" ]
Write multiple Numpy arrays of different dtype as columns of CSV file
39,183,471
<p>What would be the best way to write multiple numpy arrays of different dtype as different columns of a single CSV file?</p> <p>For instance, given the following arrays:</p> <pre><code>array([[1, 2], [3, 4], [5, 6]]) array([[ 10., 20.], [ 30., 40.], [ 50., 60.]]) </code></pre> <p>I ...
2
2016-08-27T16:44:30Z
39,184,228
<pre><code>In [38]: a=np.arange(1,7).reshape(3,2) In [39]: b=np.arange(10,70.,10).reshape(3,2) In [40]: c=np.concatenate((a,b),axis=1) In [41]: c Out[41]: array([[ 1., 2., 10., 20.], [ 3., 4., 30., 40.], [ 5., 6., 50., 60.]]) </code></pre> <p>All values are float; default <code>savetxt</c...
1
2016-08-27T18:06:54Z
[ "python", "csv", "numpy" ]
I do not get what expected on a regex expression
39,183,538
<p>I am looking for words in text6 that either contain a z or the sequence of characters pt or end with ize</p> <p>I wrote the following but it includes many words that do not meet the above criteria like appease,dance,offensive,executive.... Why is this happening?</p> <pre><code>L2=[w for w in text6 if re.search(r"....
3
2016-08-27T16:51:51Z
39,183,627
<p>You are iterating over the characters not the words, for that case you need to split your text.</p> <p>Also you can do all of these jobs without regex:</p> <pre><code>from string import ascii_uppercase def check_word(word): return 'z' in word or 'pt' in word or word.endswith('ize') or word.startswith(tuple(as...
2
2016-08-27T17:00:58Z
[ "python", "regex" ]
I do not get what expected on a regex expression
39,183,538
<p>I am looking for words in text6 that either contain a z or the sequence of characters pt or end with ize</p> <p>I wrote the following but it includes many words that do not meet the above criteria like appease,dance,offensive,executive.... Why is this happening?</p> <pre><code>L2=[w for w in text6 if re.search(r"....
3
2016-08-27T16:51:51Z
39,183,657
<p>What you are looking for is:</p> <pre><code>[w for w in text6 if re.search(r"z|pt|ize$", w)] </code></pre> <p>This will capture all the required words. Note that, the last part is not required as any word matching <code>ize$</code> will also match <code>z</code>. So essentially, the expression boils down to:</p> ...
1
2016-08-27T17:04:24Z
[ "python", "regex" ]
I do not get what expected on a regex expression
39,183,538
<p>I am looking for words in text6 that either contain a z or the sequence of characters pt or end with ize</p> <p>I wrote the following but it includes many words that do not meet the above criteria like appease,dance,offensive,executive.... Why is this happening?</p> <pre><code>L2=[w for w in text6 if re.search(r"....
3
2016-08-27T16:51:51Z
39,183,736
<p>I would suggest a non-regex approach here, since regex seems more complicated than this use case demands.</p> <p>For one, you can get rid of the "ends in <code>ize</code>" constraint, because that falls under any words with <code>z</code> in it.</p> <pre><code>text6 = [ 'appease', 'dance', 'offensive', 'execut...
2
2016-08-27T17:13:52Z
[ "python", "regex" ]
How to take real time input output from a python script on PHP
39,183,586
<p>I want to take input from user through a html form, process it through a python script and print the output on html page. The problem is the whole python script is executed each time, while I want the script to give real time output for each input. How can I manage to do this ? </p> <p>Here is what I am doing so fa...
0
2016-08-27T16:56:47Z
39,183,710
<p>The best way to solve your problem will be running simple python app using, let's say, <a href="http://flask.pocoo.org" rel="nofollow">Flask</a> and hit to specific endpoint you'll make in it. Everything then could take place through localhost, if you'll set it on the same machine.</p>
0
2016-08-27T17:10:25Z
[ "php", "python" ]
How `[System.Console]::OutputEncoding/InputEncoding` with Python?
39,183,614
<p>Under Powershell v5, Windows 8.1, Python 3. Why these fails and how to fix?</p> <pre class="lang-bsh prettyprint-override"><code>[system.console]::InputEncoding = [System.Text.Encoding]::UTF8; [system.console]::OutputEncoding = [System.Text.Encoding]::UTF8; chcp; "import sys print(sys.stdout.encoding) print(sys....
15
2016-08-27T16:59:53Z
39,428,999
<p>You are piping data into Python; at that point Python's <code>stdin</code> is no longer attached to a TTY (your console) and won't guess at what the encoding might be. Instead, the default system locale is used; on your system that's cp1251 (the Windows Latin-1-based codepage).</p> <p>Set the <a href="https://docs....
8
2016-09-10T17:58:44Z
[ "python", ".net", "shell", "powershell" ]
How `[System.Console]::OutputEncoding/InputEncoding` with Python?
39,183,614
<p>Under Powershell v5, Windows 8.1, Python 3. Why these fails and how to fix?</p> <pre class="lang-bsh prettyprint-override"><code>[system.console]::InputEncoding = [System.Text.Encoding]::UTF8; [system.console]::OutputEncoding = [System.Text.Encoding]::UTF8; chcp; "import sys print(sys.stdout.encoding) print(sys....
15
2016-08-27T16:59:53Z
39,543,595
<p>Why not embed CPython in powershell?! CPython is so easy to embed, and powershell is very good REPL to <a href="https://msdn.microsoft.com/en-us/powershell/scripting/getting-started/cookbooks/creating-.net-and-com-objects--new-object-" rel="nofollow">play with .NET and COM objects</a>. Here is a simple introduction ...
2
2016-09-17T06:32:51Z
[ "python", ".net", "shell", "powershell" ]
Understanding a memoization decorator as a closure
39,183,653
<p>I'm trying to learn about Python decorators, and I'd like to understand in more detail exactly how closure applies, for example in this memoization context:</p> <pre><code>def memoize(f): memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] ...
1
2016-08-27T17:03:55Z
39,183,776
<p>You've misunderstood what the <code>@memoize</code> decorator does. The decorator is not called each time you call <code>fib</code>. The decorator is called <em>just once</em> per function that is decorated.</p> <p>The original <code>fib</code> function is <em>replaced</em> by the <code>helper()</code> function, wi...
2
2016-08-27T17:17:31Z
[ "python", "closures", "memoization", "python-decorators" ]