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
I want to split a sentence into words and get it to display vertically
40,027,728
<p>This is what i have so far.</p> <pre><code>sentence = input("Enter a sentence".lower()) sentence = sentence.split() print (sentence) </code></pre> <p>Current output:</p> <pre><code>enter a sentence hi my name is bob ['hi', 'my', 'name', 'is', 'bob'] </code></pre> <p>Desired output (without those big spaces)</p>...
-4
2016-10-13T17:48:47Z
40,027,744
<p>You can just do:</p> <pre><code>for word in sentence: print(word) </code></pre>
6
2016-10-13T17:49:55Z
[ "python", "python-3.x" ]
I want to split a sentence into words and get it to display vertically
40,027,728
<p>This is what i have so far.</p> <pre><code>sentence = input("Enter a sentence".lower()) sentence = sentence.split() print (sentence) </code></pre> <p>Current output:</p> <pre><code>enter a sentence hi my name is bob ['hi', 'my', 'name', 'is', 'bob'] </code></pre> <p>Desired output (without those big spaces)</p>...
-4
2016-10-13T17:48:47Z
40,027,779
<p>You can specify the <code>end</code> argument for <code>print</code> to get the spacing you desire from a single print statement. The default is a single newline: <code>'\n'</code></p> <pre><code>for word in sentence: print(word, end="\n\n") </code></pre> <p>Edit: oops, missed the <code>out</code> in <code>wit...
2
2016-10-13T17:51:56Z
[ "python", "python-3.x" ]
I want to split a sentence into words and get it to display vertically
40,027,728
<p>This is what i have so far.</p> <pre><code>sentence = input("Enter a sentence".lower()) sentence = sentence.split() print (sentence) </code></pre> <p>Current output:</p> <pre><code>enter a sentence hi my name is bob ['hi', 'my', 'name', 'is', 'bob'] </code></pre> <p>Desired output (without those big spaces)</p>...
-4
2016-10-13T17:48:47Z
40,028,075
<pre><code>for i=0;i &lt; sentence.length;i++ print sentence[i]; if i != sentence.length - 1 println; </code></pre>
-2
2016-10-13T18:09:38Z
[ "python", "python-3.x" ]
Concatenate two 2 dimensional lists into a new list
40,027,837
<p>DISLCAIMER: I am new to Python</p> <p>I would like to create a concatenated 2-D list in Python by combining 2 existing 2-D lists. I start with 2 lists:</p> <pre><code>listA = [[a, b, c], [1, 2, 3]] listB = [[d, e, f], [4, 5, 6]] </code></pre> <p>and i want to make a new list (while preserving listA and listB):<...
0
2016-10-13T17:56:12Z
40,027,879
<p>Create a new list, e.g with list-comprehension</p> <pre><code>listC = [a+b for a,b in zip(listA, listB)] </code></pre>
1
2016-10-13T17:58:16Z
[ "python", "list" ]
Concatenate two 2 dimensional lists into a new list
40,027,837
<p>DISLCAIMER: I am new to Python</p> <p>I would like to create a concatenated 2-D list in Python by combining 2 existing 2-D lists. I start with 2 lists:</p> <pre><code>listA = [[a, b, c], [1, 2, 3]] listB = [[d, e, f], [4, 5, 6]] </code></pre> <p>and i want to make a new list (while preserving listA and listB):<...
0
2016-10-13T17:56:12Z
40,027,924
<p>There are a couple of ways:</p> <pre><code>listC = [listA[0] + listB[0], listA[1] + listB[1]] listC = [x + y for x, y in zip(listA, listB)] </code></pre> <p>Are probably the two simplest</p>
2
2016-10-13T18:00:39Z
[ "python", "list" ]
Concatenate two 2 dimensional lists into a new list
40,027,837
<p>DISLCAIMER: I am new to Python</p> <p>I would like to create a concatenated 2-D list in Python by combining 2 existing 2-D lists. I start with 2 lists:</p> <pre><code>listA = [[a, b, c], [1, 2, 3]] listB = [[d, e, f], [4, 5, 6]] </code></pre> <p>and i want to make a new list (while preserving listA and listB):<...
0
2016-10-13T17:56:12Z
40,027,929
<p>Here is a functional approach if you want learn more:</p> <pre><code>In [13]: from operator import add In [14]: from itertools import starmap In [15]: list(starmap(add, zip(listA, listB))) Out[15]: [['a', 'b', 'c', 'd', 'e', 'f'], [1, 2, 3, 4, 5, 6]] </code></pre> <p>Note that since <code>starmap</code> returns a...
1
2016-10-13T18:01:39Z
[ "python", "list" ]
Calling Python Django File in Android Java Code
40,027,851
<p>I'm developing an android app in Java. I was using a php file to interact w/ the database, but I want to use Python Django instead of php. Could I call the python file that interacts with the database in the same way that I called the php file?</p> <pre><code>URL url = new URL("http://10.0.3.2/MYCODE/app/login.php"...
0
2016-10-13T17:56:55Z
40,028,918
<p>You could run a python socket server and interface with that using your app. There are many ways to do this though. I created a very small python socket server <a href="https://github.com/rstims/lightweight-python-socket-server" rel="nofollow">here</a>, you're welcome to use it, of course.</p> <p><a href="http://...
1
2016-10-13T19:00:45Z
[ "php", "android", "python", "django" ]
Python Twitter API trying to retrieve tweet but error: AttributeError: 'int' object has no attribute 'encode'
40,027,856
<p>why am I getting an AttributeError: 'int' object has no attribute 'encode'? I am trying to retrieve a tweet using the Twitter API on Python. Full traceback here: </p> <pre><code>Traceback (most recent call last): File "C:/Python27/lol.py", line 34, in &lt;module&gt; headers = req.to_header() File "build\bdi...
1
2016-10-13T17:57:18Z
40,030,527
<pre><code>"oauth_timestamp": int(time.time()) </code></pre> <p>here you use an <code>int</code>, but that field <em>must</em> be a string.</p>
0
2016-10-13T20:37:28Z
[ "python", "api", "twitter" ]
Child calling parent's method without calling parent's __init__ in python
40,027,861
<p>I have a program that have a gui in PyQt in the main thread. It communicates to a photo-detector and gets power readings in another thread, which sends a signal to the main thread to update the gui's power value. Now I want to use a motor to automatically align my optical fiber, getting feedback from the photo-detec...
1
2016-10-13T17:57:29Z
40,030,455
<p>The <code>__init__</code> for <code>NanoMax</code> and <code>MyApp</code> should call <code>super().__init__()</code> to ensure initialization is done for all levels (if this is Python 2, you can't use no-arg <code>super</code>, so it would be <code>super(NanoMax, self).__init__()</code> and <code>super(MyApp, self)...
1
2016-10-13T20:33:04Z
[ "python", "multithreading", "inheritance", "pyqt", "parent-child" ]
Child calling parent's method without calling parent's __init__ in python
40,027,861
<p>I have a program that have a gui in PyQt in the main thread. It communicates to a photo-detector and gets power readings in another thread, which sends a signal to the main thread to update the gui's power value. Now I want to use a motor to automatically align my optical fiber, getting feedback from the photo-detec...
1
2016-10-13T17:57:29Z
40,030,584
<pre><code>class MyApp(QtGui.QMainWindow, Ui_MainWindow): self.PDvalue = 0 #initial PD value self.PDState = 0 #control the PD state (on-off) </code></pre> <p>In the above code it is setting a variable outside of a function. To do this in a class don't put the self keyword in front of it. This way you can just ...
0
2016-10-13T20:41:33Z
[ "python", "multithreading", "inheritance", "pyqt", "parent-child" ]
Google API Authorization (Service Account) Error: HttpAccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request
40,027,878
<p>I'm attempting to connect to the YouTube Analytics API using Python. When I go to Google's Developer Console in the Credentials tab I click on the <code>Create credentials</code> drop-down menu and select <code>Help me choose</code>. I click on the API I want to use (<code>YouTube Analytics API</code>), where I wi...
1
2016-10-13T17:58:15Z
40,044,589
<p>I found on this <a href="https://developers.google.com/youtube/analytics/authentication" rel="nofollow">documentation</a> that you cannot use Service account with YouTube Analytics API.</p> <p>It is stated here that:</p> <blockquote> <p>The service account flow supports server-to-server interactions that do no...
1
2016-10-14T13:38:04Z
[ "python", "youtube-api", "google-oauth", "google-api-client" ]
Error with if/elif statements and turtle commands
40,027,925
<p>I have been having an odd error with if/else statements. For some reason, when I use this code (intro project to turtle graphics)</p> <pre><code>from turtle import * print('Hello. I am Terry the Turtle. Enter a command to make me draw a line, or ask for help.') on = True shape('turtle') if on == True: c1 = str(i...
1
2016-10-13T18:00:41Z
40,028,187
<p>I think this is what you want</p> <pre><code>from turtle import * print('Hello. I am Terry the Turtle. Enter a command to make me draw a line, or ask for help.') on = True shape('turtle') # Get commands until user enters goodbye while on: c1 = str(input('Enter command: ')) if c1 == 'forward': # Ask ...
1
2016-10-13T18:17:29Z
[ "python", "turtle-graphics" ]
Error with if/elif statements and turtle commands
40,027,925
<p>I have been having an odd error with if/else statements. For some reason, when I use this code (intro project to turtle graphics)</p> <pre><code>from turtle import * print('Hello. I am Terry the Turtle. Enter a command to make me draw a line, or ask for help.') on = True shape('turtle') if on == True: c1 = str(i...
1
2016-10-13T18:00:41Z
40,028,254
<p>For c1, you don't have to indicate it is a string as inputs are already strings And no need for "eval".</p> <p>Try:</p> <pre><code>from turtle import * print('Hello. I am Terry the Turtle. Enter a command to make me draw a line, or ask for help.') on = True shape('turtle') while on == True: c1 = input('Enter co...
0
2016-10-13T18:21:29Z
[ "python", "turtle-graphics" ]
How to hide hiding secret keys in commits to bitbucket private repo?
40,027,965
<p>I'm using python. Currently, I'm doing this. I have a file named <code>keys.py</code> where I store in my secret keys such as AWS_SECRET and etc.</p> <p>Inside my <code>.gitignore</code> I have keys.py so that it doesn't get committed to bitbucket.</p> <p>My <code>keys.py</code> looks like this.</p> <pre><code>#!...
0
2016-10-13T18:03:16Z
40,028,250
<p>try this:</p> <pre><code>import os AWS_KEY = os.environ.get('AWS_KEY', 'XXXXXX') AWS_SECRET = os.environ.get('AWS_SECRET', 'YYYYYY') PHONE_NUMBER = os.environ.get('PHONE_NUMBER', 'ZZZZZ') </code></pre> <p>But first you need set AWS_KEY, AWS_SECRET, PHONE_NUMBER in the environment variables in <a href="https://con...
1
2016-10-13T18:21:20Z
[ "python", "git" ]
How to hide hiding secret keys in commits to bitbucket private repo?
40,027,965
<p>I'm using python. Currently, I'm doing this. I have a file named <code>keys.py</code> where I store in my secret keys such as AWS_SECRET and etc.</p> <p>Inside my <code>.gitignore</code> I have keys.py so that it doesn't get committed to bitbucket.</p> <p>My <code>keys.py</code> looks like this.</p> <pre><code>#!...
0
2016-10-13T18:03:16Z
40,028,278
<p>You should use environment variables. That is the norm. You will have to adapt your code for this change. </p> <p>A simple fix may be to have your <code>keys.py</code> file look for the environment variables. You can retrieve environment variables as follows: <code>os.environ.get("VARIABLE_NAME")</code></p> <p>As ...
1
2016-10-13T18:23:24Z
[ "python", "git" ]
Django: Filtering query to a specific id
40,028,150
<p>I have a podcast management website where a user is able to setup his account and after that will be able to create multiple episode from that specific user. After an episode is done, a button will appear where he can see some links that is created automatically for the user to use. The problem I am having is that f...
0
2016-10-13T18:14:46Z
40,030,108
<p>You filter by the id in the get method, but then don't do anything with the result. When it comes to construct the template context, Django calls get_queryset, which only filters by self.podcast - which is None.</p> <p>You should move that filter logic into get_queryset. And if you also want to filter by podcast, y...
0
2016-10-13T20:12:43Z
[ "python", "django", "django-templates", "django-views", "django-urls" ]
How do you get the name of the tensorflow output nodes in a Keras Model?
40,028,175
<p>I'm trying to create a pb file from my Keras (tensorflow backend) model so I can build it on iOS. I'm using freeze.py and I need to pass the output nodes. How do i get the names of the output nodes of my Keras model?</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze...
1
2016-10-13T18:16:42Z
40,052,942
<p>The <code>output_node_names</code> should contain the names of the graph nodes you intend to use for inference(e.g. softmax). It is used to extract the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/graph_util.py#L234" rel="nofollow">sub-graph</a> that will be needed for in...
1
2016-10-14T22:37:10Z
[ "python", "tensorflow", "keras" ]
aws boto - how to create instance and return instance_id
40,028,223
<p>I want to create a python script where I can pass arguments/inputs to specify instance type and later attach an extra EBS (if needed).</p> <pre><code>ec2 = boto3.resource('ec2','us-east-1') hddSize = input('Enter HDD Size if you want extra space ') instType = input('Enter the instance type ') def createInstance():...
0
2016-10-13T18:19:13Z
40,030,586
<p>The docs state that the call to create_instances()</p> <p><a href="https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances" rel="nofollow">https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances</a></p> <p>Returns list(...
1
2016-10-13T20:41:35Z
[ "python", "amazon-ec2", "boto", "boto3" ]
aws boto - how to create instance and return instance_id
40,028,223
<p>I want to create a python script where I can pass arguments/inputs to specify instance type and later attach an extra EBS (if needed).</p> <pre><code>ec2 = boto3.resource('ec2','us-east-1') hddSize = input('Enter HDD Size if you want extra space ') instType = input('Enter the instance type ') def createInstance():...
0
2016-10-13T18:19:13Z
40,030,610
<p>you can the following </p> <pre><code>def createInstance(): instance = ec2.create_instances( ImageId=AMI, InstanceType = instType, SubnetId='subnet-31d3ad3', DisableApiTermination=True, SecurityGroupIds=['sg-sa4q36fc'], KeyName='key' ) # return respo...
0
2016-10-13T20:42:47Z
[ "python", "amazon-ec2", "boto", "boto3" ]
How can I sort lines by the len of a field of each line? Python
40,028,281
<p>I have one code that should print out 10 lines sorted in ascending order from shortest to longest. I have a test text and I want to order the output lines using the len of the field in the position line[4] but I don´t know how to do it because I think I need to read the entire text and after to order the lines in f...
0
2016-10-13T18:23:34Z
40,028,415
<p>Change your mapper method to this</p> <pre><code>def mapper(): reader = csv.reader(sys.stdin, delimiter='\t') writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) for line in sorted(list(reader), key=lambda x: len(x[-2])): writer.writerow(line) </code></pre>
0
2016-10-13T18:30:12Z
[ "python" ]
How to get the x and y intercept in matplotlib?
40,028,330
<p>I have scoured the internet and can't find a python command to find the x and y intercepts of a curve on matplotlib. Is there a command that exists? or is there a much easier way that is going over my head? Any help would be appreciated. Thanks, </p> <p>Nimrodian.</p>
1
2016-10-13T18:25:56Z
40,028,408
<p>Use this. Much faster:</p> <pre><code>slope, intercept = np.polyfit(x, y, 1) </code></pre>
1
2016-10-13T18:29:56Z
[ "python", "matplotlib" ]
How to get the x and y intercept in matplotlib?
40,028,330
<p>I have scoured the internet and can't find a python command to find the x and y intercepts of a curve on matplotlib. Is there a command that exists? or is there a much easier way that is going over my head? Any help would be appreciated. Thanks, </p> <p>Nimrodian.</p>
1
2016-10-13T18:25:56Z
40,028,537
<pre><code>for x, y in zip(x_values, y_values): if x == 0 or y == 0: print(x, y) </code></pre>
0
2016-10-13T18:38:22Z
[ "python", "matplotlib" ]
Random comma inserted at character 8192 in python "json" result called from node.js
40,028,380
<p>I'm a JS developer just learning python. This is my first time trying to use node (v6.7.0) and python (v2.7.1) together. I'm using restify with python-runner as a bridge to my python virtualenv. My python script uses a RAKE NLP keyword-extraction package.</p> <p>I can't figure out for the life of me why my return d...
2
2016-10-13T18:28:22Z
40,029,368
<p>This looks suspiciously like a bug related to size of some buffer, since 8192 is a power of two.</p> <p>The main thing here is to isolate exactly where the failure is occurring. If I were debugging this, I would </p> <ol> <li><p>Take a closer look at the output from <code>json.dumps</code>, by printing several cha...
0
2016-10-13T19:28:13Z
[ "javascript", "python", "json", "node.js", "restify" ]
How to identify the name of the file which calls the function in python?
40,028,401
<p>I have a server.py which contains a function and other files like requestor1.py requestor2.py .... requestorN.py</p> <p>Server.py contains a function :</p> <pre><code>def callmeforhelp() return "I am here to help you out!" </code></pre> <p>and requestor1.py file calls the function callmeforhelp() and it has t...
0
2016-10-13T18:29:44Z
40,028,579
<p>Try it in your <code>server</code> file:</p> <pre><code>import inspect def callmeforhelp(): result = inspect.getouterframes(inspect.currentframe(), 2) print("Caller is: " + str(result[1][1])) </code></pre>
1
2016-10-13T18:40:41Z
[ "python" ]
How to identify the name of the file which calls the function in python?
40,028,401
<p>I have a server.py which contains a function and other files like requestor1.py requestor2.py .... requestorN.py</p> <p>Server.py contains a function :</p> <pre><code>def callmeforhelp() return "I am here to help you out!" </code></pre> <p>and requestor1.py file calls the function callmeforhelp() and it has t...
0
2016-10-13T18:29:44Z
40,028,603
<p>Here is a way to get at the caller's local attributes:</p> <pre><code>import sys def callmeforhelp(): print("Called from", sys._getframe(1).f_locals['__file__']) </code></pre> <p>This is a feature of CPython and is not guaranteed to be present in other language implementations.</p>
2
2016-10-13T18:41:48Z
[ "python" ]
adding data from different rows in a csv belonging to a common variable
40,028,405
<p>this is my csv excel file information:</p> <pre><code> Receipt merchant Address Date Time Total price 25007 A ABC pte ltd 3/7/2016 10:40 12.30 25008 A ABC ptd ltd 3/7/2016 11.30 6.70 25009 B CCC ptd ltd 4/7/2016 07.35 23.40 25010 A ABC pte...
0
2016-10-13T18:29:48Z
40,028,489
<pre><code>import pandas as pd df = pd.read_csv('assignment_info.csv') df = df.groupby(['merchant', 'Date', 'Time']).sum().reset_index() df </code></pre>
1
2016-10-13T18:34:53Z
[ "python", "csv", "pandas", "design-patterns", "group" ]
adding data from different rows in a csv belonging to a common variable
40,028,405
<p>this is my csv excel file information:</p> <pre><code> Receipt merchant Address Date Time Total price 25007 A ABC pte ltd 3/7/2016 10:40 12.30 25008 A ABC ptd ltd 3/7/2016 11.30 6.70 25009 B CCC ptd ltd 4/7/2016 07.35 23.40 25010 A ABC pte...
0
2016-10-13T18:29:48Z
40,028,771
<p>As the other answer points out, <code>pandas</code> is an excellent library for this kind of data manipulation. My answer won't use <code>pandas</code> though.</p> <p>A few issues:</p> <ul> <li>In your problem description, you state that you want to group by <em>three</em> columns, but in your example cases you ar...
0
2016-10-13T18:50:57Z
[ "python", "csv", "pandas", "design-patterns", "group" ]
Best way to dynamically add multiple abstract class instances to inheriting class instance
40,028,433
<p>I spent quite a bit of time looking for an answer to this question but am unsure of even what it is exactly that I'm looking for. I may even be approaching this entirely wrong by using abstract classes so clarification in any way will be helpful.</p> <p>I want to allow users to add multiple symptoms and treatments ...
0
2016-10-13T18:31:09Z
40,030,487
<p>Based on your requirement, I would propose have a Disease model with many to many to fields to Symptoms and Treatments model. <a href="https://docs.djangoproject.com/en/1.10/topics/db/models/#relationships" rel="nofollow">Read more about django model relationships here</a>. So your models should look like,</p> <pre...
1
2016-10-13T20:34:53Z
[ "python", "django", "inheritance", "django-models" ]
Import Pandas on apache server causes timeout error
40,028,497
<p>I've got a Django project working on an Apache server.</p> <p>I installed pandas and want to use it to start manipulating data - however something odd is happening.</p> <p>Anytime I use the <code>import pandas</code> on the production environment, the server will hang up and (after a while) throw a 408 timeout err...
0
2016-10-13T18:35:44Z
40,031,407
<p>Try adding:</p> <pre><code>WSGIApplicationGroup %{GLOBAL} </code></pre> <p>Various of the scientific packages that it is going to need will not work in Python sub interpreters. That directive will force the use of the main interpreter context.</p>
2
2016-10-13T21:35:29Z
[ "python", "django", "apache", "pandas", "mod-wsgi" ]
Pythonic way around Enums
40,028,498
<p>What is the <em>pythonic</em> way to tell the caller of a function what values a given parameter supports?</p> <p>He is an example for PyQt (for GUI). Say I have a checkbox, </p> <pre><code>class checkbox(object): .... def setCheckState(self, value): .... </code></pre> <p>Here, <code>setCheckState...
2
2016-10-13T18:35:46Z
40,029,336
<p>The <em>One Obvious Way</em> is function annotations.</p> <pre><code>class CheckBox(enum.Enum): Off = 0 On = 1 def setCheckState(self, value: CheckBox): ... </code></pre> <p>This says quite clearly that <code>value</code> should be an instance of <code>CheckBox</code>. Having <code>Enum</code> just m...
1
2016-10-13T19:25:52Z
[ "python", "python-2.7", "function", "parameters", "enums" ]
Pythonic way around Enums
40,028,498
<p>What is the <em>pythonic</em> way to tell the caller of a function what values a given parameter supports?</p> <p>He is an example for PyQt (for GUI). Say I have a checkbox, </p> <pre><code>class checkbox(object): .... def setCheckState(self, value): .... </code></pre> <p>Here, <code>setCheckState...
2
2016-10-13T18:35:46Z
40,030,794
<p>That will do the trick</p> <pre><code>import collections def create_enum(container, start_num, *enum_words): return collections.namedtuple(container, enum_words)(*range(start_num, start_num + len(enum_words))) Switch = create_enum('enums', 1, 'On', 'Off') </code></pre> <p><em>Switch</em> is your enum:</p> <...
0
2016-10-13T20:53:56Z
[ "python", "python-2.7", "function", "parameters", "enums" ]
Filtering syntax for pandas dataframe groupby with logic condition
40,028,500
<p>I have a pandas dataframe containing indices that have a one-to-many relationship. A very simplified and shortened example of my data is shown in the <a href="https://i.stack.imgur.com/7z1ih.jpg" rel="nofollow">DataFrame Example</a> link. I want to get a list or Series or ndarray of the unique namIdx values in whi...
1
2016-10-13T18:35:54Z
40,028,734
<p>I think your code works nice, only you can add use small changes:</p> <p>In <code>all</code> can be omit <code>axis=0</code><br> <code>grouped==True</code> can be omit <code>==True</code> </p> <pre><code>grouped=(namToViirs['nCldLayers']&lt;=1).groupby(level='namldx').all() grouped = grouped[grouped] filterIndex ...
1
2016-10-13T18:49:08Z
[ "python", "pandas", "dataframe" ]
Filtering syntax for pandas dataframe groupby with logic condition
40,028,500
<p>I have a pandas dataframe containing indices that have a one-to-many relationship. A very simplified and shortened example of my data is shown in the <a href="https://i.stack.imgur.com/7z1ih.jpg" rel="nofollow">DataFrame Example</a> link. I want to get a list or Series or ndarray of the unique namIdx values in whi...
1
2016-10-13T18:35:54Z
40,028,939
<p>For question 1, see jezrael answer. For question 2, you could play with indexes as sets:</p> <pre><code>namToViirs.index[namToViirs.nCldLayers &lt;= 1] \ .difference(namToViirs.index[namToViirs.nCldLayers &gt; 1]) </code></pre>
0
2016-10-13T19:01:44Z
[ "python", "pandas", "dataframe" ]
Comparing two large text files column by column in Python
40,028,560
<p>I have two large tab separated text files with dimensions : 36000 rows x 3000 columns. The structure of the columns is same in both files but they may not be sorted.</p> <p>I need to <em>compare only the numeric columns</em> between these two files(apprx 2970 columns) and export out those rows where there is a diff...
0
2016-10-13T18:39:26Z
40,028,745
<p>First of all, if files are that big, they should be read row by row.</p> <p>Reading one file row by row is simple:</p> <pre><code>with open(...) as f: for row in f: ... </code></pre> <p>To iterate two files row by row, zip them:</p> <pre><code>with open(...) as f1, open(...) as f2: for row1, row2...
1
2016-10-13T18:49:46Z
[ "python", "compare", "large-files" ]
possible to compile python.exe without Visual Studio, with MinGw
40,028,671
<p>I am trying to achieve things laid out on this page: <a href="https://blogs.msdn.microsoft.com/pythonengineering/2016/04/26/cpython-embeddable-zip-file/" rel="nofollow">https://blogs.msdn.microsoft.com/pythonengineering/2016/04/26/cpython-embeddable-zip-file/</a></p> <p>The code I am trying to compile is just this:...
-1
2016-10-13T18:46:03Z
40,065,866
<p>The error is unrelated to Python. <code>wmain</code> is Visual Studio specific. GCC does not treat <code>wmain</code> as entry point, it just sits there as a function which never gets called.</p> <p>GCC requires <code>main</code> or <code>WinMain</code> as entry point. If neither of those entry points is found, the...
0
2016-10-16T01:16:24Z
[ "python", "c++", "c", "visual-studio", "mingw" ]
Python string assignment error occurs on second loop, but not first
40,028,690
<p>The first run-through of the while loop goes fine:</p> <pre><code>hour_count = list('00/') hours = 0 while hours &lt; 24: #loop while hours &lt; 24 hour_count[1] = hours #&lt;- error occurs on this line hour_count = ''.join(hour_count) #convert to string ... hours += ...
-3
2016-10-13T18:46:50Z
40,028,743
<p>When you run this line <code>hour_count = ''.join(hour_count)</code>, you're changing the data type of <code>hour_count</code> from a list to a string.</p> <p>Because strings are immutable, you can't modify one character via the index notation (the line before this line attempts to do that).</p> <p>I'm not totally...
1
2016-10-13T18:49:35Z
[ "python", "python-3.x", "typeerror" ]
Python string assignment error occurs on second loop, but not first
40,028,690
<p>The first run-through of the while loop goes fine:</p> <pre><code>hour_count = list('00/') hours = 0 while hours &lt; 24: #loop while hours &lt; 24 hour_count[1] = hours #&lt;- error occurs on this line hour_count = ''.join(hour_count) #convert to string ... hours += ...
-3
2016-10-13T18:46:50Z
40,028,761
<p>You changed the type;</p> <pre><code># hour_count at this point is an array hour_count[1] = hours # The result of join is a string object hour_count = ''.join(hour_count) </code></pre> <p>Next time through <code>hour_count</code> is a string and you can't do "string[1] = ..."</p>
0
2016-10-13T18:50:33Z
[ "python", "python-3.x", "typeerror" ]
Suppressing Pandas dataframe plot output
40,028,727
<p>I am plotting a dataframe:</p> <pre><code> ax = df.plot() fig = ax.get_figure() fig.savefig("{}/{}ts.png".format(IMGPATH, series[pfxlen:])) </code></pre> <p>It works fine. But, on the console, I get:</p> <pre><code>/usr/lib64/python2.7/site-packages/matplotlib/axes.py:2542: UserWarning: At...
0
2016-10-13T18:48:25Z
40,029,101
<p>Those aren't errors, but warnings. If you aren't concerned by those and just want to silence them, it's as simple as:</p> <pre><code>import warnings warnings.filterwarnings('ignore') </code></pre> <p>Additionally, pandas and other libraries may trigger NumPY floating-point errors. If you encounter those, you have ...
2
2016-10-13T19:12:31Z
[ "python", "pandas" ]
Format certain JSON objects on one line
40,028,755
<p>Consider the following code:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; data = { ... 'x': [1, {'$special': 'a'}, 2], ... 'y': {'$special': 'b'}, ... 'z': {'p': True, 'q': False} ... } &gt;&gt;&gt; print(json.dumps(data, indent=2)) { "y": { "$special": "b" }, "z": { "q": false, ...
2
2016-10-13T18:50:10Z
40,029,630
<p>You can do it, but you'd basically have to copy/modify a lot of the code out of <code>json.encoder</code> because the encoding functions aren't really designed to be partially overridden.</p> <p>Basically, copy the entirety of <code>_make_iterencode</code> from <code>json.encoder</code> and make the changes so that...
0
2016-10-13T19:44:05Z
[ "python", "json", "python-3.x", "formatting" ]
Format certain JSON objects on one line
40,028,755
<p>Consider the following code:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; data = { ... 'x': [1, {'$special': 'a'}, 2], ... 'y': {'$special': 'b'}, ... 'z': {'p': True, 'q': False} ... } &gt;&gt;&gt; print(json.dumps(data, indent=2)) { "y": { "$special": "b" }, "z": { "q": false, ...
2
2016-10-13T18:50:10Z
40,030,695
<p>The <code>json</code> module is not really designed to give you that much control over the output; indentation is mostly meant to aid readability while debugging.</p> <p>Instead of making <code>json</code> produce the output, you could <em>transform</em> the output using the standard library <a href="https://docs.p...
2
2016-10-13T20:48:30Z
[ "python", "json", "python-3.x", "formatting" ]
Format certain JSON objects on one line
40,028,755
<p>Consider the following code:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; data = { ... 'x': [1, {'$special': 'a'}, 2], ... 'y': {'$special': 'b'}, ... 'z': {'p': True, 'q': False} ... } &gt;&gt;&gt; print(json.dumps(data, indent=2)) { "y": { "$special": "b" }, "z": { "q": false, ...
2
2016-10-13T18:50:10Z
40,114,245
<p>I found the following regex-based solution to be simplest, albeit &hellip; <em>regex-based</em>.</p> <pre><code>import json import re data = { 'x': [1, {'$special': 'a'}, 2], 'y': {'$special': 'b'}, 'z': {'p': True, 'q': False} } text = json.dumps(data, indent=2) pattern = re.compile(r""" { \s* "\$speci...
0
2016-10-18T17:11:36Z
[ "python", "json", "python-3.x", "formatting" ]
django - subclassing a model just to add new methods
40,028,828
<p>I need to subclass a model from a third-party app (<code>django-oscar</code>).</p> <p>If i do this</p> <pre><code>from oscar.apps.catalogue.models import Category class NewCategory(Category): @property def product_count(self): return self.product_set.all().count() class Meta: db_table...
0
2016-10-13T18:54:17Z
40,029,027
<p>You need a <a href="https://docs.djangoproject.com/en/1.10/topics/db/models/#proxy-models" rel="nofollow">proxy model</a>.</p> <pre><code>class NewCategory(Category): class Meta: proxy = True ... </code></pre>
1
2016-10-13T19:08:05Z
[ "python", "django" ]
Unable to import matplotlib.pyplot with latest conda
40,028,842
<p>I am running Conda version 4.2.9 with Python 2.7.12, I have confirmed this bug with a fresh conda environment and only the matplotlib package</p> <p>My problem occurs when I try to import matplotlib.pyplot:</p> <pre><code>&gt;&gt;&gt; import matplotlib.pyplot Traceback (most recent call last): File "&lt;stdin&gt...
0
2016-10-13T18:55:25Z
40,043,798
<p>Pinning packages is explained <a href="http://conda.pydata.org/docs/faq.html#pinning-packages" rel="nofollow">here</a>.</p> <p><a href="https://github.com/ContinuumIO/anaconda-recipes/blob/master/matplotlib/rctmp_pyside.patch" rel="nofollow">The patch</a> is so small you can apply it by hand. Look for your <a href=...
0
2016-10-14T12:58:38Z
[ "python", "matplotlib", "pyqt", "conda" ]
Automatic Image Inpainting with Keras and GpuElemwise Errors
40,028,847
<p>I have a Keras Model => </p> <blockquote> <p>Input : Gray Image : (1, 224, 224) </p> <p>Output : RGB Image: (3, 224, 224)</p> </blockquote> <p>and I want to predict pixel colors by giving it Grayscale images and getting RGB ones. I tried to make a network in Keras which mostly resembles <a href="http://tiny...
0
2016-10-13T18:55:55Z
40,032,259
<p>You are merging on the wrong axis. <code>axis = 0</code> is actually the axis with different samples. You can see from your model:</p> <pre><code>batch2 (BatchNormalization) (None, 256, 28, 28) 512 maxpooling2d_3[0][0] upsample1 (UpSampling2D) (None, 256, 28, 28) 0 re...
2
2016-10-13T22:48:52Z
[ "python", "machine-learning", "theano", "keras", "conv-neural-network" ]
SQLAlchemy Delete Persistency Error
40,028,868
<p>For some reason the code below is generating a persistency error:</p> <pre><code>'&lt;Data at 0x1041db8d0&gt;' is not persisted </code></pre> <p>Does the object need to be initialized before it's deleted, what's wrong here?</p> <pre><code>if request.method == 'POST' and form3.validate(): data_entered = Data(n...
-1
2016-10-13T18:57:15Z
40,029,915
<p><code>data_entered = Data(notes=form3.dbDelete.data)</code></p> <p>This is creating a new instance (or row) of <code>Data</code>. Then you are running a <code>session.delete</code> procedure to remove it from the database, but it never was inserted (via <code>session.commit()</code> for example).</p> <p>I'm guessi...
0
2016-10-13T20:01:12Z
[ "python", "sqlalchemy" ]
Multiprocessing in Flask
40,028,869
<p>Probably, this was repeated in a different way. May I know where am I goin wrong? Following is the code and the error</p> <p><strong>CODE:</strong></p> <pre><code>from flask import Flask, render_template import thread from multiprocessing import Process app = Flask(__name__) def print_time(): i = 0 while 1...
-5
2016-10-13T18:57:17Z
40,029,118
<p>The code mixes tabs and spaces.</p> <p>These two lines:</p> <pre><code> def index(): return 'Index Page' </code></pre> <p>Are actually:</p> <pre><code>[tab]def index(): [tab]return 'Index Page' </code></pre> <p>When tabs are used in Python source code, they are first replaced with spaces until th...
1
2016-10-13T19:13:18Z
[ "python", "flask", "multiprocessing" ]
Pushing to Diego: Cannot write: No space left on device
40,028,883
<p>Our application is one of the few left running on DEA. On DEA we were able to use a specific custom buildbpack:</p> <p><a href="https://github.com/ihuston/python-conda-buildpack" rel="nofollow">https://github.com/ihuston/python-conda-buildpack</a></p> <p>Now that we have to move on Diego runtime, we run out of spa...
0
2016-10-13T18:58:14Z
40,037,302
<p>You can use a <code>.cfignore</code> file just like a <code>.gitignore</code> file to exclude any unneeded files from being <code>cf push</code>ed. Maybe if you really only push what is necessary, the disk space could be sufficient.</p> <p><a href="https://docs.developer.swisscom.com/devguide/deploy-apps/prepare-to...
0
2016-10-14T07:24:08Z
[ "python", "swisscomdev" ]
Pushing to Diego: Cannot write: No space left on device
40,028,883
<p>Our application is one of the few left running on DEA. On DEA we were able to use a specific custom buildbpack:</p> <p><a href="https://github.com/ihuston/python-conda-buildpack" rel="nofollow">https://github.com/ihuston/python-conda-buildpack</a></p> <p>Now that we have to move on Diego runtime, we run out of spa...
0
2016-10-13T18:58:14Z
40,038,542
<p>The conda installer from <a href="https://github.com/ihuston/python-conda-buildpack" rel="nofollow">https://github.com/ihuston/python-conda-buildpack</a> installs by default with the Intel MKL library. Now this is usually a good thing, but seemingly uses too much space and thus cannot be deployed. </p> <p>I adapted...
1
2016-10-14T08:30:56Z
[ "python", "swisscomdev" ]
How to run a script in PySpark
40,028,919
<p>I'm trying to run a script in the pyspark environment but so far I haven't been able to. How can I run a script like python script.py but in pyspark? Thanks</p>
0
2016-10-13T19:00:45Z
40,029,121
<p>You can do: <code>./bin/spark-submit mypythonfile.py</code></p> <p>Running python applications through 'pyspark' is not supported as of Spark 2.0.</p>
2
2016-10-13T19:13:28Z
[ "python", "apache-spark", "pyspark" ]
port scanning an IP range in python
40,028,975
<p>So I'm working on a simple port scanner in python for a class (not allowed to use the python-nmap library), and while I can get it to work when passing a single IP address, I can't get it to work using a range of IPs. </p> <p>This is what I have:</p> <pre><code>#!/usr/bin/env python from socket import * from netad...
0
2016-10-13T19:04:34Z
40,047,252
<p>The problem turned out to be an issue with using the netaddr.IPRange, as suggested by @bravosierra99. </p> <p>Thanks again everyone!</p>
0
2016-10-14T15:48:23Z
[ "python", "python-2.7", "port-scanning" ]
Python2: Using .decode with errors='replace' still returns errors
40,029,017
<p>So I have a <code>message</code> which is read from a file of unknown encoding. I want to send to a webpage for display. I've grappled a lot with UnicodeErrors and have gone through many Q&amp;As on StackOverflow and think I have decent understand of how Unicode and encoding works. My current code looks like this</p...
0
2016-10-13T19:07:18Z
40,029,494
<p>decode with error replace implements the 'replace' error handling (for <strong>text encodings</strong> only): substitutes '?' for encoding errors (to be encoded by the codec), and '\ufffd' (the Unicode replacement character) for decoding errors</p> <p>text encodings means A "codec which encodes Unicode strings to b...
0
2016-10-13T19:36:07Z
[ "python", "python-2.7", "unicode", "character-encoding" ]
Python2: Using .decode with errors='replace' still returns errors
40,029,017
<p>So I have a <code>message</code> which is read from a file of unknown encoding. I want to send to a webpage for display. I've grappled a lot with UnicodeErrors and have gone through many Q&amp;As on StackOverflow and think I have decent understand of how Unicode and encoding works. My current code looks like this</p...
0
2016-10-13T19:07:18Z
40,038,844
<p>You should not get a <code>UnicodeDecodeError</code> with <code>errors='replace'</code>. Also <code>str.decode('latin-1')</code> should never fail, because ISO-8859-1 has a valid character mapping for every possible byte sequence.</p> <p>My suspicion is that <code>message</code> is already a <code>unicode</code> st...
0
2016-10-14T08:46:26Z
[ "python", "python-2.7", "unicode", "character-encoding" ]
Setting Series as index
40,029,071
<p>I'm using python 2.7 to take a numerical column of my dataframe <code>data</code> and make it an individual object (series) with an index of dates that is another column from <code>data</code>. </p> <pre><code>new_series = pd.Series(data['numerical_column'] , index=data['dates']) </code></pre> <p>However, when I d...
2
2016-10-13T19:11:12Z
40,029,176
<p>I think there is problem with not align index of column <code>data['numerical_column']</code>.</p> <p>So need convert it to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a>:</p> <pre><code>new_series = pd.Se...
2
2016-10-13T19:16:36Z
[ "python", "python-2.7", "pandas", "dataframe", "series" ]
Python string formatting trim float precision to no more than needed
40,029,245
<p>What's the best way to convert a float to a string with no more precision than needed to represent the number, and never more than a specified upper limit precision such that the following would happen?</p> <pre><code>&gt;&gt;&gt; values = [1, 1., 1.01, 1.00000000001, 1.123456789, 100.123456789] &gt;&gt;&gt; print(...
0
2016-10-13T19:20:16Z
40,029,293
<p>I don't believe there is a built-in option, but you could just use <code>string.rstrip</code> to remove the trailing zeros from the normal string representation of the float.</p> <p>EDIT: You would also need to format it to the fixed maximum precision using the %f formatting token before using <code>string.rstrip</...
1
2016-10-13T19:23:07Z
[ "python", "string", "string-formatting" ]
Python string formatting trim float precision to no more than needed
40,029,245
<p>What's the best way to convert a float to a string with no more precision than needed to represent the number, and never more than a specified upper limit precision such that the following would happen?</p> <pre><code>&gt;&gt;&gt; values = [1, 1., 1.01, 1.00000000001, 1.123456789, 100.123456789] &gt;&gt;&gt; print(...
0
2016-10-13T19:20:16Z
40,029,303
<p>Does <code>rstrip</code>-ing the <code>str.format</code> version do what you want? E.g.,</p> <pre><code>'{:0.6f}'.format(num).rstrip('0').rstrip('.') </code></pre>
2
2016-10-13T19:23:46Z
[ "python", "string", "string-formatting" ]
Split and keep deliminator, preferably with regex
40,029,387
<p>Let's say I have this text:</p> <pre><code>1.1 This is the 2,1 first 1.2 This is the 2,2 second 1.3 This is the 2,3 third </code></pre> <p>and I want:</p> <pre><code>["1.1 This is the 2,1 first","1.2 This is the 2,2 second","1.3 This is the 2,3 third"] </code></pre> <p>Note that:</p> <ul> <li><p>I can't use <...
0
2016-10-13T19:29:09Z
40,029,469
<p>Yes, you can:</p> <pre><code>\b\d+\.\d+ .+?(?=\d+\.\d+|$) </code></pre> <p>See it <a href="https://regex101.com/r/ABNxgQ/1" rel="nofollow"><strong>working on regex101.com</strong></a>. To be used in addition to <code>re.findall()</code>:</p> <pre><code>import re rx = re.compile(r'\b\d+\.\d+.+?(?=\d+\.\d+|$)') str...
2
2016-10-13T19:34:47Z
[ "python", "regex" ]
Split and keep deliminator, preferably with regex
40,029,387
<p>Let's say I have this text:</p> <pre><code>1.1 This is the 2,1 first 1.2 This is the 2,2 second 1.3 This is the 2,3 third </code></pre> <p>and I want:</p> <pre><code>["1.1 This is the 2,1 first","1.2 This is the 2,2 second","1.3 This is the 2,3 third"] </code></pre> <p>Note that:</p> <ul> <li><p>I can't use <...
0
2016-10-13T19:29:09Z
40,036,092
<p>split with blank whose right is 1.2 2.2 ...</p> <pre><code>re.split(r' (?=\d.\d)',s) </code></pre>
0
2016-10-14T06:10:23Z
[ "python", "regex" ]
JSON.Dump doesn't capture the whole stream
40,029,399
<p>So I have a simple crawler that crawls 3 store location pages and parses the locations of the stores to json. I print(app_data['stores']) and it prints all three pages of stores. However, when I try to write it out I only get one of the three pages, at random, written to my json file. I'd like everything that str...
0
2016-10-13T19:29:45Z
40,029,558
<p>You are opening the file for writing every time, but you want to append. Try changing the last part to this:</p> <pre><code>with open('stores.json', 'a') as f: json.dump(app_data['stores'], f, indent=4) </code></pre> <p>Where <code>'a'</code> opens the file for appending.</p>
0
2016-10-13T19:39:49Z
[ "python", "json", "scrapy", "js2xml" ]
How to use multiple token using Regex Expression
40,029,483
<p>To extract first three letters 'abc' and three sets of three-digits numbers in <code>000_111_222</code> I am using the following expression:</p> <pre><code>text = 'abc_000_111_222' print re.findall('^[a-z]{3}_[0-9]{3}_[0-9]{3}_[0-9]{3}', text) </code></pre> <p>But the expression returns empty list when instead of ...
0
2016-10-13T19:35:15Z
40,029,572
<p>You can use regex character classes with <code>[</code>...<code>]</code>. For your case, it can be <code>[_.-]</code> (note the hyphen at the end, if it isn't at the end, it will be considered as a range like <code>[a-z]</code>).</p> <p>You can use a regex like this:</p> <pre><code>print re.findall('^[a-z]{3}[_.-]...
3
2016-10-13T19:40:32Z
[ "python", "regex" ]
How to use multiple token using Regex Expression
40,029,483
<p>To extract first three letters 'abc' and three sets of three-digits numbers in <code>000_111_222</code> I am using the following expression:</p> <pre><code>text = 'abc_000_111_222' print re.findall('^[a-z]{3}_[0-9]{3}_[0-9]{3}_[0-9]{3}', text) </code></pre> <p>But the expression returns empty list when instead of ...
0
2016-10-13T19:35:15Z
40,051,125
<p>Why not abandon <code>regexes</code> altogether, and use a clearer and simpler solution?</p> <pre><code>$ cat /tmp/tmp.py SEP = '_.,;-=+' def split_str(text): for s in list(SEP): res = text.split(s) if len(res) &gt; 1: return text.split(s) print(split_str('abc_000_111_222')) print(...
-1
2016-10-14T20:00:56Z
[ "python", "regex" ]
Upgrading pip You are using pip version 7.1.2 to version 8.1.2
40,029,526
<p>Hi I am trying to upgrade my pip version to 8.1.2 this command does not work: pip install --upgrade pip </p> <p>And I also tried to get it directly from the github directory, like explained here <a href="https://github.com/pypa/pip/archive/8.1.1.zip" rel="nofollow">https://github.com/pypa/pip/archive/8.1.1.zi...
0
2016-10-13T19:38:09Z
40,029,600
<p>Try to open command prompt as an administrator, then try upgrade it, should works.</p>
0
2016-10-13T19:42:01Z
[ "python", "terminal", "install", "pip" ]
Upgrading pip You are using pip version 7.1.2 to version 8.1.2
40,029,526
<p>Hi I am trying to upgrade my pip version to 8.1.2 this command does not work: pip install --upgrade pip </p> <p>And I also tried to get it directly from the github directory, like explained here <a href="https://github.com/pypa/pip/archive/8.1.1.zip" rel="nofollow">https://github.com/pypa/pip/archive/8.1.1.zi...
0
2016-10-13T19:38:09Z
40,029,634
<p>Your problem is that your user doesn't have write privileges to the <code>/Library/Python/2.7/site-packages</code> directory. That is what it means by <code>[Errno 13] Permission denied</code></p> <p>Try running the command with <code>sudo</code> prefixing the original command. Sudo allows you to safely run program...
0
2016-10-13T19:44:30Z
[ "python", "terminal", "install", "pip" ]
Upgrading pip You are using pip version 7.1.2 to version 8.1.2
40,029,526
<p>Hi I am trying to upgrade my pip version to 8.1.2 this command does not work: pip install --upgrade pip </p> <p>And I also tried to get it directly from the github directory, like explained here <a href="https://github.com/pypa/pip/archive/8.1.1.zip" rel="nofollow">https://github.com/pypa/pip/archive/8.1.1.zi...
0
2016-10-13T19:38:09Z
40,029,669
<p>You can follow it up with:</p> <pre><code>pip install -U pip sudo !! </code></pre> <p>This has the same effect as:</p> <pre><code>sudo pip install -U pip </code></pre> <p>Or even better, move away from OS X's Python install, and instead install Python / pip via <a href="http://brew.sh/" rel="nofollow">Homebrew</...
0
2016-10-13T19:46:52Z
[ "python", "terminal", "install", "pip" ]
How to avoid StaleElementReferenceException in Selenium - Python
40,029,549
<p>I am stuck in writing a Python Selenium script and can't seem to satisfactorily resolve this StaleElementReferenceException I am getting. </p> <p>I have my page loaded and click a button which opens a form that allows the user to add a new credit card to the order. At this point I do a WebDriverWait to pause the ...
1
2016-10-13T19:39:29Z
40,070,927
<p>A StaleElementReferenceException is thrown when the element you were interacting is destroyed and then recreated. Most complex web pages these days will move things about on the fly as the user interacts with it and this requires elements in the DOM to be destroyed and recreated.</p> <p>Try doing</p> <pre><code>wa...
1
2016-10-16T13:41:02Z
[ "python", "selenium" ]
how do I reset a input in python
40,029,550
<p>so i have this code that basically consists of you asking questions, but i have it so the input answers the question, so you can only ask one question, then you have to reset the whole thing again and again, and i have it to ask you your name first so i want a loop that ignores that.</p> <pre><code> print("hello...
-3
2016-10-13T19:39:31Z
40,029,607
<p>Take out the <code>break</code>s. Then have one of the options be "quit" with a <code>break</code></p>
-1
2016-10-13T19:42:21Z
[ "python" ]
how do I reset a input in python
40,029,550
<p>so i have this code that basically consists of you asking questions, but i have it so the input answers the question, so you can only ask one question, then you have to reset the whole thing again and again, and i have it to ask you your name first so i want a loop that ignores that.</p> <pre><code> print("hello...
-3
2016-10-13T19:39:31Z
40,029,619
<pre><code>print("hello,what is your name?") name = input() print("hello",name) while True: question = input("ask me anything:") if question == ("what is love"): print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name) elif question == ("i want a dog"): print("ask...
0
2016-10-13T19:43:13Z
[ "python" ]
how do I reset a input in python
40,029,550
<p>so i have this code that basically consists of you asking questions, but i have it so the input answers the question, so you can only ask one question, then you have to reset the whole thing again and again, and i have it to ask you your name first so i want a loop that ignores that.</p> <pre><code> print("hello...
-3
2016-10-13T19:39:31Z
40,029,625
<p>Get rid of the <code>break</code>s, so the loop keeps prompting for new questions. For performance, change the subsequent <code>if</code> tests to <code>elif</code> tests (not strictly necessary, but it avoids rechecking the string if you get a hit early on):</p> <pre><code>while True: question = input("ask me ...
3
2016-10-13T19:43:47Z
[ "python" ]
How to update `xarray.DataArray` using `.sel()` indexer?
40,029,618
<p>I found the easiest way to visualize creating a <code>N-dimensional</code> <code>DataArray</code> was to make a <code>np.ndarray</code> and then fill in the values by the coordinates I've created. When I tried to actually do it, I couldn't figure out how to update the <code>xr.DataArray</code>.</p> <p><strong>How ...
1
2016-10-13T19:43:04Z
40,030,606
<p>This is really awkward, due to the unfortunate limitation of Python syntax that keyword arguments are not supported in inside square bracket.</p> <p>So instead, you need to put the arguments to <code>.sel</code> as a dictionary in <code>.loc</code> instead:</p> <pre><code>DA.loc[dict(axis_A="A_1", axis_B="B_1", ax...
2
2016-10-13T20:42:41Z
[ "python", "database", "numpy", "dataframe", "python-xarray" ]
Function to find the factors of a negative number
40,029,623
<p>I need to write a function that will find the factors for a negative number and output them to a list. How would I do that? I can get my function to do positive numbers (see below) but not negative ones.</p> <pre><code>#Finds factors for A and C def factorspos(x): factorspos = [1,-6]; print("The factors of"...
1
2016-10-13T19:43:34Z
40,030,772
<pre><code>def factorspos(x): x = int(x) factorspos = [] print("The factors of",x,"are:") if x &gt; 0: # if input is postive for i in range(1,x+1): if x % i == 0: factorspos.append(i) print(i) return factorspos elif x &lt; 0: #if input is n...
1
2016-10-13T20:52:29Z
[ "python", "python-3.x" ]
Use eval with dictionary without losing imported modules in Python2
40,029,746
<p>I have a string to be executed inside my python program and I want to change some variables in the string like x[1], x[2] to something else. I had previously used eval with 2 arguments (the second being a dict with replaced_word: new_word) but now I noticed I can't use previously imported modules like this. So if I ...
0
2016-10-13T19:51:05Z
40,029,834
<p>Build your globals <code>dict</code> with <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow"><code>globals()</code></a> as a base:</p> <pre><code>from math import log # Copy the globals() dict so changes don't affect real globals eval_globals = globals().copy() # Tweak the copy to ad...
1
2016-10-13T19:56:48Z
[ "python", "eval", "python-2.x" ]
Freeing memory in python parallel process loops
40,029,768
<p>I'm using a master-slaves structure to implement a parallel computation. A single master process (<code>0</code>) loads data, and distributes relevant chunks and instructions to slave processes (<code>1</code>-<code>N</code>) which do the heavy lifting, using large objects... blah blah blah. The issue is memory us...
0
2016-10-13T19:52:30Z
40,030,013
<p><code>del _gwb</code> should make a big difference. With <code>_gwb = Large_Data_Structure(task)</code> the new data is generated and then assigned to _gwd. Only then is the old data released. A specific <code>del</code> will get rid of the object early. You may still see a memory increase for the second loop - pyth...
1
2016-10-13T20:06:57Z
[ "python", "performance", "memory", "parallel-processing", "numerical-methods" ]
Change Array of multi integer vectors to single value for each vector in Numpy
40,029,777
<p>I have an array below, which I want to make each row randomly have a single 1 or all zeros, but only the current 1 values can be converted to 0. I have a check below that was going to do this by seeing if there is a 1 in the row and if the summed value is greater or = to 0. I am hoping there is a simple approach to...
1
2016-10-13T19:52:58Z
40,032,617
<p>You can randomly select per row the column you want to keep:</p> <pre><code>m, n = A.shape J = np.random.randint(n, size=m) </code></pre> <p>You can use these to create a new array:</p> <pre><code>I = np.arange(m) B = np.zeros_like(A) B[I,J] = A[I,J] </code></pre> <p>Or if you want to modify <code>A</code>, e.g....
0
2016-10-13T23:25:09Z
[ "python", "numpy" ]
Why does the class definition's metaclass keyword argument accept a callable?
40,029,807
<h2>Background</h2> <p>The Python 3 <a href="https://docs.python.org/3.6/reference/datamodel.html#determining-the-appropriate-metaclass">documentation</a> clearly describes how the metaclass of a class is determined:</p> <blockquote> <ul> <li>if no bases and no explicit metaclass are given, then type() is used</l...
8
2016-10-13T19:54:43Z
40,030,066
<p>Well, the <code>type</code> is of course <code>MyMetaClass</code>. <code>metaclass_callable</code> is initially 'selected' as the metaclass since <a href="https://github.com/python/cpython/blob/master/Python/bltinmodule.c#L100" rel="nofollow">it's been specified in the <code>metaclass</code> kwarg</a> and as such, i...
2
2016-10-13T20:10:23Z
[ "python", "class", "python-3.x", "metaclass" ]
Why does the class definition's metaclass keyword argument accept a callable?
40,029,807
<h2>Background</h2> <p>The Python 3 <a href="https://docs.python.org/3.6/reference/datamodel.html#determining-the-appropriate-metaclass">documentation</a> clearly describes how the metaclass of a class is determined:</p> <blockquote> <ul> <li>if no bases and no explicit metaclass are given, then type() is used</l...
8
2016-10-13T19:54:43Z
40,030,142
<p>Regarding your first question the metaclass should be <code>MyMetaclass</code> (which it's so):</p> <pre><code>In [7]: print(type(MyClass), type(MyDerived)) &lt;class '__main__.MyMetaclass'&gt; &lt;class '__main__.MyMetaclass'&gt; </code></pre> <p>The reason is that if the metaclass is not an instance of type pyth...
7
2016-10-13T20:14:46Z
[ "python", "class", "python-3.x", "metaclass" ]
Why does the class definition's metaclass keyword argument accept a callable?
40,029,807
<h2>Background</h2> <p>The Python 3 <a href="https://docs.python.org/3.6/reference/datamodel.html#determining-the-appropriate-metaclass">documentation</a> clearly describes how the metaclass of a class is determined:</p> <blockquote> <ul> <li>if no bases and no explicit metaclass are given, then type() is used</l...
8
2016-10-13T19:54:43Z
40,031,127
<p>Concerning question 1, I think the "metaclass" of a class <code>cls</code> should be understood as <code>type(cls)</code>. That way of understanding is compatible with Python's error message in the following example:</p> <pre><code>&gt;&gt;&gt; class Meta1(type): pass ... &gt;&gt;&gt; class Meta2(type): pass ... ...
2
2016-10-13T21:15:49Z
[ "python", "class", "python-3.x", "metaclass" ]
How to properly import sub-modules in a Python package?
40,029,862
<p>I am a bit lost about how I should import and organise my sub-modules and I need some literature and some conventions.</p> <h2>The problem</h2> <p>We want to write a new package written in Python that is composed of several components: </p> <ul> <li>Classes and functions useful for the end user</li> <li>Classes a...
0
2016-10-13T19:58:09Z
40,030,121
<blockquote> <p>Both of these methods are common, but it may pollute the pizzafactory namespace, so it may be preferable to mangle the import names. I relalized that nobody does that and I don't know why.</p> </blockquote> <p>Python is a consenting adult language, we leave the doors unlocked and everything out in th...
1
2016-10-13T20:13:40Z
[ "python", "module", "package", "packages", "python-import" ]
Understanding why tensorflow RNN is not learning toy data
40,029,904
<p>I am trying to train a Recurrent Neural Network using Tensorflow (r0.10, python 3.5) on a toy classification problem, but I am getting confusing results.</p> <p>I want to feed in a sequence of zeros and ones into an RNN, and have the target class for a given element of the sequence to be the number represented by t...
0
2016-10-13T20:00:36Z
40,031,736
<p>Figured it out, with the help of <a href="http://killianlevacher.github.io/blog/posts/post-2016-03-01/post.html" rel="nofollow">this blog post</a> (it has wonderful diagrams of the input tensors). It turns out that I was not understanding the shape of the inputs to <code>tf.nn.rnn()</code> correctly:</p> <p>Let's s...
0
2016-10-13T22:00:25Z
[ "python", "tensorflow", "recurrent-neural-network" ]
redirect output of ipython script into a csv or text file like sqlplus spool
40,029,938
<p>I try to redirect the output of my script to a file. I don't want to do something like</p> <pre><code>python myscript.py &gt; xy.out </code></pre> <p>as a lot of the variable is being stored in my ipython environment and I like to carry it over.</p> <p>I try to follow this link </p> <p><a href="http://stackoverf...
0
2016-10-13T20:02:20Z
40,048,677
<p>Greeting. I end up using this solution:</p> <pre><code>%%capture var2 %run -I script2 import sys orig_stdout = sys.stdout f = file('out5.txt', 'w') sys.stdout = f print var2 stdout = orig_stdout f.close() </code></pre> <p>It is not very handy but it works!</p>
0
2016-10-14T17:17:20Z
[ "python", "ipython" ]
regular expression does not replace hyphens with dots
40,029,957
<p>For the following text:</p> <pre><code>comment = """ I took the pill - I realized only side-effect after I went off it how it affected my eating habits - I put on weight - around 10 lbs - in the 2.5 months on it - no control and syndrome - this was counterproductive !""" </code></pre> <p>I wrote regular expressio...
0
2016-10-13T20:03:41Z
40,029,987
<p>You could also use the <code>str.replace</code> method</p> <pre><code>comment.replace('-', '...') </code></pre>
4
2016-10-13T20:05:32Z
[ "python", "regex" ]
Compare two files for differences in python
40,029,985
<p>I want to compare two files (take line from first file and look up in whole second file) to see differences between them and write missing line from fileA.txt to end of fileB.txt. I am new to python so at first time I thought abou simple program like this:</p> <pre><code>import difflib file1 = "fileA.txt" file2 = ...
0
2016-10-13T20:05:24Z
40,030,529
<p>Try with this in the <code>bash</code>:</p> <pre><code>cat fileA.txt fileB.txt | sort -M | uniq &gt; new_file.txt </code></pre> <p><strong><a href="http://ss64.com/bash/sort.html" rel="nofollow">sort -M</a>:</strong> sorts based on initial string, consisting of any amount of whitespace, followed by a mon...
1
2016-10-13T20:37:35Z
[ "python", "linux", "diff" ]
Compare two files for differences in python
40,029,985
<p>I want to compare two files (take line from first file and look up in whole second file) to see differences between them and write missing line from fileA.txt to end of fileB.txt. I am new to python so at first time I thought abou simple program like this:</p> <pre><code>import difflib file1 = "fileA.txt" file2 = ...
0
2016-10-13T20:05:24Z
40,030,592
<p>read in two files and convert to set <br><br> find union of two sets<br> sort union set based on time <br> join set to string with new line <br></p> <pre><code>import datetime import file1 = "fileA.txt" file2 = "fileB.txt" with open(file1 ,'rb') as f: sa = set( line for line in f ) with open(file2 ,'rb') as f: ...
1
2016-10-13T20:41:57Z
[ "python", "linux", "diff" ]
"pythonic" way to fill bag of words
40,029,996
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code> There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p> <p>I want a count for each one</p> <pre><code>#make bag of worsds Word_arrayU = np.unique(Word_array) wordBag = [['0','0'] for _ in range(len(...
0
2016-10-13T20:05:57Z
40,030,147
<pre><code>from collections import Counter counter = Counter(Word_array) the_count_of_some_word = counter["some_word"] #printing the counts for word, count in counter.items(): print("{} appears {} times.".format(word, count) </code></pre>
1
2016-10-13T20:15:00Z
[ "python", "string", "counter" ]
"pythonic" way to fill bag of words
40,029,996
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code> There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p> <p>I want a count for each one</p> <pre><code>#make bag of worsds Word_arrayU = np.unique(Word_array) wordBag = [['0','0'] for _ in range(len(...
0
2016-10-13T20:05:57Z
40,030,177
<p>Building on the suggestion from @jonrsharpe...</p> <pre><code>from collections import Counter words = Counter() words['foo'] += 1 words['foo'] += 1 words['bar'] += 1 </code></pre> <p>Output</p> <pre><code>Counter({'bar': 1, 'foo': 2}) </code></pre> <p>It's really convenient because you don't have to initialize...
0
2016-10-13T20:16:23Z
[ "python", "string", "counter" ]
"pythonic" way to fill bag of words
40,029,996
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code> There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p> <p>I want a count for each one</p> <pre><code>#make bag of worsds Word_arrayU = np.unique(Word_array) wordBag = [['0','0'] for _ in range(len(...
0
2016-10-13T20:05:57Z
40,030,182
<p>I don't know about most 'Pythonic' but definitely the easiest way of doing this would be to use <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a>.</p> <pre><code>from collections import Counter Word_array = ["word1", "word2", "word3", "word1", "...
-1
2016-10-13T20:16:32Z
[ "python", "string", "counter" ]
"pythonic" way to fill bag of words
40,029,996
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code> There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p> <p>I want a count for each one</p> <pre><code>#make bag of worsds Word_arrayU = np.unique(Word_array) wordBag = [['0','0'] for _ in range(len(...
0
2016-10-13T20:05:57Z
40,030,202
<p>If you want a less efficient (than <code>Counter</code>), but more transparent solution, you can use <code>collections.defaultdict</code></p> <pre><code>from collections import defaultdict my_counter = defaultdict(int) for word in word_array: my_counter[word] += 1 </code></pre>
-1
2016-10-13T20:17:45Z
[ "python", "string", "counter" ]
"pythonic" way to fill bag of words
40,029,996
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code> There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p> <p>I want a count for each one</p> <pre><code>#make bag of worsds Word_arrayU = np.unique(Word_array) wordBag = [['0','0'] for _ in range(len(...
0
2016-10-13T20:05:57Z
40,030,349
<p>In python 3 there is a built-in list.count function. For example:</p> <pre><code>&gt;&gt;&gt; h = ["a", "b", "a", "a", "c"] &gt;&gt;&gt; h.count("a") 3 &gt;&gt;&gt; </code></pre> <p>So, you could make it more efficient by doing something like:</p> <pre><code>Word_arrayU = np.unique(Word_array) wordBag = [] for u...
0
2016-10-13T20:26:07Z
[ "python", "string", "counter" ]
"pythonic" way to fill bag of words
40,029,996
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code> There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p> <p>I want a count for each one</p> <pre><code>#make bag of worsds Word_arrayU = np.unique(Word_array) wordBag = [['0','0'] for _ in range(len(...
0
2016-10-13T20:05:57Z
40,030,369
<p>Since you are already using <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html" rel="nofollow"><em>numpy.unique</em></a>, just set <em>return_counts=True</em> in the unique call:</p> <pre><code>import numpy as np unique, count = np.unique(Word_array, return_counts=True) </code><...
1
2016-10-13T20:28:10Z
[ "python", "string", "counter" ]
Value won't increment inside while loop
40,030,338
<p>my problem is that the 'month' value increments once to month = 1, then stays there the whole time, causing an infinite loop. How do I get this to change every time through the loop? I know I'm probably missing something extremely simple. </p> <pre><code>def rem_bal(balance, annualInterestRate, monthlyInterestRate)...
0
2016-10-13T20:25:45Z
40,030,361
<pre><code>month += 1 </code></pre> <p>not </p> <pre><code>month = +1 </code></pre> <p>which is just </p> <pre><code>month = 1 </code></pre>
4
2016-10-13T20:27:27Z
[ "python", "python-3.x", "while-loop" ]
Value won't increment inside while loop
40,030,338
<p>my problem is that the 'month' value increments once to month = 1, then stays there the whole time, causing an infinite loop. How do I get this to change every time through the loop? I know I'm probably missing something extremely simple. </p> <pre><code>def rem_bal(balance, annualInterestRate, monthlyInterestRate)...
0
2016-10-13T20:25:45Z
40,030,373
<p>It needs to be <code>month += 1</code> not <code>month =+ 1</code>; the latter is just plain assignment rather than incrementing the value of <code>month</code> (i.e., assigning <code>month</code> to <code>+1</code>/<code>1</code>).</p>
0
2016-10-13T20:28:13Z
[ "python", "python-3.x", "while-loop" ]
Value won't increment inside while loop
40,030,338
<p>my problem is that the 'month' value increments once to month = 1, then stays there the whole time, causing an infinite loop. How do I get this to change every time through the loop? I know I'm probably missing something extremely simple. </p> <pre><code>def rem_bal(balance, annualInterestRate, monthlyInterestRate)...
0
2016-10-13T20:25:45Z
40,030,933
<p>BTW, this is not how you write a code in python. Why parentheses around almost everything? Why recalculate monthly_interest over and over, when it doesn't change? Using a while loop for this isn't pythonic. You should rather use </p> <pre><code>for month in range(13): </code></pre>
0
2016-10-13T21:02:30Z
[ "python", "python-3.x", "while-loop" ]
Value won't increment inside while loop
40,030,338
<p>my problem is that the 'month' value increments once to month = 1, then stays there the whole time, causing an infinite loop. How do I get this to change every time through the loop? I know I'm probably missing something extremely simple. </p> <pre><code>def rem_bal(balance, annualInterestRate, monthlyInterestRate)...
0
2016-10-13T20:25:45Z
40,032,005
<p>month = month+1 - tried this works</p>
0
2016-10-13T22:22:17Z
[ "python", "python-3.x", "while-loop" ]
Embedding a range in a pandas series
40,030,362
<p>I have a table of 14 columns and I want to pull select ones into a new dataframe. Let's say I want column 0 then column 8-14</p> <pre><code> dfnow = pd.Series([df.iloc[row_count,0], \ df.iloc[row_count,8], \ df.iloc[row_count,9], \ .... </code></pre> <p...
2
2016-10-13T20:27:31Z
40,030,475
<p>Is that what you want?</p> <pre><code>In [52]: df = pd.DataFrame(np.arange(30).reshape(5,6), columns=list('abcdef')) In [53]: df Out[53]: a b c d e f 0 0 1 2 3 4 5 1 6 7 8 9 10 11 2 12 13 14 15 16 17 3 18 19 20 21 22 23 4 24 25 26 27 28 29 In [54]: df[[0,2,4]]...
1
2016-10-13T20:34:10Z
[ "python", "pandas" ]
Embedding a range in a pandas series
40,030,362
<p>I have a table of 14 columns and I want to pull select ones into a new dataframe. Let's say I want column 0 then column 8-14</p> <pre><code> dfnow = pd.Series([df.iloc[row_count,0], \ df.iloc[row_count,8], \ df.iloc[row_count,9], \ .... </code></pre> <p...
2
2016-10-13T20:27:31Z
40,030,589
<p>I think you can convert all values to <code>lists</code> and then create <code>Series</code>, but then lost indices:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9], 'D':[1,3,5], 'E':[5,3,6], 'F':[...
0
2016-10-13T20:41:37Z
[ "python", "pandas" ]
Embedding a range in a pandas series
40,030,362
<p>I have a table of 14 columns and I want to pull select ones into a new dataframe. Let's say I want column 0 then column 8-14</p> <pre><code> dfnow = pd.Series([df.iloc[row_count,0], \ df.iloc[row_count,8], \ df.iloc[row_count,9], \ .... </code></pre> <p...
2
2016-10-13T20:27:31Z
40,031,043
<p>consider the <code>df</code></p> <pre><code>from string import ascii_uppercase import pandas as pd import numpy as np df = pd.DataFrame(np.arange(150).reshape(-1, 15), columns=list(ascii_uppercase[:15])) df </code></pre> <p><a href="https://i.stack.imgur.com/84S4N.png" rel="nofollow"><img src="h...
1
2016-10-13T21:09:08Z
[ "python", "pandas" ]
Speeding up Numpy Masking
40,030,448
<p>I'm still an amature when it comes to thinking about how to optimize. I have this section of code that takes in a list of found peaks and finds where these peaks,+/- some value, are located in a multidimensional array. It then adds +1 to their indices of a zeros array. The code works well, but it takes a long tim...
2
2016-10-13T20:32:40Z
40,031,225
<p><strong>Approach #1 :</strong> Memory permitting, here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code># Craate +,-2 limits usind ind r = x[ind[:,None]] + [-2,2] # Use limits to get inside matches a...
2
2016-10-13T21:22:32Z
[ "python", "arrays", "performance", "numpy", "masking" ]
numpy.savetxt- Save one column as int and the rest as floats?
40,030,481
<p><strong>The Problem</strong></p> <p>So I have a 2D array (151 rows, 52 columns) I'd like to save as a text file using np.savetxt. However, I want the first column's numbers to save as integers (1950, 1951, etc) while the rest of the data saves as precision 5 (4 if rounded) floating point numbers (2.7419, 2.736, etc...
1
2016-10-13T20:34:33Z
40,030,726
<p><code>data</code> has 3 columns, so you need supply 3 <code>'%format'</code>s. For example:</p> <pre><code>np.savetxt('array.txt', data, fmt='%i %1.4f %1.4f') </code></pre> <p>should work. If you have a lot more than 3 columns, you can try something like:</p> <pre><code>np.savetxt('array.txt', data, fmt=' '.joi...
2
2016-10-13T20:50:02Z
[ "python", "arrays", "numpy", "text-files", "number-formatting" ]
numpy.savetxt- Save one column as int and the rest as floats?
40,030,481
<p><strong>The Problem</strong></p> <p>So I have a 2D array (151 rows, 52 columns) I'd like to save as a text file using np.savetxt. However, I want the first column's numbers to save as integers (1950, 1951, etc) while the rest of the data saves as precision 5 (4 if rounded) floating point numbers (2.7419, 2.736, etc...
1
2016-10-13T20:34:33Z
40,030,731
<p>your <code>fmt</code> parameter needs to have the the same number of <code>%</code> as the columns you are trying ot format. You are trying to format 3 columns but only giving it 2 formats. </p> <p>Try changing your <code>np.savetxt(...)</code> to</p> <pre><code>np.savetxt('array.txt',data,fmt="%i %1.4f %1.4f") <...
0
2016-10-13T20:50:14Z
[ "python", "arrays", "numpy", "text-files", "number-formatting" ]
Pycharm - Python Console
40,030,494
<p>I am testing my python code in the console window.</p> <p>It is not allowing me to enter any code and instead it passes this error message:</p> <pre><code>/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py 55724 55725 PyDev console: star...
0
2016-10-13T20:35:33Z
40,030,711
<p>This is how your <code>pydev_import_hook.py</code> should look like:</p> <pre><code>import sys from _pydevd_bundle.pydevd_constants import dict_contains from types import ModuleType class ImportHookManager(ModuleType): def __init__(self, name, system_import): ModuleType.__init__(self, name) se...
0
2016-10-13T20:49:13Z
[ "python", "console", "pycharm" ]
Need main to call functions in order, properly
40,030,623
<pre><code>def load(): global name global count global shares global pp global sp global commission name=input("Enter stock name OR -999 to Quit: ") count =0 while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("...
-2
2016-10-13T20:43:49Z
40,032,181
<p>The first problem is that you are clobbering the variable <code>name</code> every time you execute the input statement. You need to assign the result of input to temporary variable and check that for equality to -999, like this:</p> <pre><code>def load(): global name global count global shares ...
0
2016-10-13T22:38:54Z
[ "python", "function", "python-3.x" ]
Need main to call functions in order, properly
40,030,623
<pre><code>def load(): global name global count global shares global pp global sp global commission name=input("Enter stock name OR -999 to Quit: ") count =0 while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("...
-2
2016-10-13T20:43:49Z
40,032,191
<p>Based on your comment</p> <pre><code>take the calc() and display() inside the loop and move them directly into def main(): </code></pre> <p>this is consistent with your expected output:</p> <pre><code>def main(): name=input("Enter stock name OR -999 to Quit: ") count, totalpr = 0, 0 while name != '-99...
0
2016-10-13T22:39:38Z
[ "python", "function", "python-3.x" ]