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
Extracting a set from a list of composite elements in python
39,546,200
<p>I'm maintaining <code>message_id</code> and <code>message_writer_id</code> together in a python list like so:</p> <pre><code>composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] </code></pre> <p>Where each element is <code>message_id:message_poster_id</code>. </p> <p>From the above list, I ...
0
2016-09-17T11:18:10Z
39,546,755
<pre><code>composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] posters = dict() for element in composite_items: poster_id = element.split(":")[1] posters[poster_id] = posters.get(poster_id, 0) + 1 </code></pre> <p>You can use dictionaries and also count how many messages sent by <code>m...
0
2016-09-17T12:21:16Z
[ "python" ]
Extracting a set from a list of composite elements in python
39,546,200
<p>I'm maintaining <code>message_id</code> and <code>message_writer_id</code> together in a python list like so:</p> <pre><code>composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] </code></pre> <p>Where each element is <code>message_id:message_poster_id</code>. </p> <p>From the above list, I ...
0
2016-09-17T11:18:10Z
39,546,888
<p>You may use set comprehension like so:</p> <pre><code>new_set = {item.partition(":")[2] for item in composite_items} </code></pre> <p>Set comprehension is fast, and unlike <code>str.split()</code>, <code>str.partition()</code> splits only once and stops looking for more colons. Quite the same as with <code>str.spl...
2
2016-09-17T12:36:07Z
[ "python" ]
Python start all Threads from doulbe FOR LOOP
39,546,286
<p>I have this kind of scenario:</p> <pre><code>threads = [] for wordToScan in wordsList: dictionaryFileOpen = open(dictionaryFile, "r") for i in range(10): threads.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan))) for thread in threads: thread.start() for thread in t...
0
2016-09-17T11:26:20Z
39,546,587
<p>Here is how I have it done:</p> <pre><code>threads = [] for wordToScan in wordsList: wordThread = [] dictionaryFileOpen = open(dictionaryFile, "r") for i in range(10): wordThread.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan))) threads.append(wordThread) for t...
0
2016-09-17T12:02:59Z
[ "python", "multithreading", "readline" ]
Python start all Threads from doulbe FOR LOOP
39,546,286
<p>I have this kind of scenario:</p> <pre><code>threads = [] for wordToScan in wordsList: dictionaryFileOpen = open(dictionaryFile, "r") for i in range(10): threads.append(Thread(target=words_Scan_Start, args=(dictionaryFileOpen, wordToScan))) for thread in threads: thread.start() for thread in t...
0
2016-09-17T11:26:20Z
39,546,667
<p>You should not read file from several threads. This involves following considerations:</p> <ol> <li>Objects which are accessed from several threads must be thread safe. File is not thread safe. So you must guard all places where you use it with mutex.</li> <li>Reading from the disk is quite a slow process. A single...
0
2016-09-17T12:13:34Z
[ "python", "multithreading", "readline" ]
Unable to send mail using python with multiple attachment and multiple recipients [to,cc,bcc]
39,546,398
<p>Below is my code. It is unable to send mail somewhere at parsing level. Not able to understand the actual issue. OS is Ubuntu 14.04 Server provided by AWS. It has to send email with two attachments.</p> <pre><code>import smtplib import sys from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIM...
1
2016-09-17T11:39:05Z
39,546,521
<p>Try it with <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a>. Disclaimer: I'm the developer of yagmail.</p> <pre><code>import yagmail yag = yagmail.SMTP("[email protected]", "password") yag.send(toaddrs, subject, body, str(sys.argv[5]).split(";"), ccaddrs, bccaddrs) # ^ to ^subject ...
1
2016-09-17T11:54:34Z
[ "python", "python-2.7", "gmail", "sendmail" ]
Unable to send mail using python with multiple attachment and multiple recipients [to,cc,bcc]
39,546,398
<p>Below is my code. It is unable to send mail somewhere at parsing level. Not able to understand the actual issue. OS is Ubuntu 14.04 Server provided by AWS. It has to send email with two attachments.</p> <pre><code>import smtplib import sys from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIM...
1
2016-09-17T11:39:05Z
39,552,374
<p>I had the same problem when I tried to feed a list in to msg['To']. I changed the list to string and I got rid of the problem. ['[email protected]', '[email protected]'] => '[email protected], [email protected]' </p>
0
2016-09-17T22:39:13Z
[ "python", "python-2.7", "gmail", "sendmail" ]
Python: Save element by element from input
39,546,524
<p>I have an input file as follow</p> <pre><code>0.1 #real number 0.2 #real number Hello #string 10000 #integer number </code></pre> <p>I want to read it and use each line, before the '#' symbol, in my code. For the second part I did</p> <pre><code>with open('input.dat') as f: for line in f: line = line....
0
2016-09-17T11:55:00Z
39,546,620
<p>One way to do it is to store the results in an array. What to do next will depend on how your input is structured: will it always contain just four values of those types and in that order?</p> <pre><code>values = [] with open('input.dat') as f: for line in f: value = line.split('#', 1)[0] if va...
1
2016-09-17T12:06:53Z
[ "python", "string", "file", "input" ]
Python: Save element by element from input
39,546,524
<p>I have an input file as follow</p> <pre><code>0.1 #real number 0.2 #real number Hello #string 10000 #integer number </code></pre> <p>I want to read it and use each line, before the '#' symbol, in my code. For the second part I did</p> <pre><code>with open('input.dat') as f: for line in f: line = line....
0
2016-09-17T11:55:00Z
39,546,631
<p>You already have all the pieces, you just need to put them in the right places:</p> <pre><code>def remove_comment(line): line = line.split('#', 1)[0] line = line.rstrip() return line with open('input.dat') as f: lines = [remove_comment(line) for line in f] # no need for this: "with" takes care of ...
1
2016-09-17T12:08:39Z
[ "python", "string", "file", "input" ]
Same Origin Policy violated on localhost with falcon webserver
39,546,536
<p>I am running an elm frontend via elm-reactor on <code>localhost:8000</code>. It is supposed to load json files from a <strong>falcon backend</strong> running via gunicorn on <code>localhost:8010</code>. This fails.</p> <p>The frontend is able to load static dummy files served by elm-reactor (<code>:8000</code>) but...
0
2016-09-17T11:56:58Z
39,546,695
<p>It turns out that falcon_cors offers <code>allow_all_origins=True</code> as a parameter. This fixes my problem, but isn't a perfect solution.</p> <p>When using POST requests as well <code>allow_all_methods=True</code> should be set as well.</p>
0
2016-09-17T12:15:56Z
[ "python", "web-services", "cross-domain", "elm", "falconframework" ]
IndexError: invalid index to scalar variable for double and if 'for' statement
39,546,560
<p>My main aim is to print out the values of one variable which is in a double <code>for loop</code> and under an <code>if-statement</code>but however I tend to get an error <code>IndexError: invalid index to scalar variable.</code> Here is my codes</p> <pre><code>import numpy as np nR = 133 nP = 255 Pmin = 0.09 P...
0
2016-09-17T11:59:42Z
39,547,432
<p>In your next-to-last line, you have the sub-expression</p> <pre><code>LnPa - LnPa[ka] </code></pre> <p>That first reference to <code>LnPa</code> is fine, since that is a float variable, but the second is not. You are trying to treat that float variable as a list or some-such with <code>LnPa[ka]</code>, by indexing...
0
2016-09-17T13:34:50Z
[ "python", "numpy", "if-statement", "for-loop" ]
Copy a flat numpy array to an given attribute of an np.array of objects
39,546,562
<p>Can I copy a 1D numpy array to an given attribute of an np.array of objects without using a for loop? For filling the "percentage" property of all PlotInputGridData objects in objarray with the "dist" array, i use something like this:</p> <pre><code>import numpy as np class PlotInputGridData(object): def __ini...
0
2016-09-17T11:59:57Z
39,547,521
<p>I don't think there is a way to do that assignment without a for-loop.</p> <p>You could do it if you used a <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured array</a> instead of an array of objects. The class <code>PlotInputGridData</code> is just a few fields, so the data i...
3
2016-09-17T13:44:24Z
[ "python", "arrays", "numpy" ]
run pygame with phycharm
39,546,646
<p>I try to run pygame in Pycharm. The editor show the library. But if I run the program I get an error that it can't find the module: pygame.</p> <p>I am running python 3.5</p> <p>I added a picutre: <a href="http://i.stack.imgur.com/brTCS.png" rel="nofollow"><img src="http://i.stack.imgur.com/brTCS.png" alt="enter i...
0
2016-09-17T12:10:44Z
39,546,688
<p>then install <code>pygame</code>:</p> <pre><code>pip install pygame </code></pre> <p>or:</p> <pre><code>python -m pip install pygame </code></pre> <p>or from code:</p> <pre><code>import pip pip.main(['install', 'pygame']) </code></pre>
1
2016-09-17T12:15:24Z
[ "python", "python-3.x" ]
run pygame with phycharm
39,546,646
<p>I try to run pygame in Pycharm. The editor show the library. But if I run the program I get an error that it can't find the module: pygame.</p> <p>I am running python 3.5</p> <p>I added a picutre: <a href="http://i.stack.imgur.com/brTCS.png" rel="nofollow"><img src="http://i.stack.imgur.com/brTCS.png" alt="enter i...
0
2016-09-17T12:10:44Z
39,546,877
<ol> <li><p>You do not have the PyGame module and even PyCharm suggests it for you.</p></li> <li><p>You do not run pip inside the python IDE. In order to do install a module with pip you have to open the command line and directly run</p> <p><code>Pip install PyGame</code></p></li> </ol> <p>Or</p> <pre><code>Python -...
0
2016-09-17T12:35:14Z
[ "python", "python-3.x" ]
Django models, adding new value, migrations
39,546,734
<p>I worked with django 1.9 and added a new field (creation_date) to myapp/models.py. After that I run "python manage.py makemigrations". I got: </p> <blockquote> <p>Please select a fix:</p> <ol> <li>Provide a one-off default now (will be set on all existing rows)</li> <li>Quit, and let me add a default in ...
1
2016-09-17T12:18:54Z
39,547,167
<p>As long as your migration isn't applied to the database you can manually update your migration file located in <code>myapp/migrations/*.py</code>. Find the string '10.07.2016' and update it to a supported format.</p> <p>A less attractive solution would be to delete the old migration file (as long as it isn't apllie...
1
2016-09-17T13:05:51Z
[ "python", "django", "django-models", "django-migrations" ]
pandas: error on DataFrame.unstack
39,546,975
<p>I wrote the following function to convert several columns of a dataframe into numeric values:</p> <pre><code>def factorizeMany(data, columns): """ Factorize a bunch of columns in a data frame""" data[columns] = data[columns].stack().rank(method='dense').unstack() return data </code></pre> <p>Calling it...
2
2016-09-17T12:45:15Z
39,548,611
<p>The error is due to the fact that you are trying to perform the <code>rank</code> operation on the subset of the dataframe containing both numerical and categorical/string values by filling the <code>NaN's</code> in the dataframe with 0 and calling that function.</p> <p>Consider this case:</p> <pre><code>df = pd.D...
1
2016-09-17T15:35:36Z
[ "python", "pandas", "dataframe" ]
Python parse string containing functions, lists and dicts
39,547,056
<p>I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.</p> <p>Example string: <code>"variable, function1(1,3), function2([1,3],2), ['list_item_1',...
3
2016-09-17T12:54:49Z
39,547,094
<p>Have you tried using split?</p> <pre><code>&gt;&gt;&gt; teststring = "variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}" &gt;&gt;&gt; teststring.split(", ") ['variable', 'function1(1,3)', 'function2([1,3],2)', "['list_item_1','list_item_2'],{'dict_key_1': 'dic...
0
2016-09-17T12:57:46Z
[ "python", "regex", "string-parsing" ]
Python parse string containing functions, lists and dicts
39,547,056
<p>I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.</p> <p>Example string: <code>"variable, function1(1,3), function2([1,3],2), ['list_item_1',...
3
2016-09-17T12:54:49Z
39,547,196
<p>Regular expressions aren't very good for parsing the complexity of arbitrary code. What exactly are you trying to accomplish? You can (unsafely) use <code>eval</code> to just evaluate the string as code. Or if you're trying to understand it without <code>eval</code>ing it, you can use <a href="https://docs.python.or...
0
2016-09-17T13:08:50Z
[ "python", "regex", "string-parsing" ]
Python parse string containing functions, lists and dicts
39,547,056
<p>I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.</p> <p>Example string: <code>"variable, function1(1,3), function2([1,3],2), ['list_item_1',...
3
2016-09-17T12:54:49Z
39,547,420
<p>I guess the main problem here is that the arrays and dicts also have commas in them, so just using <code>str.split(",")</code> wouldn't work. One way of doing it is to parse the string one character at a time, and keep track of whether all brackets are closed. If they are, we can append the current result to an arra...
2
2016-09-17T13:33:26Z
[ "python", "regex", "string-parsing" ]
Can variables in a function for later use?
39,547,150
<p>Can Python store variables in a function for later use?</p> <p>This is a stat calculator below (unfinished):</p> <pre><code>#Statistics Calculator import random def main(mod): print '' if (mod == '1'): print 'Mode 1 activated' dat_entry = dat() elif (mod == '2'): print 'Mode 2 a...
0
2016-09-17T13:03:56Z
39,547,253
<p>There's a problem with the logic. If you go straight to mode 2 this is what will cause this error because "dat_entry" would be undefined.</p> <p>You've selected mode 2, at this point it doesn't know what dat_entry is:</p> <pre><code>elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat_entry) </cod...
0
2016-09-17T13:15:41Z
[ "python" ]
Can variables in a function for later use?
39,547,150
<p>Can Python store variables in a function for later use?</p> <p>This is a stat calculator below (unfinished):</p> <pre><code>#Statistics Calculator import random def main(mod): print '' if (mod == '1'): print 'Mode 1 activated' dat_entry = dat() elif (mod == '2'): print 'Mode 2 a...
0
2016-09-17T13:03:56Z
39,547,645
<p>This part of the code is problematic. <code> elif (mod == '2'): print 'Mode 2 activated' array = rndom(dat_entry) </code> </p> <p>Python does not know what 'dat_entry' is in rndom(dat_entry) because it has not yet been assigned previously in the function, that's why it's throwing an error...
0
2016-09-17T13:58:04Z
[ "python" ]
Can variables in a function for later use?
39,547,150
<p>Can Python store variables in a function for later use?</p> <p>This is a stat calculator below (unfinished):</p> <pre><code>#Statistics Calculator import random def main(mod): print '' if (mod == '1'): print 'Mode 1 activated' dat_entry = dat() elif (mod == '2'): print 'Mode 2 a...
0
2016-09-17T13:03:56Z
39,547,725
<p>If the first <code>if</code> condition is not satisfied, it wont execute the block of codes associated with it. Since the first <code>if</code> condition is not satisfied, the assignment <code>dat_entry = dat()</code> will not execute.</p> <p>So, in your case you can do the do it as follows:</p> <pre><code>elif (m...
0
2016-09-17T14:06:01Z
[ "python" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code><...
0
2016-09-17T13:09:17Z
39,547,331
<p>There are these two options:</p> <blockquote> <p>Using a dictionary:</p> </blockquote> <p>Another way would be to use a <code>dictionary</code> instead. So you could create your dictionary once the list is filled up with elements. The dictionary's keys would be the values of your list and as values you could use...
0
2016-09-17T13:24:28Z
[ "python", "attributes" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code><...
0
2016-09-17T13:09:17Z
39,547,333
<p>Use a boolean operator <a href="https://docs.python.org/3.5/reference/expressions.html#and" rel="nofollow"><code>and</code></a>.</p> <pre><code>if ins_list[ind] and ins_list[ind].some_attribute == "thing": # Code </code></pre>
0
2016-09-17T13:24:35Z
[ "python", "attributes" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code><...
0
2016-09-17T13:09:17Z
39,547,395
<p>As coder proposed, you can remove None from your list, or use dictionaries instead, to avoid to have to create an entry for each index.</p> <p>I want to propose another way: you can create a dummyclass and replace None by it. This way there will be no error if you set an attribute:</p> <pre><code>class dummy: ...
0
2016-09-17T13:30:51Z
[ "python", "attributes" ]
Avoid extra line for attribute check?
39,547,201
<p>I am developing this Python project where I encounter a situation many times and I wondered if there is a better way.</p> <p>There is a list of class instances. Some part of lists are empty(filled with <code>None</code>). Here is an example list.</p> <pre><code>ins_list = [ins_1, ins_2, None, ins_3, None] </code><...
0
2016-09-17T13:09:17Z
39,548,821
<p>In this case I would use an try-except statement because of <a href="https://docs.python.org/2/glossary.html" rel="nofollow">EAFP</a> <em>(easier to ask for forgivness than permission)</em>. It won't shorten yout code but it's a more Pythonic way to code when checking for valid attributes. This way you won't break a...
0
2016-09-17T15:57:05Z
[ "python", "attributes" ]
Django REST Framework Swagger - Authentication Error
39,547,208
<p>I followed the instructions <a href="http://django-rest-swagger.readthedocs.io/en/latest/" rel="nofollow">in the docs</a>. So here's my view:</p> <pre><code>from rest_framework.decorators import api_view, renderer_classes from rest_framework import response, schemas from rest_framework_swagger.renderers import Open...
1
2016-09-17T13:10:39Z
39,547,632
<blockquote> <p>Isn't there a way to login as an admin, or any other user to view the docs.</p> </blockquote> <p>If your only use token authentication, first <a href="http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication" rel="nofollow">create tokens for your users</a>, then access the r...
1
2016-09-17T13:57:03Z
[ "python", "django", "django-rest-framework", "swagger", "swagger-ui" ]
Django REST Framework Swagger - Authentication Error
39,547,208
<p>I followed the instructions <a href="http://django-rest-swagger.readthedocs.io/en/latest/" rel="nofollow">in the docs</a>. So here's my view:</p> <pre><code>from rest_framework.decorators import api_view, renderer_classes from rest_framework import response, schemas from rest_framework_swagger.renderers import Open...
1
2016-09-17T13:10:39Z
39,554,754
<p>I think I've found the solution.</p> <p>In the <code>settings.py</code>, I added the following settings:</p> <pre><code>SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, } </code></p...
1
2016-09-18T06:20:02Z
[ "python", "django", "django-rest-framework", "swagger", "swagger-ui" ]
How can I continuously replace an element of an array?
39,547,219
<p>At each time step, I am trying to replace one element of my <code>list</code> with the sum of the other 2 plus 1. This is my code:</p> <pre><code>def replace(x, y, z): for i in range(3): rep_x = [y+z+1, y, z] rep_y = [x, x+z+1, z] rep_z = [x, y, x+y+1] ini_x = rep_x in...
1
2016-09-17T13:11:54Z
39,547,468
<blockquote> <p>at each time step, replace one element of my array with the sum of the other 2 plus 1</p> </blockquote> <pre><code>from __future__ import print_function def business(array): # Can't give a proper name without knowing what the function does total = sum(array) return [total + 1 - x for x in arr...
0
2016-09-17T13:38:15Z
[ "python", "arrays", "python-2.7" ]
How can I continuously replace an element of an array?
39,547,219
<p>At each time step, I am trying to replace one element of my <code>list</code> with the sum of the other 2 plus 1. This is my code:</p> <pre><code>def replace(x, y, z): for i in range(3): rep_x = [y+z+1, y, z] rep_y = [x, x+z+1, z] rep_z = [x, y, x+y+1] ini_x = rep_x in...
1
2016-09-17T13:11:54Z
39,547,884
<p>Is this helpful:</p> <pre><code>def replace(x, y, z): ini_x = [y+z+1, y, z] ini_y = [x, x+z+1, z] ini_z = [x, y, x+y+1] return ini_x, ini_y, ini_z s = replace(2, 4, 6) print s for i in s: print replace(i[0], i[1], i[2]) </code></pre> <p>output:</p> <pre><code>([11, 4, 6], [2, 9, 6], [2, 4, 7]) ([11,...
0
2016-09-17T14:24:10Z
[ "python", "arrays", "python-2.7" ]
python django run bash script in server
39,547,220
<p>I would like to create a website-app to run a bash script located in a server. Basically I want this website for:</p> <ul> <li>Upload a file</li> <li>select some parameters</li> <li>Run a bash script taking the input file and the parameters</li> <li>Download the results</li> </ul> <p>I know you can do this with ph...
0
2016-09-17T13:11:54Z
39,548,033
<p>This can be done in Python using the Django framework. </p> <p>First create a form including a <code>FileField</code> and the fields for the other parameters:</p> <pre><code>from django import forms class UploadFileForm(forms.Form): my_parameter = forms.CharField(max_length=50) file = forms.FileField() </...
0
2016-09-17T14:39:48Z
[ "python", "django" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary !=...
3
2016-09-17T13:17:15Z
39,547,326
<p>Use <code>any</code>:</p> <pre><code>v1, v2, v3, v4 = 0, 1, 1, 2 if any(x not in [0, 1] for x in [v1, v2, v3, v4]): print "bad" </code></pre> <p>of course, if you use a list it will look even better</p> <pre><code>inputs = [1, 1, 0 , 2] if any(x not in [0, 1] for x in inputs): print "bad" </code></pre>
6
2016-09-17T13:23:20Z
[ "python" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary !=...
3
2016-09-17T13:17:15Z
39,547,363
<p>I'd break it down into the two parts that you're trying to solve: </p> <p>Is a particular piece of input valid? Are all the pieces of input taken together valid? </p> <pre><code>&gt;&gt;&gt; okay = [0,1,1,0] &gt;&gt;&gt; bad = [0,1,2,3] &gt;&gt;&gt; def validateBit(b): ... return b in (0, 1) &gt;&gt;&gt; def...
1
2016-09-17T13:27:45Z
[ "python" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary !=...
3
2016-09-17T13:17:15Z
39,547,380
<p>This is due to the operator precedence in python. The <code>or</code> operator is of higher precedence than the <code>and</code> operator, the list looks like this:</p> <ol> <li><code>or</code></li> <li><code>and</code></li> <li><code>not</code></li> <li><code>!=</code>, <code>==</code></li> </ol> <p>(Source: <a h...
3
2016-09-17T13:29:35Z
[ "python" ]
Validating the value of several variables
39,547,275
<p><strong>What I am after:</strong> The user is allowed to input only 0 or 1 (for a total of 4 variables). If the user inputs for example 2, 1, 1, 0 it should throw an error saying <code>Only 0 and 1 allowed</code>.</p> <p><strong>What I've tried so far:</strong></p> <pre><code>if (firstBinary != 0 or firstBinary !=...
3
2016-09-17T13:17:15Z
39,547,526
<pre><code>values = [firstBinary, secondBinary, thirdBinary] if set(values) - set([0, 1]): print "Only 0 or 1, please" </code></pre>
0
2016-09-17T13:45:01Z
[ "python" ]
Sending an image through UDP communication
39,547,386
<p>I am trying to make a video-streaming application, in which i'll be able to both stream my webcam and my desktop. Up until now I've done so with TCP communication in order to make sure everything works, and it does, but very slowly. I know that usually in live streams like these you would use UDP, but I can't get it...
0
2016-09-17T13:29:52Z
39,556,790
<p>My psychic powers tell me that are hitting the size limit for a UDP packet, which is just under 64KB. You will likely need to split your image bytes up into multiple packets when sending and have some logic to put them back together on the receiving end. You will likely need to roll out your own header format.</p...
0
2016-09-18T10:46:14Z
[ "python", "image", "sockets", "stream", "udp" ]
Convert numpy array of integers to 12 bit binary
39,547,397
<p>I neeed to convert a np array of integers to 12 bit binary numbers, in an array format. What would be the best way to go about doing so? </p> <p>I've been a bit stuck so any help would be appreciated. Thanks!</p> <p>Here is what I have to convert an integer to binary:</p> <pre><code>def dec_to_binary(my_int): """...
1
2016-09-17T13:31:08Z
39,547,500
<p>Slight correction (replace <code>12b</code> with <code>012b</code>):</p> <pre><code>def dec_to_binary(my_int): """ Format a number as binary with leading zeros """ if my_int &lt; 4096: return "{0:012b}".format(my_int) else: return "111111111111" </code></pre> <p>Example: </p>...
1
2016-09-17T13:42:36Z
[ "python", "arrays", "python-3.x", "numpy" ]
Determine program was installed using "setup.py develop"
39,547,411
<p>I am developing a Gtk application and would like to use a system-wide, installed version and run a different development version at the same time.</p> <p>The application cannot be started twice because <code>Gtk.Application</code> will try to connect to same DBus bus and refuse to be started twice. Therefore my ide...
0
2016-09-17T13:32:22Z
39,547,684
<p>Due to how <code>setuptools</code> is designed the development mode is simply a transparent <code>.egg-link</code> object away, so internally it is effectively impossible to determine whether or not the package is loaded as an <code>egg-link</code> (i.e. development mode; relevant <a href="https://github.com/pypa/se...
1
2016-09-17T14:01:33Z
[ "python", "setuptools", "gtk3" ]
Reportlab Error after page break
39,547,528
<p>I am designing a two page form to be printed duplex. After I add a pagebreak, I get the following error:</p> <pre><code> File "f:\Dropbox\pms\pms_reports.py", line 450, in &lt;module&gt; a = Key_card1() File "f:\Dropbox\pms\pms_reports.py", line 441, in __init__ doc.build(elements) File "c:\Python34\Lib\sit...
1
2016-09-17T13:45:21Z
39,547,653
<p>I have tried to understand the error and i guess there is problem in <code>doc = SimpleDocTemplate("key_card.pdf", pagesize=A4)</code>.The problem may be the argument "key_card.pdf". I'm not sure</p> <p>Edit: Maybe, <code>BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)</code> problem is about "flowab...
1
2016-09-17T13:59:02Z
[ "python", "reportlab" ]
How do i draw a line and change colors in pygame?
39,547,587
<p>I am trying to make a draw program in pygame for a school project. In this module, i am intending for the user to press down on the mouse and draw a line on the surface. If a person presses down on a rect, the color that the person selected is the color that the drawn line will be. For some reason, the variable can ...
2
2016-09-17T13:51:38Z
39,547,896
<p>What I would do is</p> <pre><code>painting_module() def painting_module(): running = True while running: #clock for timingn processes Clock.tick(FPS) # Process input (event) for event in pygame.event.get(): Mouse_location = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() displacement_...
0
2016-09-17T14:26:10Z
[ "python", "python-2.7", "pygame", "pygame-surface" ]
Filerenaming loop not functioning
39,547,750
<p>I'm having trouble understanding why my code doesn't work. I want to rename each file in a particular folder in an order like this: Foldername_1 Foldername_2 Foldername_3 etc...</p> <p>The code I wrote should increase the 'num' variable by 1 every time it reloops the for loop.</p> <pre><code>path = os.getcwd() f...
0
2016-09-17T14:09:58Z
39,547,761
<p>You are setting <code>num</code> to 0 <em>for each iteration</em>. Move the <code>num = 0</code> <em>out</em> of the loop:</p> <pre><code>num = 0 for filename in filenames: num = num + 1 name = "Foldername_{}".format(num) os.rename(filename, "{}".format(name)) </code></pre> <p>You don't need to format ...
1
2016-09-17T14:11:10Z
[ "python", "python-3.x", "file-rename" ]
How do I get an entry widget to save what I input? Python Tkinter
39,547,768
<p>I want to make an entry widget that inputs personal details, however I want to save those details as variables, so I can write them in a txt file. </p> <pre><code>from tkinter import * root = Tk() Label(root, text = "Childs First name").grid(row = 0, sticky = W) Label(root, text = "Childs Surname").grid(row = 1, st...
0
2016-09-17T14:12:12Z
39,548,068
<p>Entry widgets have a <code>get</code> method which can be used to get the values when you need them. Your "save" function simply needs to call this function before writing to a file.</p> <p>For example:</p> <pre><code>def save(): x_value = x.get() y_value = y.get() z_value = z.get() ... </code></pr...
0
2016-09-17T14:43:38Z
[ "python", "button", "tkinter", "widget", "entry" ]
How to read the string and long features in tensorflow
39,547,815
<p>The tensorflow, I can't read string,long, only short float allowed? Why? </p> <pre><code>import tensorflow as tf import numpy as np # Data sets IRIS_TRAINING = "seRelFeatures.csv" IRIS_TEST = "seRelFeatures.csv" # Load datasets. training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, targe...
2
2016-09-17T14:16:50Z
39,549,160
<p>Your error is <code>ValueError: invalid literal for long() with base 10: ''</code>. It simply that you are entering empty string instead of an integer (or string presentation of an integer). I'd check data in CSV files. </p>
0
2016-09-17T16:33:17Z
[ "python", "csv", "tensorflow" ]
How to read the string and long features in tensorflow
39,547,815
<p>The tensorflow, I can't read string,long, only short float allowed? Why? </p> <pre><code>import tensorflow as tf import numpy as np # Data sets IRIS_TRAINING = "seRelFeatures.csv" IRIS_TEST = "seRelFeatures.csv" # Load datasets. training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, targe...
2
2016-09-17T14:16:50Z
39,873,129
<p>Actually I solved this problem by myself, this mistake mean</p> <pre><code>ValueError: invalid literal for long() with base 10: '' </code></pre> <p>I have some empty cell, but actually I don't have on the view. After I check it, it cased by I delete the last column but I just delete the content didn't delete the c...
0
2016-10-05T11:47:09Z
[ "python", "csv", "tensorflow" ]
Counting the number of vowels
39,547,818
<p>Trying to print no. of vowels. When I run this code I get <code>1,2,3,4</code> I intend to print only 4. Where is my mistake and how would I correct it?</p> <pre><code>vowels='a','e','i','o','u' s= 'hellohello' count = 0 for letters in s: if letters in vowels: count+=1 print (count) </code></pre...
0
2016-09-17T14:17:07Z
39,547,849
<p>You're mostly right, but you're printing in the loop rather than at the end.</p> <pre><code>for letters in s: if letters in vowels: count+=1 # de indent to close the loop print (count) </code></pre>
0
2016-09-17T14:20:17Z
[ "python", "python-3.x" ]
Counting the number of vowels
39,547,818
<p>Trying to print no. of vowels. When I run this code I get <code>1,2,3,4</code> I intend to print only 4. Where is my mistake and how would I correct it?</p> <pre><code>vowels='a','e','i','o','u' s= 'hellohello' count = 0 for letters in s: if letters in vowels: count+=1 print (count) </code></pre...
0
2016-09-17T14:17:07Z
39,547,875
<p><code>count</code> should be out of <code>for</code> loop.So that it prints only once.</p> <pre><code>vowels='a','e','i','o','u' s= 'hellohello' count = 0 for letters in s: if letters in vowels: count+=1 print (count) </code></pre>
0
2016-09-17T14:22:29Z
[ "python", "python-3.x" ]
Doing something after popen is finished
39,547,820
<p>I want to make a background process that displays a <code>file</code> with an external <code>viewer</code>. When the process is stopped, it should delete the file. The following piece of code does what I want to do, but it is ugly and I guess there is a more idiomatic way. It would be perfect, if it is even OS indep...
1
2016-09-17T14:17:20Z
39,547,855
<p>Using <code>subprocess.call()</code> to open the viewer and view the file will exactly do that. Subsequently, run the command to delete the file.</p> <p>If you want the script to continue while the process is running, use <code>threading</code></p> <p>An example:</p> <pre><code>from threading import Thread import...
1
2016-09-17T14:20:44Z
[ "python", "python-3.x", "subprocess", "popen" ]
Pandas group by chunks not single values
39,547,873
<p>Now I'm kinda confused about grouping stuff using pandas.</p> <p>I have set of data (over 60k rows) with 3 columns:</p> <pre><code>2015/12/18 11:12:49 +0300 d1 b1 2015/12/18 11:12:50 +0300 d2 b2 2015/12/18 11:13:08 +0300 d1 b3 2015/12/18 11:13:36 +0300 d2 b4 2015/12/18 11:13:43 +0300 d2 b5 2015/12/1...
1
2016-09-17T14:22:29Z
39,548,003
<p>The first part of you question, how to group by 4 hour chunks is easy and is addressed in both options below. <code>df.index.hour // 4</code></p> <p>The second part was vague as there are several ways to interpret "merge into a single column". I provided you two alternatives.</p> <p><strong><em>Option 1</em></st...
1
2016-09-17T14:37:01Z
[ "python", "pandas", "dataframe", "grouping" ]
Setting a plain checkbox with robobrowser
39,547,879
<p>I am struggling to check a simple checkbox with <code>robobrowser</code> to discard all messages in mailman.</p> <pre><code>form['discardalldefersp'].options </code></pre> <p>returns <code>['0']</code>, neither </p> <pre><code>form['discardalldefersp'].value= True </code></pre> <p>nor </p> <pre><code>form['disc...
1
2016-09-17T14:22:59Z
39,897,976
<p>I had a similar error message with a radio button. Try to add the option of '1' or True to the Robobrowser field <strong>discardalldefersp</strong> and see if it solves the problem:</p> <pre><code>form['discardalldefersp'].options = ['1'] form['discardalldefersp'].value = '1' </code></pre> <p>Or with the True opti...
1
2016-10-06T13:57:41Z
[ "python", "beautifulsoup", "robobrowser" ]
Python - print name shows None
39,547,942
<pre><code>import re import time import sys def main(): name = getName() getOption() nameForTicket, done = getTraveling(name) price, destination = getWay() fare = getFare() seat = getSeat() age = getAge() totalcost = getTotalCost(price, fare, seat, age) print("\n" + "Thank you " + n...
0
2016-09-17T14:31:20Z
39,548,081
<p>In <code>main2</code>, change </p> <p><code>nameForTicket = getTraveling2(name, done)</code> </p> <p>to </p> <p><code>nameForTicket2 = getTraveling2(name, done)</code> </p> <p>because your print statement in <code>main2</code> addresses <code>str(nameForTicket2).title()</code>, which is trying to print the title...
0
2016-09-17T14:44:47Z
[ "python", "function" ]
Neural Network predictions are always the same while testing an fMRI dataset with pyBrain. Why?
39,547,947
<p>I am quite new to fMRI analysis. I am trying to determine which object (out of 9 objects) a person is thinking about just by looking at their Brain Images. I am using the dataset on <a href="https://openfmri.org/dataset/ds000105/" rel="nofollow">https://openfmri.org/dataset/ds000105/</a> . So, I am using a ne...
1
2016-09-17T14:31:54Z
39,548,287
<p>I can't be sure -- because I haven't used all of these tools together before, or worked specifically in this kind of project -- but I would look at the documentation and be sure that your <code>nn</code> is being created as you expect it to.</p> <p>Specifically, it mentions here:</p> <p><a href="http://pybrain.org...
1
2016-09-17T15:03:17Z
[ "python", "neural-network", "pybrain" ]
Why does SymPy not work properly with real numbers?
39,547,952
<p>I am trying to evaluate an infinite sum in SymPy. While the first expression is calculated the way I expect it, SymPy seems to have trouble with the second expression.</p> <pre><code>from sympy import * n = symbols('n') print Sum((2)**(-n), (n, 1, oo)).doit() print Sum((0.5)**(n), (n, 1, oo)).doit() </code></pre> ...
1
2016-09-17T14:32:13Z
39,548,327
<p>From the <a href="http://docs.sympy.org/latest/modules/concrete.html#concrete-functions-reference" rel="nofollow">docs:</a></p> <blockquote> <p>If it cannot compute the sum, it returns an unevaluated Sum object.</p> </blockquote> <p>Another way to do this would be:</p> <pre><code>In [40]: Sum((Rational(1,2))**(...
3
2016-09-17T15:06:42Z
[ "python", "sympy" ]
Why does SymPy not work properly with real numbers?
39,547,952
<p>I am trying to evaluate an infinite sum in SymPy. While the first expression is calculated the way I expect it, SymPy seems to have trouble with the second expression.</p> <pre><code>from sympy import * n = symbols('n') print Sum((2)**(-n), (n, 1, oo)).doit() print Sum((0.5)**(n), (n, 1, oo)).doit() </code></pre> ...
1
2016-09-17T14:32:13Z
39,622,450
<p>That's <a href="https://github.com/sympy/sympy/issues/11642" rel="nofollow">a bug</a>. It ought to work. In general, however, it's best to prefer exact rational numbers over floats in SymPy, wherever possible. If you replace <code>0.5</code> with <code>Rational(1, 2)</code> it works. </p>
2
2016-09-21T16:59:49Z
[ "python", "sympy" ]
the Georgian language in tkinter. Python
39,547,969
<p>I can not write on a standard Georgian language in the Text widget. instead of letters writes question marks . when no tkinter, ie, when writing code, Georgian font recognized without problems. Plus, if I copy the word written in Georgian and inserted in the text widget, it is displayed correctly.</p> <p>this is el...
0
2016-09-17T14:33:03Z
39,548,453
<p>Okay, so here is how I achieved it:<br/> First, make sure you have a Georgian font installed in your computer; if there is no any, then go download one (I downloaded mine from <a href="http://fonts.ge/en/font/2/AcadNusx" rel="nofollow">here</a>);<br/> Now, go to your tkinter program, and add your font to your <code>...
0
2016-09-17T15:20:30Z
[ "python", "tkinter", "georgian" ]
the Georgian language in tkinter. Python
39,547,969
<p>I can not write on a standard Georgian language in the Text widget. instead of letters writes question marks . when no tkinter, ie, when writing code, Georgian font recognized without problems. Plus, if I copy the word written in Georgian and inserted in the text widget, it is displayed correctly.</p> <p>this is el...
0
2016-09-17T14:33:03Z
39,563,799
<p>The best answer I can determine so far is that there is something about Georgian and keyboard entry that tk does not like, at least not on Windows. </p> <p>Character 'translation' is usually called 'transliteration'.</p> <p>Tk text uses the Basic Multilingual Plane (the BMP, the first 2**16 codepoints) of Unicode....
0
2016-09-19T00:13:17Z
[ "python", "tkinter", "georgian" ]
Pandas dataframe slicing
39,547,985
<p>I have the following dataframe:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 0 5.31 5.27 5.61 4.34 4.54 5.02 7.07 Gewinn pro Aktie in EUR 1 13.39 14.70 12.45 16.29 15.67 14.17 10.08 KGV 2 -21.21 -0.75 6.45 -22.63 -7.75 9....
1
2016-09-17T14:34:50Z
39,548,058
<p>Not sure why the last five years are 2012-2016 (they seem to be the <em>first</em> five years). Notwithstanding, to find the mean for 2012-2016 for <code>'KGV'</code>, you can use</p> <pre><code>df[df['Kategorie'] == 'KGV'][[c for c in df.columns if c != 'Kategorie' and 2012 &lt;= int(c) &lt;= 2016]].mean(axis=1) <...
2
2016-09-17T14:42:17Z
[ "python", "pandas", "dataframe" ]
Pandas dataframe slicing
39,547,985
<p>I have the following dataframe:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 0 5.31 5.27 5.61 4.34 4.54 5.02 7.07 Gewinn pro Aktie in EUR 1 13.39 14.70 12.45 16.29 15.67 14.17 10.08 KGV 2 -21.21 -0.75 6.45 -22.63 -7.75 9....
1
2016-09-17T14:34:50Z
39,548,073
<p>I used <code>filter</code> and <code>iloc</code></p> <pre><code>row = df[df.Kategorie == 'KGV'] row.filter(regex='\d{4}').sort_index(1).iloc[:, -5:].mean(1) 1 13.732 dtype: float64 </code></pre>
2
2016-09-17T14:43:53Z
[ "python", "pandas", "dataframe" ]
Pandas dataframe slicing
39,547,985
<p>I have the following dataframe:</p> <pre><code> 2012 2013 2014 2015 2016 2017 2018 Kategorie 0 5.31 5.27 5.61 4.34 4.54 5.02 7.07 Gewinn pro Aktie in EUR 1 13.39 14.70 12.45 16.29 15.67 14.17 10.08 KGV 2 -21.21 -0.75 6.45 -22.63 -7.75 9....
1
2016-09-17T14:34:50Z
39,548,150
<p><code>loc</code> supports that type of slicing (from left to right):</p> <pre><code>df.loc[df["Kategorie"] == "KGV", "2012":"2016"].mean(axis=1) Out: 1 14.5 dtype: float64 </code></pre> <p>Note that this does not necessarily mean 2012, 2013, 2014, 2015 and 2016. These are strings so it means all columns betwee...
4
2016-09-17T14:50:39Z
[ "python", "pandas", "dataframe" ]
Printing Simple Diamond Pattern in Python
39,548,099
<p>I would like to print the following pattern in Python 3.5 (I'm new to coding): </p> <pre><code> * *** ***** ******* ********* ******* ***** *** * </code></pre> <p>But I only know how to print the following using the code below, but not sure how to invert it to make it a complete diamond:</p> <p...
0
2016-09-17T14:46:00Z
39,548,404
<p>Since the middle and largest row of stars has 9 stars, you should make <code>n</code> equal to 9. You were able to print out half of the diamond, but now you have to try to make a function that prints a specific number of spaces, then a specific number of stars. So try to develop a pattern with the number of spaces ...
0
2016-09-17T15:15:01Z
[ "python" ]
Printing Simple Diamond Pattern in Python
39,548,099
<p>I would like to print the following pattern in Python 3.5 (I'm new to coding): </p> <pre><code> * *** ***** ******* ********* ******* ***** *** * </code></pre> <p>But I only know how to print the following using the code below, but not sure how to invert it to make it a complete diamond:</p> <p...
0
2016-09-17T14:46:00Z
39,548,445
<p>As pointed out by Martin Evans in his post: <a href="http://stackoverflow.com/a/32613884/4779556">http://stackoverflow.com/a/32613884/4779556</a> a possible solution to the diamond pattern could be: </p> <blockquote> <pre><code>side = int(input("Please input side length of diamond: ")) for x in list(range(side)) +...
1
2016-09-17T15:19:34Z
[ "python" ]
My code skips the IF block and goes to ELSE
39,548,134
<p>Just started python a few hours ago and stumbles across a problem. The blow snippet shows that initially I store a userInput as 1 or 2 then execute a if block. Issue is that the code jumps straight to else (even if i type 1 in the console window). I know Im making a simple mistake but any help will be appreciated.<...
1
2016-09-17T14:49:09Z
39,548,199
<p>You are converting your input to float but checking for the string of the number. Change it to:</p> <pre><code>If userInput == 1.0: </code></pre> <p>Or better yet, keep it the way it is and just don't convert your user input to float in the first place. It is only necessary to convert the input to <code>float</cod...
0
2016-09-17T14:56:17Z
[ "python" ]
Faster way of converting Date column to weekday name in Pandas
39,548,139
<p>Here is my input csv file that i read via pd.read_csv()</p> <pre><code>ProductCode,Date,Receipt,Total x1,07/29/15,101790,17.35 x2,07/29/15,103601,8.89 x3,07/29/15,103601,8.58 x4,07/30/15,101425,11.95 x5,07/29/15,101422,1.09 x6,07/29/15,101422,0.99 x7,07/29/15,101422,3 y7,08/05/15,100358,7.29 x8,08/05/15,100358,2.6 ...
0
2016-09-17T14:49:57Z
39,548,416
<p>Specifying the format of your date strings will speed up the conversion considerably:</p> <pre><code>df['Day_of_Week'] = pd.to_datetime(df['Date'], format='%m/%d/%y').dt.weekday_name </code></pre> <p>Here are some benchmarks:</p> <pre><code>import io import pandas as pd data = io.StringIO('''\ ProductCode,Date,R...
3
2016-09-17T15:16:19Z
[ "python", "pandas" ]
inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"?
39,548,157
<p>inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"? Here is the code:</p> <pre><code>def bigger(a,b): if a &gt; b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def m...
-2
2016-09-17T14:51:22Z
39,548,229
<p>A function call is an expression. Consider the following:</p> <pre><code>def add(a, b): a + b x = add(3, 5) </code></pre> <p>Would you expect <code>x</code> to now have the value <code>8</code>? You shouldn't because <code>add</code> did not return the value of the expression <code>a+b</code>. The correct def...
0
2016-09-17T14:58:29Z
[ "python", "return" ]
inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"?
39,548,157
<p>inside the function "bigger()", it has returned a value--a or b. so, why do still need "return"s before "bigger()"s in the function "median()"? Here is the code:</p> <pre><code>def bigger(a,b): if a &gt; b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def m...
-2
2016-09-17T14:51:22Z
39,548,246
<p>I'll try to explain with examples, maybe it is simpler. </p> <p>You have defined your <code>bigger</code> function, that returns a value, right?</p> <pre><code>def bigger(a,b): if a &gt; b: return a else: return b </code></pre> <p>Now, you have defined a <code>biggest</code> function, and ...
0
2016-09-17T14:59:43Z
[ "python", "return" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original ar...
0
2016-09-17T14:55:25Z
39,548,211
<p>Since you use recursion, the slice operation in the argument will create new list instance which is different than you instance. That's the reason.</p> <p>You can change your code as following:</p> <pre><code>a = range(10) def list_reduction(array, position=0): if len(array) -1 &lt;= position: return ...
1
2016-09-17T14:57:20Z
[ "python", "list" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original ar...
0
2016-09-17T14:55:25Z
39,548,525
<p>A slice creates a new list. If you want to do this recursively, you'll have to pass the index where the function is supposed to work on the list, not the actual slice.</p>
2
2016-09-17T15:27:44Z
[ "python", "list" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original ar...
0
2016-09-17T14:55:25Z
39,548,562
<p>This is probably what you want.</p> <pre><code>a = range(1, 10) def list_reduction(l, prev_split_pos=None): split_pos = (len(l) + prev_split_pos) / 2 if prev_split_pos else len(l) / 2 if split_pos == prev_split_pos: return l[split_pos] = 0 return list_reduction(l, split_pos) list_reduction...
1
2016-09-17T15:30:48Z
[ "python", "list" ]
How to use a function to change a list when passed by reference?
39,548,189
<p>The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero. The change to zero is happens in the array but when I call print a at the end I get the original ar...
0
2016-09-17T14:55:25Z
39,548,618
<p>In Python argumnet passing is different from other conventional programming language. arguments are passed by object reference. And the whether the referred object will be modifed or not it depends on two things</p> <ul> <li>Whether the variable is mutable or immutable. In your case <code>range</code> will create a...
1
2016-09-17T15:36:48Z
[ "python", "list" ]
Faster method of looping through pixels
39,548,328
<p>I'm looping through every pixel of some photos and storing the RGB numbers, plus the location of the pixel.</p> <p>This is my current loop which looks like it might be a very slow version of what is actually possible - I have some familiarity with pandas hence I've used a dataframe to store the data inside the loop...
1
2016-09-17T15:06:47Z
39,548,510
<p>A faster way would be:</p> <pre><code>import pandas as pd from PIL import ImageColor from PIL import Image IMAGE_PATH = 'P:/image_files/' def loopThroughPixels(): im = Image.open(IMAGE_PATH + 'small_orange_white.png') w,h = im.size pixLocation = [(y, x) for x in range(h) for y in range(w)] pixRGB ...
3
2016-09-17T15:26:08Z
[ "python", "pandas" ]
Python 3: pass filename variable from Gtk.FileChooser to __init__ function
39,548,356
<p>I'm writing a Gtk program that does stuff with images. I got app window with menu and connected one of the buttons to Gtk.FileChooser that gets a filename (i can open it with Gtk.Image() but cant do much with such object afaik). The problem is I don't know how to pass the filename to my <strong>init</strong> functio...
0
2016-09-17T15:09:31Z
39,550,748
<p>Well, maybe you have a legitimate reason for using OpenCV to simply display an image (because for example you use that library elsewhere in your code) but you can use GTK+ 3 facilities for that.</p> <pre><code>import os, re import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class main_win(Gt...
0
2016-09-17T19:13:43Z
[ "python", "variables", "scope", "gtk3", "opencv3.0" ]
Python 3: pass filename variable from Gtk.FileChooser to __init__ function
39,548,356
<p>I'm writing a Gtk program that does stuff with images. I got app window with menu and connected one of the buttons to Gtk.FileChooser that gets a filename (i can open it with Gtk.Image() but cant do much with such object afaik). The problem is I don't know how to pass the filename to my <strong>init</strong> functio...
0
2016-09-17T15:09:31Z
39,563,468
<p>Moved to pyqt4, not only opencv but also matplotlib works there smoothly ;)</p>
0
2016-09-18T23:06:59Z
[ "python", "variables", "scope", "gtk3", "opencv3.0" ]
How does threading.join() detect a timeout?
39,548,357
<p>We are running quit a large Python code to randomly scan the parameter space of some physics models (So, it is very difficult to give a minimal example, sorry). Evaluating one parameter point takes about 300ms, but sometimes (I don't know why) the evaluation suddenly takes several hours which kills the CPU budget we...
-1
2016-09-17T15:09:32Z
39,549,124
<p>Short answer:</p> <p>I don't think <code>threading.join</code> checks timeout. You have to check if it has timed out.</p> <ul> <li><a href="http://stackoverflow.com/questions/13821156/timeout-function-using-threading-in-python-does-not-work">Timeout function using threading in python does not work</a></li> <li><a ...
0
2016-09-17T16:29:34Z
[ "python", "multithreading", "numpy", "nlopt" ]
How to integrate python3-flake8 with Atom in Ubuntu 16.04
39,548,524
<p>I installed python3-flake8 on Ubuntu 16.04 with the command <em>sudo apt-get install python3-flake8</em> Then proceeded to install the flake8 linter package on Atom. However on restart it shows the following error <em>Error: spawn flake8 ENOENT</em>.</p> <p>I do not know if atom is able to detect flake8 on my syste...
1
2016-09-17T15:27:44Z
39,549,171
<p>From Ubuntu 16.04, the <code>flake8</code> binary can be found in the <code>flake8</code> package rather than <code>python3-flake8</code> (<a href="http://packages.ubuntu.com/xenial/flake8" rel="nofollow">Xenial/16.04</a> and <a href="http://packages.ubuntu.com/yakkety/flake8" rel="nofollow">Yakkety/16.10</a>). Inst...
1
2016-09-17T16:34:20Z
[ "python", "ubuntu", "atom" ]
Create a a segment with the given number of verts and hook and empty to every verts in the segment
39,548,544
<p>How can I create a segment with for example 30 verices and then connect an empty with an Hook parenting to every veritces in the segment, all this via Python in Blender 3d?</p>
0
2016-09-17T15:29:32Z
39,708,428
<p>I'm going to say that this was frustrating but after trying several different approaches this is the one way that I got to work.</p> <pre><code>import bpy import bmesh num_verts = 30 scn = bpy.context.scene D = bpy.data.objects verts = [] edges = [] for i in range(num_verts): verts += [(i, 0.0, 0.0)] if ...
0
2016-09-26T17:00:48Z
[ "python", "blender", "segment", "vertices" ]
Read dicom file in python by sample ITK
39,548,551
<p>I use simple ITK for read dicom file but I do not know how to show it into a QLabel.</p> <pre><code>reader = SimpleITK.ImageFileReader() reader.SetFileName("M:\\CT-RT DICOM\ct\\CT111253009007.dcm") image1 = reader.Execute() </code></pre> <p>How can I show image1 in QLabel?</p>
1
2016-09-17T15:29:51Z
39,632,974
<p>Maybe something like this? It should generate a QImage which you can then pass into the QLabel. </p> <p>A few catch-me's will be the 16 bit image data (I assume) from the DICOM which needs passed into the RGB image. Further the scaling of the image. But this should be enough to get you started</p> <pre><code>from ...
0
2016-09-22T07:35:21Z
[ "python", "pyqt", "dicom", "itk" ]
python - import namespace
39,548,560
<p>If I have a library like:</p> <p>MyPackage:</p> <ul> <li><p><code>__init__.py</code></p></li> <li><p>SubPackage1</p> <ul> <li><code>__init__.py</code></li> <li>moduleA.py</li> <li>moduleB.py </li> </ul></li> <li>SubPackage2 <ul> <li><code>__init__.py</code></li> <li>moduleC.py</li> <li>moduleD.py</li> </ul></li>...
0
2016-09-17T15:30:33Z
39,548,591
<p>In <code>MyPackage/__init__.py</code>, import the modules you want available from the subpackages:</p> <pre><code>from __future__ import absolute_import # Python 3 import behaviour from .SubPackage1 import moduleA from .SubPackage2 import moduleD </code></pre> <p>This makes both <code>moduleA</code> and <code>mo...
3
2016-09-17T15:34:10Z
[ "python", "import", "namespaces", "package" ]
Python: monster list need monster help, how do I fill my list the proper way?
39,548,703
<p>So I started with Python yesterday and for my first project I want to make monsters battle each other.</p> <p>I'm still at the start and I want to fill a list with monsters I created. My monster function asks for how many monsters it should create and gives back a list with all of them.</p> <p>Somehow my code is w...
0
2016-09-17T15:46:06Z
39,548,736
<p>Your loop:</p> <pre><code>for i in monster: </code></pre> <p>iterates over the <em>values</em> in the <code>monster</code> list. You are not getting indices, as Python loops are <a href="https://en.wikipedia.org/wiki/Foreach_loop" rel="nofollow"><em>foreach</em> constructs</a>.</p> <p>Your list only contains the ...
3
2016-09-17T15:49:40Z
[ "python", "arrays", "list" ]
Python: monster list need monster help, how do I fill my list the proper way?
39,548,703
<p>So I started with Python yesterday and for my first project I want to make monsters battle each other.</p> <p>I'm still at the start and I want to fill a list with monsters I created. My monster function asks for how many monsters it should create and gives back a list with all of them.</p> <p>Somehow my code is w...
0
2016-09-17T15:46:06Z
39,548,754
<p>simply replace </p> <pre><code>monster = [0] * number </code></pre> <p>with </p> <pre><code>monster = range(number) </code></pre>
1
2016-09-17T15:51:12Z
[ "python", "arrays", "list" ]
How do I get np.where to accept more arguments, so it will filter >, < , and =; not just > and <?
39,548,753
<p>I am using python 3.5 and have the numpy and pandas libraries imported. I have created a DataFrame called df, which has an index starting at zero, and two columns; Percentage of Change (PofChg) and Up, Down, or Flat (U_D_F).</p> <p>For the U_D_F column I want to populate it with the words 'Up', 'Down', 'Flat', base...
3
2016-09-17T15:51:09Z
39,548,815
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map()</a> in conjunction with <code>np.sign()</code> in this case:</p> <pre><code>In [133]: mp = {-1:'Down', 0:'Flat', 1:'Up'} In [134]: df['U_D_F'] = np.sign(df.PofChg).map(mp) In [135]: df Out[135]:...
4
2016-09-17T15:56:52Z
[ "python", "pandas", "numpy", "dataframe", "where" ]
How do I get np.where to accept more arguments, so it will filter >, < , and =; not just > and <?
39,548,753
<p>I am using python 3.5 and have the numpy and pandas libraries imported. I have created a DataFrame called df, which has an index starting at zero, and two columns; Percentage of Change (PofChg) and Up, Down, or Flat (U_D_F).</p> <p>For the U_D_F column I want to populate it with the words 'Up', 'Down', 'Flat', base...
3
2016-09-17T15:51:09Z
39,548,816
<blockquote> <p>Why is it displaying "Down" in the U_D_F column when the number in the PofChg column is "Zero" </p> </blockquote> <p>That is because your condition to <code>np.where</code> was > 0, so, if it is 0, the condition fails, and it chooses the alternative.</p> <blockquote> <p>I want to change it to - if...
5
2016-09-17T15:56:54Z
[ "python", "pandas", "numpy", "dataframe", "where" ]
AttributeError not generated in case of passing method reference
39,548,864
<p>I have one simple doubt with respect to python 2.7:</p> <p>I have created an abstract base class and a child class:</p> <pre><code>from abc import ABCMeta, abstractmethod class Base: """ Abstract base class for all entities. """ __metaclass__ = ABCMeta def __init__(self, name): self...
-2
2016-09-17T16:01:37Z
39,548,895
<p>In your first example you simply created a recursive function:</p> <pre><code>def send_data(self): self.send_data() </code></pre> <p>This calls itself, without end, and that's why you end up with a recursion depth exception.</p> <p>Your second example <em>doesn't actually call the method</em>:</p> <pre><code...
0
2016-09-17T16:06:03Z
[ "python", "abstract-base-class" ]
Indexing a matrix by a column vector
39,548,914
<p>I have a matrix M of size m x n, and column vector of m x 1. For each of m rows, I need to pickup the index corresponding to the value in the column vector minus 1. Thus, giving me answer m x 1. How can I do this?</p> <pre><code>zb=a1.a3[np.arange(a1.z3.shape[0]),a1.train_labels-1] zb.shape Out[72]: (4000, 4000) ...
1
2016-09-17T16:08:09Z
39,549,012
<p>If your 2d array is <em>M</em>, and indices are a 1d array <code>v</code>, then you can use</p> <pre><code>M[np.arange(len(v)), v - 1] </code></pre> <p>For example:</p> <pre><code>In [14]: M = np.array([[1, 2], [3, 4]]) In [15]: v = np.array([2, 1]) In [16]: M[np.arange(len(v)), v - 1] Out[16]: array([2, 3]) </...
1
2016-09-17T16:17:31Z
[ "python", "numpy" ]
New Programmer, How do you use If and Elif and Else statements? Its giving me NameError: name 'No' is not defined
39,548,972
<pre><code>answer = input('Hi! Would you like to say something? (No or Yes)') if answer == No or no: print('Okay then, have a good day!') elif answer == Yes or yes: answertwo = input('What would you like to say?') print(answertwo, 'Hmmmmmm, Intresting.') </code></pre> <p> <pre><code> **if answer == N...
-4
2016-09-17T16:14:04Z
39,801,058
<p>I would suggest you using <code>.lower()</code> for every input. This ensures that if some types "nO" or "YeS" it takes the lowercase equivalent. Example:</p> <pre><code>ui = input("Type \"Hi\"").lower() </code></pre> <p>Next, you should really add an <code>else</code> option to your code. This is for answers you ...
0
2016-09-30T22:39:00Z
[ "python", "if-statement", "input" ]
While loop does not recognise if statement and variables?
39,549,015
<p>I'm doing a code for a school project and I tried to include a while loop but the if statement that is inside this loop is not recognised and the program does not recognise the variable Correct_Weight under each statement and instead it takes it as 0 which causes a division by zero error. </p> <p>the code is this:<...
-1
2016-09-17T16:17:46Z
39,549,057
<p>At the top, <code>Coin_Grams</code> is set to 0:</p> <pre><code>Coin_Grams = 0 </code></pre> <p>and you never set it to something else, because you <em>break out of the loop</em> immediately:</p> <pre><code>while Continue == "y": Type_Of_Coin = input("Please enter the type of coin in the bag") break </cod...
0
2016-09-17T16:21:37Z
[ "python", "loops", "while-loop", "project", "division" ]
MIT 6.00 Newton's Method in Python 3
39,549,024
<p>This is part of the second problem set for MIT's OCW 6.00 Intro to Computation and Programming using Python. First, I created a function that evaluates a polynomial for a given x value. Then a function that computes the derivative for a given polynomial. Using those, I created a function that evaluates the first der...
0
2016-09-17T16:18:52Z
39,549,202
<p>It seems to be just a small oversight. Notice how <code>fguess</code> is printed with a value of -13.2119. In your <code>while</code> condition (in <code>else</code> from <code>compute_root</code>) you require <code>fguess &gt; 0 and fguess &lt; epsilon</code>, which is not met so nothing is done further and you exi...
0
2016-09-17T16:37:50Z
[ "python", "python-3.x", "newtons-method" ]
Form validation failing in Django
39,549,053
<p>Im trying to get a form to validate with a Charfield but using the Select widget.</p> <p>Here is my <code>view.py</code> code:</p> <pre><code>def mpld3plot(request): form = PlotlyPlotForm() form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False) if request.method == 'POST': ...
1
2016-09-17T16:21:11Z
39,556,281
<p>Turns out I did not pass the <code>request</code> object to the form.</p> <p>The <code>view.py</code> file should look like the following:</p> <pre><code>def mpld3plot(request): form = PlotlyPlotForm(request.POST) form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False) if requ...
0
2016-09-18T09:47:08Z
[ "python", "django", "forms", "validation", "python-3.x" ]
Is it possible to detect the number of local variables declared in a function?
39,549,078
<p>In a Python test fixture, is it possible to count how many local variables a function declares in its body?</p> <pre><code>def foo(): a = 1 b = 2 Test.assertEqual(countLocals(foo), 2) </code></pre> <p>Alternatively, is there a way to see if a function declares any variables at all?</p> <pre><code>def foo...
2
2016-09-17T16:23:26Z
39,549,096
<p>Yes, the associated code object accounts for all local names in the <code>co_nlocals</code> attribute:</p> <pre><code>foo.__code__.co_nlocals </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; def foo(): ... a = 1 ... b = 2 ... &gt;&gt;&gt; foo.__code__.co_nlocals 2 </code></pre> <p>See the <a href="http...
8
2016-09-17T16:25:35Z
[ "python", "metaprogramming" ]
Is it possible to detect the number of local variables declared in a function?
39,549,078
<p>In a Python test fixture, is it possible to count how many local variables a function declares in its body?</p> <pre><code>def foo(): a = 1 b = 2 Test.assertEqual(countLocals(foo), 2) </code></pre> <p>Alternatively, is there a way to see if a function declares any variables at all?</p> <pre><code>def foo...
2
2016-09-17T16:23:26Z
39,560,200
<p>To elaborate somewhat on @Martijn excellent answer, if you read the documentation for the <a href="https://docs.python.org/3/library/inspect.html" rel="nofollow">inspect — Inspect live objects</a> module, you can see that it allows for introspection of a wealth of data, including (as @Martijn noted) in the <code>c...
1
2016-09-18T16:48:01Z
[ "python", "metaprogramming" ]
Filtering out string in a Panda Dataframe
39,549,097
<p>I have the following formulas that I use to compute data in my Dataframe. The Datframe consists of data downloaded. My Index is made of dates, and the first row contains only strings..</p> <pre><code>cols = df.columns.values.tolist() weight = pd.DataFrame([df[col] / df.sum(axis=1) for col in df], index=cols).T std...
0
2016-09-17T16:25:40Z
39,549,471
<p>You could filter the rows so as to compute weight and standard deviation as follows:</p> <pre><code>df_string = df.iloc[0] # Assign First row to DF df_numeric = df.iloc[1:].astype(float) # Assign All rows after first row to DF cols = df_numeric.columns.values.tolist() </code></pre> <p>...
3
2016-09-17T17:00:46Z
[ "python", "pandas", "dataframe", "rows" ]
How to print words that only cointain letters from a list?
39,549,175
<p>Hello I have recently been trying to create a progam in Python 3 which will read a text file wich contains 23005 words, the user will then enter a <strong>string of 9 characters</strong> which the program will use to create words and compare them to the ones in the text file.</p> <p><strong>I want to print words wh...
0
2016-09-17T16:34:59Z
39,549,319
<p>You get multiple words mainly because you iterate through each character in a given word and if that character is in the <code>letterList</code> you append and print it.</p> <p>Instead, iterate on a word basis and not on a character basis while also using the <code>with</code> context managers to automatically clos...
1
2016-09-17T16:47:28Z
[ "python", "python-3.x", "for-loop", "comparison", "iteration" ]
How to print words that only cointain letters from a list?
39,549,175
<p>Hello I have recently been trying to create a progam in Python 3 which will read a text file wich contains 23005 words, the user will then enter a <strong>string of 9 characters</strong> which the program will use to create words and compare them to the ones in the text file.</p> <p><strong>I want to print words wh...
0
2016-09-17T16:34:59Z
39,549,352
<p>You can try this logic:</p> <pre><code>for word in wordList: # if not a valid work skip - moving this check out side the inner for-each will improve performance if len(word) &lt; 4 or len(word) &gt; 9 or letterList[4] not in word: continue # find the number of matching words match_count = 0 ...
0
2016-09-17T16:50:27Z
[ "python", "python-3.x", "for-loop", "comparison", "iteration" ]
How to print words that only cointain letters from a list?
39,549,175
<p>Hello I have recently been trying to create a progam in Python 3 which will read a text file wich contains 23005 words, the user will then enter a <strong>string of 9 characters</strong> which the program will use to create words and compare them to the ones in the text file.</p> <p><strong>I want to print words wh...
0
2016-09-17T16:34:59Z
39,549,442
<p>You can use lambda functions to get this done. I am just putting up a POC here leave it to you to convert it into complete solution.</p> <pre><code>filen = open("test.text", "r") word_list = filen.read().split() print("Enter your string") search_letter = raw_input()[4] solved_list = [ word for word in word_list i...
0
2016-09-17T16:58:21Z
[ "python", "python-3.x", "for-loop", "comparison", "iteration" ]
How to load a pre-trained Word2vec MODEL File and reuse it?
39,549,248
<p>I want to use a pre-trained <code>word2vec</code> model, but I don't know how to load it in python.</p> <p>This file is a MODEL file (703 MB). It can be downloaded here:<br> <a href="http://devmount.github.io/GermanWordEmbeddings/" rel="nofollow">http://devmount.github.io/GermanWordEmbeddings/</a></p>
0
2016-09-17T16:40:54Z
39,662,736
<p>just for loading</p> <pre><code>import gensim # Load pre-trained Word2Vec model. model = gensim.models.Word2Vec.load("modelName.model") </code></pre> <p>now you can train the model as usual. also, if you want to be able to save it and retrain it multiple times, here's what you should do</p> <pre><code>model.trai...
0
2016-09-23T14:02:09Z
[ "python", "file", "model", "word2vec" ]
Reshape numpy (n,) vector to (n,1) vector
39,549,331
<p>So it is easier for me to think about vectors as column vectors when I need to do some linear algebra. Thus I prefer shapes like (n,1). </p> <p>Is there significant memory usage difference between shapes (n,) and (n,1)? </p> <p>What is preferred way? </p> <p>And how to reshape (n,) vector into (n,1) vector. Someh...
1
2016-09-17T16:48:45Z
39,549,486
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape" rel="nofollow"><code>ndarray.reshape()</code></a> returns a new view, or a copy (depends on the new shape). It does not modify the array in place.</p> <pre><code>b.reshape((10, 1)) </code></pre> <p>as such is effectively...
2
2016-09-17T17:02:43Z
[ "python", "numpy" ]
Group a list of dates by month, year
39,549,338
<pre><code>raw_data = ["2015-12-31", "2015-12-1" , "2015-1-1", "2014-12-31", "2014-12-1" , "2014-1-1", "2013-12-31", "2013-12-1" , "2013-1-1",] expected_grouped_bymonth = [("2015-12", #dates_in_the_list_occured_in_december_2015) , ... ("201...
0
2016-09-17T16:49:01Z
39,553,026
<p>If you want to get the frequency of how often a date occurs per month and year you can use a <em>defaulftdict</em>:</p> <pre><code>raw_data = ["2015-12-31", "2015-12-1", "2015-1-1", "2014-12-31", "2014-12-1", "2014-1-1", "2013-12-31", "2013-12-1", "2013-1-1", ] from collections import defau...
2
2016-09-18T00:37:39Z
[ "python", "list", "datetime", "pandas", "group-by" ]
Django 1.9 error - 'User' object has no attribute 'profile'
39,549,351
<p>So I recently added an optional user profile model that is linked to a user via a OneToOneField like so:</p> <pre><code>class UserProfile(models.Model): # Creating class user = models.OneToOneField(User, on_delete=models.CASCADE) </code></pre> <p>This worked fine, and my current UserProfile models were intact ...
0
2016-09-17T16:50:27Z
39,549,956
<p>You haven't set any related_name attribute on that one-to-one field, so the reverse accessor will be called <code>userprofile</code> not <code>profile</code>.</p>
1
2016-09-17T17:49:28Z
[ "python", "django", "django-models", "django-views" ]
Read multiple lines from a file batch by batch
39,549,426
<p>I would like to know is there a method that can read multiple lines from a file batch by batch. For example:</p> <pre><code>with open(filename, 'rb') as f: for n_lines in f: process(n_lines) </code></pre> <p>In this function, what I would like to do is: for every iteration, next n lines will be read fr...
0
2016-09-17T16:57:12Z
39,549,830
<p>You can actually just iterate over lines in a file (see <a href="https://docs.python.org/2/library/stdtypes.html#file.next" rel="nofollow">file.next</a> docs - this also works on Python 3) like</p> <pre><code>with open(filename) as f: for line in f: something(line) </code></pre> <p>so your code can be ...
0
2016-09-17T17:36:10Z
[ "python", "python-2.7", "io", "readfile" ]
Read multiple lines from a file batch by batch
39,549,426
<p>I would like to know is there a method that can read multiple lines from a file batch by batch. For example:</p> <pre><code>with open(filename, 'rb') as f: for n_lines in f: process(n_lines) </code></pre> <p>In this function, what I would like to do is: for every iteration, next n lines will be read fr...
0
2016-09-17T16:57:12Z
39,549,901
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a> and two arg <code>iter</code> can be used to accomplish this, but it's a little funny:</p> <pre><code>from itertools import islice n = 5 # Or whatever chunk size you want with open(filename...
2
2016-09-17T17:43:00Z
[ "python", "python-2.7", "io", "readfile" ]
Why does loop never exit?
39,549,429
<p>I have been working on a Bisectional Number guessing game and I would like to make it work automatically, but the code appears to be getting stuck in a loop. </p> <p>Any suggestions?</p> <pre><code>x = 75 low = 0 high = 100 guessing = True while guessing: guess = int((high + low) // 2) if guess == x: ...
0
2016-09-17T16:57:24Z
39,549,554
<p>I think it will work:</p> <pre><code>x = 75 low = 0 high = 100 guessing = True while guessing: guess = (high + low) // 2 print("guess:",guess) if guess == x: guessing = False elif guess &lt; x: low = guess else: high = guess print("Your number is ", guess) </code></pre> ...
0
2016-09-17T17:08:58Z
[ "python", "python-3.x" ]
Why does loop never exit?
39,549,429
<p>I have been working on a Bisectional Number guessing game and I would like to make it work automatically, but the code appears to be getting stuck in a loop. </p> <p>Any suggestions?</p> <pre><code>x = 75 low = 0 high = 100 guessing = True while guessing: guess = int((high + low) // 2) if guess == x: ...
0
2016-09-17T16:57:24Z
39,549,651
<p>For such things it's better to limit the number of possible iterations. </p> <pre><code>max_iter = 25 x = 42 low , high = 0 , 100 for _ in range(max_iter): guess = (high + low) // 2 if guess == x: break low , high = (guess , high) if x &gt; guess else (low , guess) print("Your number is {}".fo...
0
2016-09-17T17:16:59Z
[ "python", "python-3.x" ]
Finding multiple lines with a regex?
39,549,437
<p>I am trying to complete a "Regex search" project from the book <a href="https://automatetheboringstuff.com/chapter8/" rel="nofollow">Automate boring stuff with python</a>. I tried searching for answer, but I failed to find related thread in python.</p> <p>The task is: "Write a program that opens all .txt files in a...
1
2016-09-17T16:58:04Z
39,550,854
<p>In python regex, parentheses define a <em>capturing group</em>. (See <a href="https://regex101.com/r/iV8nS1/1" rel="nofollow">here</a> for breakdown and explanation).</p> <p><code>findall</code> will only return the captured group. If you want the entire line, you will have to iterate over the result of <code>findi...
0
2016-09-17T19:24:51Z
[ "python", "regex", "python-3.x" ]