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
array assignment using slicing
37,883,776
<p>When I was using array assignment using slicing, there is some thing strange happened. The source code is below:</p> <pre><code>import numpy as np a = np.array([1,2,3,4]).reshape(2,2) b = np.array([5,6,7,8]).reshape(2,2) print(id(a)) print(id(b)) b = a[:] b[1,1] = 10 print(b is a) print(id(a)) print(id(b)) print(a)...
0
2016-06-17T14:10:14Z
37,885,068
<p>With lists, <code>b=a[:]</code> makes a copy of <code>a</code>. Changes to <code>b</code> will not affect <code>a</code> or its values.</p> <p>But with an <code>numpy</code> array, this action makes <code>view</code>. <code>b</code> is a new object, but it shares the underlying data buffer. Changes to values in ...
0
2016-06-17T15:16:38Z
[ "python", "arrays", "numpy" ]
Creating objects within an existing object in Python
37,883,925
<p>I would like to create an object that holds and creates different objects within itself. I have an outer class and inner classes, like this:</p> <pre><code>class Outer: def __init__(self, name): self.name = name def sayHello(self): print "Hello " + self.name class Inner1: def _...
1
2016-06-17T14:18:37Z
37,884,305
<p>Here is how you would do nested classes and nested instantiations. When you're embedding the classes, you're only embedding the types. You have to create the instances in <code>self.__init__</code> </p> <p>(If you're trying to do global inner instances shared among all Outer instances please update your question....
2
2016-06-17T14:36:54Z
[ "python", "class", "object", "inner-classes" ]
Creating objects within an existing object in Python
37,883,925
<p>I would like to create an object that holds and creates different objects within itself. I have an outer class and inner classes, like this:</p> <pre><code>class Outer: def __init__(self, name): self.name = name def sayHello(self): print "Hello " + self.name class Inner1: def _...
1
2016-06-17T14:18:37Z
37,884,339
<p>Honestly inner classes are not generally a good idea, especially if you're instantiating them outside of the "containing" class. </p> <p>But to answer your question, basically the inner class is just declared in a different scope, so you need to reference the scope it is in. </p> <pre><code># Changed to a capitol ...
2
2016-06-17T14:38:46Z
[ "python", "class", "object", "inner-classes" ]
tasty pie - Return JSON with non ORM object
37,883,990
<p>I am new with tasty pie and I am trying to simply return a json structure from my API.</p> <p>I have the following class:</p> <pre><code>class CaseResource(Resource): class Meta: authentication = SessionAuthentication() resource_name = 'case' allowed_methods = ['get'] def obj_get_l...
2
2016-06-17T14:21:09Z
37,916,246
<p>For one single request you could make none RESTful endpoint. This would be not right if you have decided for some reason that your whole service is going to be 100% RESTful. </p> <p>But, if you are looking for something less heavily try standard Django view:</p> <pre><code>import json from django.http import (Htt...
0
2016-06-20T06:54:37Z
[ "python", "django", "tastypie" ]
Bug with in-place quick selection (aka linear time selection) in Python
37,884,105
<p>I am following the Stanford course "Algorithms: Design and Analysis, Part 1", while trying implement an in place randomized selection algorithm in Python (i.e. selection based on quick sort), I believe my partition function is correct, but I just cannot figure out why the selection part keeps failing, any suggestion...
2
2016-06-17T14:26:54Z
37,886,419
<p>The problem is you need to decide whether your indices are based on 0, or based on start. </p> <p>Most of the code uses indices based on 0, except the recursive call to random_selection:</p> <pre><code>return random_selection(nums, pivot + 1, end, i - pivot) </code></pre> <p>which adjusts the i index to <code>i ...
2
2016-06-17T16:37:10Z
[ "python", "algorithm", "quicksort" ]
Tensorflow Dimensions are not compatible in CNN
37,884,106
<p>This is main.py:</p> <pre><code># pylint: disable=missing-docstring from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from pylab import * import cnn # ...
0
2016-06-17T14:26:54Z
37,884,958
<p>Easy Typo:</p> <p>In your second convolution:</p> <pre><code>conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='VALID') </code></pre> <p>Change <code>images</code> to <code>pool1</code>:</p> <pre><code>conv = tf.nn.conv2d(pool1, kernel, [1, 1, 1, 1], padding='VALID') </code></pre>
2
2016-06-17T15:11:18Z
[ "python", "numpy", "machine-learning", "tensorflow" ]
Odoo do not add new XML file after module update
37,884,180
<p>I have a module already installed inside my project with a couple of new tables. Now, I want to add XML associated with these tables to create menu items.</p> <p>In my <strong>openerp</strong>.py, I had this code:</p> <pre><code> 'data': ['main.xml', 'security/ir.model.access.csv'] </code></pre> <p>Now, I want to...
0
2016-06-17T14:30:39Z
37,915,264
<p>Create new database and reinstall your module if possible.</p>
-1
2016-06-20T05:41:19Z
[ "python", "python-2.7", "openerp", "odoo-8", "openerp-8" ]
Odoo do not add new XML file after module update
37,884,180
<p>I have a module already installed inside my project with a couple of new tables. Now, I want to add XML associated with these tables to create menu items.</p> <p>In my <strong>openerp</strong>.py, I had this code:</p> <pre><code> 'data': ['main.xml', 'security/ir.model.access.csv'] </code></pre> <p>Now, I want to...
0
2016-06-17T14:30:39Z
37,917,435
<p>If you are brave, use pgAdmin III to delete the view form ir_ui_view table. Make sure that you also delete data from all the related tables such as ir_ui_view. Sometimes OpenERP does not realise that there is an update in the xml. By deleting the correct data in ir_ui_view, you ensure that the view must be recrea...
-1
2016-06-20T08:08:56Z
[ "python", "python-2.7", "openerp", "odoo-8", "openerp-8" ]
Odoo do not add new XML file after module update
37,884,180
<p>I have a module already installed inside my project with a couple of new tables. Now, I want to add XML associated with these tables to create menu items.</p> <p>In my <strong>openerp</strong>.py, I had this code:</p> <pre><code> 'data': ['main.xml', 'security/ir.model.access.csv'] </code></pre> <p>Now, I want to...
0
2016-06-17T14:30:39Z
37,947,537
<pre><code> &lt;menuitem action="action_partner_trip_form" name="Trips" sequence="4" parent="base.menu_sales" groups="base.group_no_one"/&gt; </code></pre> <p>Won't work. </p> <p>we need to put an ID to the menuitem like this:</p> <pre><code> &lt;menuitem id="menu_trips" action="action_partner_trip_form" name="Trips...
1
2016-06-21T14:41:58Z
[ "python", "python-2.7", "openerp", "odoo-8", "openerp-8" ]
How to mix several python scripts into a shell script?
37,884,201
<p>I have a local repository and now I would like to deploy it to a docker container. I'd like to write a shell script to handle the setup of environment.</p> <p>The shell script may do somethings like this in order:</p> <p>1.Install virtualenv</p> <pre><code>pip install virtualenv </code></pre> <p>2.Setup a new vi...
2
2016-06-17T14:31:51Z
37,884,365
<p><a href="https://github.com/ansible/ansible" rel="nofollow">Ansible</a> is a good choice for this. Its easy to get started and can scale up as your system complexity increases. Please refer to this <a href="http://docs.ansible.com/ansible/intro_getting_started.html" rel="nofollow">tutorial</a>. A simply <code>yml</c...
1
2016-06-17T14:40:05Z
[ "python", "bash", "shell", "docker", "virtualenv" ]
I am trying to use python and store the href element from in a list
37,884,254
<p>I am trying to store the href elements in a list but have a bit of trouble due to my limited knowledge of python.</p> <pre><code>import requests, bs4 url = 'https://www.hellopeter.com/spar?page=2' response = requests.get(url) html = response.content soup = bs4.BeautifulSoup(html, "lxml") url_list = [] for detail...
-1
2016-06-17T14:34:43Z
37,884,437
<p>use the lxml library</p> <pre><code>from lxml import html import requests page = requests.get('https://www.hellopeter.com/spar?page=2') # or just get the page using urllib2 library tree = html.fromstring(page.content) divs= tree.xpath('//div[contains(@class, "col-xs-12") and contains(@class, "review-post")]') ls...
-1
2016-06-17T14:43:28Z
[ "python", "web-scraping", "bs4" ]
matplotlib 2D slice of 3D data
37,884,265
<p>I haven't been able to find anything on this, maybe because I don't have the right nomenclature (i.e. I don't know exactly how to ask for it), but anyway, I have a 3D numpy array "a". I would like to identify and plot the 2D surface where a=0. To make clear, the data is double precision floats smoothly varying ove...
2
2016-06-17T14:35:13Z
37,884,520
<p>To "identify and plot the 2D surface where a=0", you just need to subset the data where <code>a=0</code> and plot (shown below) If you are looking for a projection of the data onto that plane, then that is a little more complicated.</p> <pre><code>threeD = np.array([(x,y,z) for x in [0,1] for y in [1,2] for z in [5...
1
2016-06-17T14:47:24Z
[ "python", "matplotlib", "plot", "scipy", "surface" ]
matplotlib 2D slice of 3D data
37,884,265
<p>I haven't been able to find anything on this, maybe because I don't have the right nomenclature (i.e. I don't know exactly how to ask for it), but anyway, I have a 3D numpy array "a". I would like to identify and plot the 2D surface where a=0. To make clear, the data is double precision floats smoothly varying ove...
2
2016-06-17T14:35:13Z
37,897,803
<p>The volume slicing operation usually relies on a notion of interpolation and the the most typical are: <a href="https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation" rel="nofollow">Nearest neighbor</a>, <a href="https://en.wikipedia.org/wiki/Linear_interpolation" rel="nofollow">Linear</a>, and <a href="https...
0
2016-06-18T14:01:03Z
[ "python", "matplotlib", "plot", "scipy", "surface" ]
Go back and retry when given wrong input & decision tree
37,884,272
<p>So I'm brand new to coding and using python so I've been looking around at tutorials and now i'm trying to get my feet wet by just messing around a little. I do everything in ipython while making the script in the application Brackets on mac... dunno if that changes anything at all. Just some extra info.</p> <p>So,...
0
2016-06-17T14:35:45Z
37,884,614
<p>So if statements are going to be your best friend! Another thing I would recommend is while loops! So every time you ask the user to input a yes or no, do it in a while loop! </p> <pre><code>userAnswer =input("Yes or no??") while (userAnswer != yes and userAnswer != no): userAnswer = input("Yes or no???") </cod...
0
2016-06-17T14:51:34Z
[ "python", "loops", "input", "back" ]
Go back and retry when given wrong input & decision tree
37,884,272
<p>So I'm brand new to coding and using python so I've been looking around at tutorials and now i'm trying to get my feet wet by just messing around a little. I do everything in ipython while making the script in the application Brackets on mac... dunno if that changes anything at all. Just some extra info.</p> <p>So,...
0
2016-06-17T14:35:45Z
37,884,698
<p>You can tidy up (and allow any case for input) Mr. DROP TABLEs answer like so:</p> <pre><code>userAnswer =input("Yes or no??") while userAnswer.lower() in ('yes', 'no'): userAnswer = input("Yes or no???") </code></pre>
0
2016-06-17T14:56:47Z
[ "python", "loops", "input", "back" ]
How to remove minimum value from row in a matrix-
37,884,383
<p>So our assinment is to create a function that take the input grades~(An N ×M matrix containing grades on the 7-step-scale given to N students on M different assignments.), and compute gradesFinal(A vector of length n containing the final grade for each of the N students.).</p> <p>For each student, the final grade ...
2
2016-06-17T14:40:54Z
37,886,126
<p><code>grades.remove(min(grades))</code> doesn't return anything. So <code>trimmed</code> is <code>None</code>. Also, your <code>roundGrade</code> function is wrong, because you are passing a number to roundGrade, and are trying to iterate in <code>gradesRounded = [min(grade_groups,key=lambda x:abs(grade-x)) for grad...
1
2016-06-17T16:18:11Z
[ "python", "matrix", "delete-row" ]
How to remove minimum value from row in a matrix-
37,884,383
<p>So our assinment is to create a function that take the input grades~(An N ×M matrix containing grades on the 7-step-scale given to N students on M different assignments.), and compute gradesFinal(A vector of length n containing the final grade for each of the N students.).</p> <p>For each student, the final grade ...
2
2016-06-17T14:40:54Z
37,886,204
<p>There are roughly 5 areas which need to be changed in the original code: Indentation, <code>list.remove</code>, <code>if</code>/<code>elif</code> order, the way the presence of a value is checked for in a list and passing of lists in the <code>roundGrade()</code> function.</p> <p><strong>1. Indentation</strong></p>...
1
2016-06-17T16:22:41Z
[ "python", "matrix", "delete-row" ]
How to remove minimum value from row in a matrix-
37,884,383
<p>So our assinment is to create a function that take the input grades~(An N ×M matrix containing grades on the 7-step-scale given to N students on M different assignments.), and compute gradesFinal(A vector of length n containing the final grade for each of the N students.).</p> <p>For each student, the final grade ...
2
2016-06-17T14:40:54Z
37,886,602
<p>Here is a solution which works directly on the <code>NxM</code> 2d array, and not on each vector individually, so I assume that M is the same for all students, and missing values (assignments) are set to <code>nan</code>. <code>G</code> can also be just 1d, which means there is only 1 assignment per student.</p> <p...
1
2016-06-17T16:49:59Z
[ "python", "matrix", "delete-row" ]
How to append reshaped / flattened images to a python list without consuming too much memory?
37,884,465
<p>I'm trying to read around 2,000 grayscale images (640 x 480) from a directory using opencv, scale down the intensity values between 0 and 1, flatten the images as one-dimensional numpy arrays and append them to a list for feeding them to a Neural Network later. This is my code :</p> <pre><code>import os import cv2 ...
2
2016-06-17T14:44:47Z
37,885,103
<p>Each of your images is 640 * 480, or 307200 pixels. You're reading each pixel as as a <code>float</code>, <a href="http://stackoverflow.com/questions/16972501/numpy-size-of-data-type">which might be as much as 8 bytes</a>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; print np.dtype(float).itemsize ...
3
2016-06-17T15:18:21Z
[ "python", "opencv", "numpy", "image-processing", "neural-network" ]
Python - Converting a string into a dictionary
37,884,466
<p>I need help trying to put an inputted string into a dictionary </p> <p>Input:</p> <pre><code>Hello my name is Bob Hello Hello </code></pre> <p>Actual output:</p> <p>Desired output:</p> <pre><code>{'Hello' : '1', 'my' : '2', 'name' : '3', 'is' : '4', 'Bob' : '5'} </code></pre> <p>Should only record the same wo...
-2
2016-06-17T14:44:48Z
37,884,878
<p>The code below splits a sentence into words and puts them in a dcitionary in the manner that you want.</p> <pre><code>&gt;&gt;&gt; string = 'Hello my name is bob' &gt;&gt;&gt; string = {v: k for k ,v in enumerate(string.split(), start=1)} &gt;&gt;&gt; string {'bob': 5, 'is': 4, 'my': 2, 'Hello': 1, 'name': 3} &gt;&...
0
2016-06-17T15:06:48Z
[ "python" ]
How to select multiple rows in QTableWidget?
37,884,480
<p>I have a table where I've enabled ExtendedSelection:</p> <pre><code>table.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) </code></pre> <p>When I close the UI I use QSettings to remember any selected rows. When I re-open my UI I want it to automatically re-select the rows automatically.</p> <p>I have ...
0
2016-06-17T14:45:28Z
37,892,230
<p>You need to use <code>setSelected</code> on each <code>QTableWidgetItem</code></p> <pre><code>for row in xrange(table.rowCount()): table_item = table.item(row, 1) row_data = table_item.data(QtCore.Qt.UserRole) row_id = row_data if row_id in QSETTINGS: for col in table.columnCount(): ...
1
2016-06-18T00:49:00Z
[ "python", "pyqt4", "pyside", "pyqt5" ]
How to select multiple rows in QTableWidget?
37,884,480
<p>I have a table where I've enabled ExtendedSelection:</p> <pre><code>table.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) </code></pre> <p>When I close the UI I use QSettings to remember any selected rows. When I re-open my UI I want it to automatically re-select the rows automatically.</p> <p>I have ...
0
2016-06-17T14:45:28Z
37,895,291
<p>in this example <code>table.selectRow(i)</code> is working on multiselection:</p> <pre><code>import sys from PyQt5 import QtCore, QtGui, QtWidgets class MyTableWidget(QtWidgets.QTableWidget): def __init__(self, parent = None): QtWidgets.QTableWidget.__init__(self, parent) self.setRowCount(5) ...
0
2016-06-18T09:14:10Z
[ "python", "pyqt4", "pyside", "pyqt5" ]
How to select multiple rows in QTableWidget?
37,884,480
<p>I have a table where I've enabled ExtendedSelection:</p> <pre><code>table.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) </code></pre> <p>When I close the UI I use QSettings to remember any selected rows. When I re-open my UI I want it to automatically re-select the rows automatically.</p> <p>I have ...
0
2016-06-17T14:45:28Z
37,937,287
<p>By temporarily setting <code>MultiSelection</code> selection mode, each row is selected.</p> <pre><code>QSETTINGS = [1, 2, 3] # Indicates row 1, 2 and 3 should be selected # Temporarily set MultiSelection table.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) for row in xrange(table.rowCount()): tabl...
0
2016-06-21T06:45:53Z
[ "python", "pyqt4", "pyside", "pyqt5" ]
Changing the value in a dataframe column depending on the value of two columns in a diffrent dataframe
37,884,593
<p>I have two dataframes made with Pandas in python:</p> <pre><code>df1 id business state inBusiness 1 painter AL no 2 insurance AL no 3 lawyer OH no 4 dentist NY yes ........... df2 id business state 1 painter NY 2 painter ...
0
2016-06-17T14:50:44Z
37,885,274
<p>You could use <code>.merge(how='left', indicator=True)</code> (<code>indicator</code> was added in <code>pandas&gt;=0.17</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">see docs</a>) to identify matching columns as well as the source of the match to ...
2
2016-06-17T15:28:44Z
[ "python", "pandas", "dataframe" ]
Changing the value in a dataframe column depending on the value of two columns in a diffrent dataframe
37,884,593
<p>I have two dataframes made with Pandas in python:</p> <pre><code>df1 id business state inBusiness 1 painter AL no 2 insurance AL no 3 lawyer OH no 4 dentist NY yes ........... df2 id business state 1 painter NY 2 painter ...
0
2016-06-17T14:50:44Z
37,885,390
<p>Probably most efficient to create a map</p> <pre><code>inBusiness = {(business,state): 'yes' for business,state in zip(df2['business'],df2['state'])} df1['inBusiness'] = [ inBusiness.get((business,state),"no") for business,state in zip(df1['business'],df1['state'])] df1 </code><...
1
2016-06-17T15:35:26Z
[ "python", "pandas", "dataframe" ]
Stop channel.basic_consume if the connection is idle/Not consuming from long time
37,884,655
<p>I am having a use case in which i want get the last idle time(last message processed time) of a pika consumer(pika.BlockingConnection).<br/> <strong>Usecase:</strong><br/> If the last processed time is greater than Threshold time(ex: 1 hr). I want the consumer to get exited or have a callback method to decide on wha...
0
2016-06-17T14:54:41Z
37,885,243
<p>pika supports a <a href="http://pika.readthedocs.io/en/0.10.0/modules/connection.html#pika.connection.Connection.add_timeout" rel="nofollow">timeout callback.</a></p> <p>You could add this callback at the end of each message receipt, keeping the reference to it, and removing it at the start of each message receipt....
0
2016-06-17T15:26:42Z
[ "python", "rabbitmq", "amqp", "pika" ]
Collatz sequence ends at 4
37,884,792
<p>I am writing a Collatz sequence program using the practice projects from chapter 3 of Automate the boring stuff with python. </p> <p>The program outline is:</p> <blockquote> <p>Write a function named <code>collatz()</code> that has one parameter named <code>number</code>.</p> <p>If <code>number</code> is ev...
1
2016-06-17T15:01:44Z
37,884,893
<p>The problem is that you call <code>collatz()</code> once more after the loop finishes with 1. Just remove that line, and it works fine. </p> <p>Also if you move the <code>"pick a number"</code> to the <code>input</code> function, you can avoid the new line after the question and are asked again every time, if you i...
1
2016-06-17T15:07:35Z
[ "python", "python-3.x" ]
Collatz sequence ends at 4
37,884,792
<p>I am writing a Collatz sequence program using the practice projects from chapter 3 of Automate the boring stuff with python. </p> <p>The program outline is:</p> <blockquote> <p>Write a function named <code>collatz()</code> that has one parameter named <code>number</code>.</p> <p>If <code>number</code> is ev...
1
2016-06-17T15:01:44Z
37,884,961
<pre><code>def collatz(number): number = number // 2 if number % 2 == 0 else 3 * number + 1 print(number) return number number = int(input("Pick a Number\n")) while number != 1: number = collatz(number) print("Magic! You are down to 1.") </code></pre>
0
2016-06-17T15:11:21Z
[ "python", "python-3.x" ]
Django w/ sqlite3 CharField crashing on special character: "Rüppell's Vulture"
37,884,820
<p>Django verision 1.9, DB backend: sqlite3.</p> <p>I am having a hard time figuring out how to handle this error. I am importing the master bird species list (<a href="http://www.worldbirdnames.org/ioc-lists/master-list-2/" rel="nofollow">available here</a>) into a set of Django models. I had the import going well,...
0
2016-06-17T15:03:38Z
37,905,784
<p>Django CharField is a character-oriented format. You need to pass it Unicode strings.</p> <p>CSV is a byte-oriented format. When you read data out of a CSV file you get byte strings.</p> <p>To get from bytes to characters you have to know what encoding was used when the original characters were turned into bytes a...
2
2016-06-19T09:32:34Z
[ "python", "django", "csv", "unicode", "sqlite3" ]
How to find the FFT of an unevenly sampled signal in python3?
37,884,856
<p>I have a data with unevenly spaced (time) samples. How can I find the FFT of the signal and plot it. </p>
-1
2016-06-17T15:05:30Z
37,884,972
<p>You can't do an FFT of an unevenly sampled signal. That invalidates the assumptions of the math the FFT is based upon.</p> <p>You'll have to resample the signal so you have evenly spaced samples.</p> <p>This is slightly out of scope of this forum, but you can start <a href="http://dsp.stackexchange.com/questions/8...
1
2016-06-17T15:11:57Z
[ "python", "python-3.x", "signals", "signal-processing", "fft" ]
How to find the FFT of an unevenly sampled signal in python3?
37,884,856
<p>I have a data with unevenly spaced (time) samples. How can I find the FFT of the signal and plot it. </p>
-1
2016-06-17T15:05:30Z
37,889,465
<p>To use an FFT, you will need to created a vector of samples evenly spaced in time.</p> <p>If the signal was bandlimited to below a sample rate implied by the widest sample spacings, you can try polynomial interpolation between your unevenly spaced samples to create a grid of about the same number of equally spaced ...
0
2016-06-17T19:56:41Z
[ "python", "python-3.x", "signals", "signal-processing", "fft" ]
Python re: if string has one word AND any one of a list of words?
37,884,940
<p>I want to find if a string matches on this rule using a regular expression:</p> <pre><code>list_of_words = ['a', 'boo', 'blah'] if 'foo' in temp_string and any(word in temp_string for word in list_of_words) </code></pre> <p>The reason I want it in a regular expression is that I have hundreds of rules like it and d...
4
2016-06-17T15:10:19Z
37,885,126
<p>You can join the array elements using <code>|</code> to construct a lookahead assertion regex:</p> <pre><code>&gt;&gt;&gt; list_of_words = ['a', 'boo', 'blah'] &gt;&gt;&gt; reg = re.compile( r'^(?=.*\b(?:' + "|".join(list_of_words) + r')\b).*foo' ) &gt;&gt;&gt; print reg.pattern ^(?=.*\b(?:a|boo|blah)\b).*foo &g...
5
2016-06-17T15:19:43Z
[ "python", "regex" ]
populate bootstrap dropdown on the base.html using django
37,884,945
<p>Im using django 1.9 and python 3.5 which i'm both really new too, and i'm having trouble populating a bootstrap dropdown which is located in the base.html. So far i have this:</p> <p>base.html:</p> <pre><code>&lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt;Event...
1
2016-06-17T15:10:30Z
37,885,143
<p>There are a couple of issues here:</p> <p>Firstly, you don't have any context in your view called <code>categories</code>, yet you're checking for them in your template. Your view function is called 'categories', which might be creating some confusion for you. However, this is not context that is accessible to your...
1
2016-06-17T15:20:29Z
[ "python", "django", "python-3.x" ]
populate bootstrap dropdown on the base.html using django
37,884,945
<p>Im using django 1.9 and python 3.5 which i'm both really new too, and i'm having trouble populating a bootstrap dropdown which is located in the base.html. So far i have this:</p> <p>base.html:</p> <pre><code>&lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt;Event...
1
2016-06-17T15:10:30Z
37,885,184
<p>So, "categories" variable will never give you "true", while you do not define it, and add it to template context.</p> <p>Do this in your python code</p> <pre><code>def categories(request, pk): categories = Category.objects.all() return render(request, 'categories.html', {'categories': categories}) </code>...
0
2016-06-17T15:22:49Z
[ "python", "django", "python-3.x" ]
Scraping a table from webpage with Python
37,884,990
<pre><code>from bs4 import BeautifulSoup from urllib import urlopen player_code = open("/Users/brandondennis/Desktop/money/CF_Name.txt").read() player_code = player_code.split("\r") for player in player_code: html =urlopen("https://www.capfriendly.com/players/"+player+"") soup = BeautifulSoup(html, 'html.parser') ...
1
2016-06-17T15:13:00Z
37,885,084
<p>Hard to answer when there is almost no context in your question (What exactly isn't working and what exactly you are trying to scrape), but take a look at these lines:</p> <pre><code>first_columns.append(row.findAll('td'))[0] third_columns.append(row.findAll('td'))[2] </code></pre> <p>Since <code>append</code> ret...
0
2016-06-17T15:17:03Z
[ "python", "html", "csv", "beautifulsoup", "html-table" ]
Scraping a table from webpage with Python
37,884,990
<pre><code>from bs4 import BeautifulSoup from urllib import urlopen player_code = open("/Users/brandondennis/Desktop/money/CF_Name.txt").read() player_code = player_code.split("\r") for player in player_code: html =urlopen("https://www.capfriendly.com/players/"+player+"") soup = BeautifulSoup(html, 'html.parser') ...
1
2016-06-17T15:13:00Z
37,885,090
<p>Your parenthesis and brackets look misplaced. </p> <p>Does this do what you want ?</p> <pre><code>first_columns = [] third_columns = [] for row in rows[1:]: first_columns.append(row.findAll('td')[0]) third_columns.append(row.findAll('td')[2]) </code></pre> <p>Where I no longer insert all the td elements i...
0
2016-06-17T15:17:29Z
[ "python", "html", "csv", "beautifulsoup", "html-table" ]
Scraping a table from webpage with Python
37,884,990
<pre><code>from bs4 import BeautifulSoup from urllib import urlopen player_code = open("/Users/brandondennis/Desktop/money/CF_Name.txt").read() player_code = player_code.split("\r") for player in player_code: html =urlopen("https://www.capfriendly.com/players/"+player+"") soup = BeautifulSoup(html, 'html.parser') ...
1
2016-06-17T15:13:00Z
37,885,655
<p>Aside from what the others mentioned. Take a look at this line:</p> <pre><code>table = soup.findAll('table_c')[2] </code></pre> <p>here, <code>BeautifulSoup</code> would try to locate <code>table_c</code> elements. But, <code>table_c</code> is a class attribute:</p> <pre><code>&lt;div class="table_c"&gt;&lt;div c...
1
2016-06-17T15:49:00Z
[ "python", "html", "csv", "beautifulsoup", "html-table" ]
Scraping a table from webpage with Python
37,884,990
<pre><code>from bs4 import BeautifulSoup from urllib import urlopen player_code = open("/Users/brandondennis/Desktop/money/CF_Name.txt").read() player_code = player_code.split("\r") for player in player_code: html =urlopen("https://www.capfriendly.com/players/"+player+"") soup = BeautifulSoup(html, 'html.parser') ...
1
2016-06-17T15:13:00Z
37,891,039
<p><em>It seems to work fine for one player at a time, but when I change to my text file of a list of players that where I am having trouble.</em> I think how you are parsing the file is the issue, if you have a player per line just iterate over the file object, stripping any whitespace:</p> <pre><code>from bs4 import...
0
2016-06-17T22:06:49Z
[ "python", "html", "csv", "beautifulsoup", "html-table" ]
DataFrame boolean indexing using .loc
37,885,000
<p>I have a series (business_day) which was generated via <code>isin</code> in order to create the series with dtype: bool:</p> <pre><code>Series: 0 True 1 True 2 True ... 563 False 566 False Name: Date, dtpye: bool </code></pre> <p>I then tried to update another array by using:</p> <pre><code>myArray.ix[business_da...
2
2016-06-17T15:13:33Z
37,885,344
<p>Assign the result as it doesn't modify the original <code>DataFrame</code>:</p> <pre><code>myarray = myarray.loc[business_day] </code></pre>
1
2016-06-17T15:33:02Z
[ "python", "pandas", "dataframe" ]
Sum and count data from columns
37,885,024
<p>I have a <code>DataFrame</code> like: </p> <pre><code>1 member_id application_name active_seconds 2 192180 Opera 6 3 192180 Opera 7 4 192180 Chrome 243 5 5433112 Chrome 52 6 5433112 Opera 3...
1
2016-06-17T15:14:28Z
37,885,186
<p>Your <code>active_seconds</code> seem to be of <code>dtype</code> <code>string</code>, so <code>sum()</code> concatenates them.</p> <p>If you do <code>df.info()</code>, <code>active_seconds</code> probably shows <code>object</code> as <code>dtype</code>, which implies they are <code>string</code> rather than <code>...
3
2016-06-17T15:22:55Z
[ "python", "pandas", "dataframe", "group-by" ]
Python config file as JSON with inheritance
37,885,056
<p>I am looking for library that can easily return configuration object from JSON file, but not just read JSON file and return it - apply inheritance to sections. Similar what old *.ini or Zend_Config_JSON (from PHP Zend Framework)</p> <p>Example:</p> <pre><code>{ "production":{ "phpSettings":{ ...
0
2016-06-17T15:16:02Z
37,886,260
<p>Check this one </p> <pre><code>cfg = JSONConfigParser() cfg.read_string(""" [section] number = 3.141592654 dictionary = {"key": "value"} list = [1, 2, 3] nested = {"list": [1,2,3]} true = true none = null [DEFAULT] # settings in the default section are inherited # by all other sections. default-se...
-1
2016-06-17T16:26:26Z
[ "python", "json", "django", "inheritance", "config" ]
"Not a directory" when using PyCharm, pip to install numpy
37,885,077
<p>I'm trying to install Python packages, specifically numpy and networkx, using PyCharm on a laptop running Gallium, and I keep getting:</p> <pre><code>IOError: [Errno 20] Not a directory: '/tmp/pip-build-xMS1YA/numpy/doc/f2py/oldnews.html' </code></pre> <p>The path that isn't a directory varies depending on what I'...
0
2016-06-17T15:16:55Z
37,886,156
<p>When the other person <a href="http://stackoverflow.com/questions/37249879/cant-install-update-packages-with-python-pip-errno-20-not-a-directory#comment62117795_37249879">reinstalled their OS</a> I imagine the only thing that really mattered was reinstalling pip.</p> <p>The instructions to reinstall pip can be <a h...
1
2016-06-17T16:20:06Z
[ "python", "pip", "pycharm" ]
Naming the self parameter something else
37,885,330
<p>In Python, this code is valid:</p> <pre><code>class A: def __init__(me): me.foo = 17 def print_foo(myself): print(myself.foo) def set_foo(i, v): i.foo = v </code></pre> <p>As you might already have noticed, the <code>self</code> parameter is named <code>me</code> in the <code...
4
2016-06-17T15:32:02Z
37,885,480
<p>The <strong>self</strong> parameter is really only named self by convention, and that isn't even a universally accepted convention - I also often see <strong>cls</strong> or <strong>this</strong> used instead.</p> <p>The term <strong>self</strong> isn't a keyword in python like it is in, say, Java. The user can cho...
1
2016-06-17T15:39:44Z
[ "python", "self" ]
Naming the self parameter something else
37,885,330
<p>In Python, this code is valid:</p> <pre><code>class A: def __init__(me): me.foo = 17 def print_foo(myself): print(myself.foo) def set_foo(i, v): i.foo = v </code></pre> <p>As you might already have noticed, the <code>self</code> parameter is named <code>me</code> in the <code...
4
2016-06-17T15:32:02Z
37,885,597
<p><a href="http://neopythonic.blogspot.ch/2008/10/why-explicit-self-has-to-stay.html" rel="nofollow">This blog post</a> from Guido van Rossum explains a little around the subject. Spesifically:</p> <blockquote> <p>I see no reason with this proposal to make 'self' a reserved word or to require that the prefix name b...
1
2016-06-17T15:46:39Z
[ "python", "self" ]
Naming the self parameter something else
37,885,330
<p>In Python, this code is valid:</p> <pre><code>class A: def __init__(me): me.foo = 17 def print_foo(myself): print(myself.foo) def set_foo(i, v): i.foo = v </code></pre> <p>As you might already have noticed, the <code>self</code> parameter is named <code>me</code> in the <code...
4
2016-06-17T15:32:02Z
37,885,676
<p><a href="https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments" rel="nofollow">PEP 8 addresses this pretty clearly:</a></p> <blockquote> <p>Always use self for the first argument to instance methods.</p> <p>Always use cls for the first argument to class methods.</p> </blockquote> <p>Althou...
3
2016-06-17T15:50:17Z
[ "python", "self" ]
Naming the self parameter something else
37,885,330
<p>In Python, this code is valid:</p> <pre><code>class A: def __init__(me): me.foo = 17 def print_foo(myself): print(myself.foo) def set_foo(i, v): i.foo = v </code></pre> <p>As you might already have noticed, the <code>self</code> parameter is named <code>me</code> in the <code...
4
2016-06-17T15:32:02Z
37,885,900
<p>The first part of your question is: "Is there a situation in which naming the self parameter something other than self is useful?" I don't know of any really compelling cases, but even if someone comes up with the perfect example, they're rare enough that I wouldn't look to them as the reason for this design choice:...
1
2016-06-17T16:04:06Z
[ "python", "self" ]
SGE DRMAA python job process
37,885,333
<p>I am using Python drmaa library to launch jobs on a SGE cluster. My services is available on REST API, during my test, all work fine, jobs are submitted / waited for completion / results retrieved once finished. Process is run once, in the same drmaa session.</p> <p>On my web interface, the job is not processed : -...
2
2016-06-17T15:32:08Z
37,923,406
<p>I finally found why this is not working : Finished job cannot be accessed anymore with 'qstat' method on seg (I guess this is the underlying command executed when asking for a job status via drmaa library). Some work is in progress with drmaav2 for sge which seems to solve the problem (<a href="http://stackoverflow....
0
2016-06-20T13:06:39Z
[ "python", "drmaa" ]
OpenERP - Can I just get city name in my form field with "res.better.zip"?
37,885,335
<p>I have a custom form that inherit city from "res.better.zip", this is the python code:</p> <pre><code>city= fields.Many2one('res.better.zip', 'City:') </code></pre> <p>but when I search for a city, it autofill with "zip code, city, state and country", can I only get the "city" in this field?</p> <p>P.D. this is t...
0
2016-06-17T15:32:13Z
37,905,684
<p>If i understand your question correctly, what you need to do is define _rec_name on your res.better.zip model, like:</p> <pre><code>_rec_name = 'city' </code></pre> <p>Note that will change default name for whole model res.better.zip.</p>
1
2016-06-19T09:17:44Z
[ "python", "python-2.7", "openerp", "odoo-8" ]
Delete lines in a file
37,885,457
<p>I have this code that brute forces a parameter:</p> <pre><code>import urllib import sys with open('finaltext.txt', 'r') as f: for line in f: site = urllib.urlopen("localhost/?cin="+line) if site.read() == "good": print line reponse = open("result.txt",'w') reponse.write(lin...
-1
2016-06-17T15:38:22Z
37,885,576
<pre><code>import urllib import sys s = open('index.txt','r') indx = int(s.readlines()[0]) s.close() with open('finaltext.txt', 'r') as f: g = open('result.txt','w') finaltext = f.readlines() for line in finaltext[indx:len(finaltext)]: indx+=1 with open('index.txt','w') as ixfile: ...
0
2016-06-17T15:45:12Z
[ "python", "file" ]
Are Python's map and filter really so ridiculously fast or are my measurements wrong?
37,885,531
<p>I do some speed tests for operations on vectors/lists. Suprisingly, <code>map</code> and <code>filter</code> seem to beat <code>numpy</code> by a factor of 5-10x. See the following short code sample with times given (Full code below.):</p> <pre><code>n = 10000000 a = np.random.rand(n) b = np.random.rand(n) c = a + ...
1
2016-06-17T15:42:53Z
37,885,673
<p>My guess is that <code>c = map(lambda x, y: x + y, a, b)</code> is actually not calculated. In python 3, <code>map</code> and <code>filter</code> are evaluated lazy, and therefore not before they have to be evaluated. </p> <p>You can verify this by adding a <code>list(c)</code> before you stop the timer, though thi...
3
2016-06-17T15:50:16Z
[ "python", "numpy" ]
How to take form string value from CharField and convert into object instance in Django?
37,885,550
<p>I keep running into this error:</p> <p>Cannot assign "u'Foo Group'": "Team.membership_group" must be a "Group" instance.</p> <p>In my Django application, I give the user an option to create a Team. The team has a memebership_group ForeignKey attribute which maps to 'Group' (django.contrib.auth.models.Group). In th...
2
2016-06-17T15:43:46Z
37,887,169
<p>I think in anyway it is not a good idea to do type translation in <code>form_valid</code>. If you use django1.9, then consider to create a customized <a href="https://docs.djangoproject.com/en/1.8/ref/forms/validation/#form-field-default-cleaning" rel="nofollow">FormField</a>:</p> <pre><code>from django import form...
0
2016-06-17T17:30:16Z
[ "python", "django", "django-forms" ]
Azure Access Token Request returning HTML
37,885,574
<p>I am trying to request an authorization code as <a href="https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx" rel="nofollow">documented here</a>. I am using Python requests package to do this and have the following example code:</p> <pre><code>import requests auth_endpoint = 'https://login.microsoftonline....
0
2016-06-17T15:45:04Z
37,913,967
<p>Please use session class of requests module to implement your requirement. Please refer to the following code sample:</p> <pre><code>import requests s = requests.Session() USERNAME = '&lt;username_email&gt;' PASSWORD = '&lt;userpassword&gt;' s.auth = (USERNAME, PASSWORD) TENANT_ID = '&lt;tenant_id&gt;' # Authorize...
1
2016-06-20T02:42:10Z
[ "python", "python-2.7", "azure", "python-requests", "azure-resource-manager" ]
Problems with wrapping C++ class to python
37,885,598
<p>For my project (ia for a game) I need a C network interface. I want to code my project in Python so I created a C++ wrapper from C TCP-Socket functions, to use it with <code>c-types</code> in my Python code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include "Socket.h" #include "stdio.h" voi...
-1
2016-06-17T15:46:49Z
37,899,453
<p>As you say you use a Python 3 version, the documentation for the <code>ctypes</code> module states that Python unicode strings (<code>str</code>) correspond to wide character arrays in C (<code>wchar_t *</code>), and that Python byte strings (<code>bytes</code>) correspond to narrow character arrays (<code>char *</c...
1
2016-06-18T16:54:49Z
[ "python", "c++", "c", "sockets", "ctypes" ]
Test bottle app without running bottle server
37,885,638
<p>I am following <a href="http://bottlepy.org/docs/dev/recipes.html#functional-testing-bottle-applications" rel="nofollow">Recipes</a> of <a href="/questions/tagged/bottle" class="post-tag" title="show questions tagged &#39;bottle&#39;" rel="tag">bottle</a> framework.</p> <p>When I try below code</p> <pre><code>#fil...
0
2016-06-17T15:48:08Z
37,888,197
<p>Your question doesn't make sense. How can you test a web app, without running a web engine to test it? You can test any function that manipulates data outside of bottle, but generating a 200 status, or receiving a post command inherently requires a web engine to be running?</p> <p>It would be like testing the pos...
-1
2016-06-17T18:35:04Z
[ "python", "paste", "functional-testing", "bottle", "testapp" ]
Test bottle app without running bottle server
37,885,638
<p>I am following <a href="http://bottlepy.org/docs/dev/recipes.html#functional-testing-bottle-applications" rel="nofollow">Recipes</a> of <a href="/questions/tagged/bottle" class="post-tag" title="show questions tagged &#39;bottle&#39;" rel="tag">bottle</a> framework.</p> <p>When I try below code</p> <pre><code>#fil...
0
2016-06-17T15:48:08Z
37,973,051
<p>Thanks for posting the stack trace. It clearly indicates that this is the line that is causing the 500:</p> <pre><code>assert app.get('/hello').status_code == 200 </code></pre> <p>Why don't you print the value of <code>app.get('/hello').status_code</code> so you can learn what's happening?</p> <p>I'm also pretty...
1
2016-06-22T15:58:14Z
[ "python", "paste", "functional-testing", "bottle", "testapp" ]
Python script to move data from a SQL server db to an oracle db keeps giving 'ORA-01036: illegal variable name/number'
37,885,691
<p>So I am using python to pull data from a sql server with a simple select that grabs 15 columns. The data looks like this </p> <pre><code>2016-06-01 05:45:06.003,5270,240,1,1,0,5000,1,null,null,7801009661561,0,null,null,null </code></pre> <p>The columns on the oracle table are all number except for the first column...
1
2016-06-17T15:51:14Z
37,886,725
<p><code>rec[7]</code> appears twice in the function <code>BuildBindList()</code>.</p> <p>I'm guessing this will cause the insert to fail as you passed it 16 columns to instantiate 15 bind variables in the <code>insert</code> statement.</p>
1
2016-06-17T16:57:45Z
[ "python", "sql", "oracle" ]
lte & gte query inconsistent when Crosschecking for dates in Django
37,885,729
<p>I want users to be able to check the calendar for dates already booked so the person won't be able to book a room if it has been booked already. I used the lte and gte to check for dates but it's very inconsistent.</p> <p>See what my DB looks like below.</p> <p><a href="http://i.stack.imgur.com/lJ4En.png" rel="nof...
1
2016-06-17T15:53:26Z
37,886,129
<p>Your conditions have been swapped <code>gte &lt;&gt; lte</code> . The second query worked because there is a matching date <code>'2016-06-14'</code> for <code>hotelrooms_id=1</code>.</p> <p>But you want to check if <code>start_date</code> and <code>end_date</code> are within range <code>checkin_booked_date</code> t...
2
2016-06-17T16:18:37Z
[ "python", "django", "django-models", "django-views" ]
How to calculate the midpoint of several geolocations in python
37,885,798
<p>Is there's a library or a way to calculate the center point for several geolocations points? This is my list of geolocations based in New York and want to find the approximate midpoint geolocation</p> <pre><code>L = [ (-74.2813611,40.8752222), (-73.4134167,40.7287778), (-74.3145014,40.9475244), ...
-1
2016-06-17T15:58:03Z
37,886,384
<p>After the <code>comments</code> I received and comment from <a href="http://gis.stackexchange.com/questions/12120/calculate-midpoint-from-a-series-of-latitude-and-longitude-coordinates">HERE</a></p> <p>With coordinates that <code>close to each other</code>, you can treat the Earth as being locally flat and simply f...
1
2016-06-17T16:35:19Z
[ "python", "geolocation", "centering", "ip-geolocation" ]
How to get brighness percentage level from a histogram?
37,885,830
<p>I wrote a python program that used scikit-image to return the histogram of an image:</p> <pre><code>def get_hist(image): image = img_as_float(image) hs, dis = exposure.histogram(image) cdf = np.cumsum(hs) #cumulative distribution function cdf = 255 * cdf / cdf[-1] #normalize return hs, c...
-1
2016-06-17T15:59:40Z
37,885,885
<p>Well, I don't think you need a histogram for this. Also, "how bright" is not really a defined value. What you could do, is to simply look at the average pixel value.</p> <pre><code>image = img_as_float(image) print(np.mean(image)) </code></pre> <p>Does this solve your problem?</p> <p>An example:</p> <pre><code>&...
1
2016-06-17T16:03:02Z
[ "python", "numpy", "histogram", "brightness", "scikit-image" ]
How to assign and call multiple variables inside a multiline string with Tkinter
37,885,874
<p>I am learning to code and just starting with python. I built my first "on my own" app that i plan to use to automate some typing at work when sending in DHCP requests. I am having an issue with calling multiple entries that i've set to variables inside a multiline string. I've tried using StringVar() along with tex...
-1
2016-06-17T16:02:21Z
37,922,840
<p>There are two main issues inside your code:</p> <ul> <li>Usage of StringVar</li> <li>Time when str1 is built</li> </ul> <p>As <a href="http://stackoverflow.com/users/5827215/tadhg-mcdonald-jensen">Tadhg McDonald-Jensen</a> mentioned in his commend, Tkinter.StringVar is beeing accessed by its <code>get()</code>-Met...
0
2016-06-20T12:40:20Z
[ "python", "tkinter" ]
How do I optimize a pandas apply lambda that looks at all records?
37,885,882
<p>I have a dataframe that looks like this:</p> <pre><code>ID YEAR AMOUNT 1 | 2001 | 4340 1 | 2002 | 5460 1 | 2004 | 1245 1 | 2006 | 6000 2 | 2003 | 5000 2 | 2006 | 3059 .... </code></pre> <p>I would like to add a column that computes the highest amount thus far, as in:</p> <pre><code>ID YEAR AMOUNT A...
1
2016-06-17T16:02:50Z
37,885,986
<p>Use <code>cummax</code></p> <pre><code>df['AMT_MAX'] = df.groupby('ID').AMOUNT.cummax() </code></pre>
3
2016-06-17T16:08:40Z
[ "python", "pandas", "optimization", "dataframe" ]
robot framework: difference in encoding between old formatting %s and new formatting
37,885,894
<ol> <li>I have a library with keyword. Keyword write some message to a test documentation.</li> <li>This python file in <code>utf-8</code>, and has needed heading <code># -*- coding: utf-8 -*-</code></li> <li><code>*.robot</code> files are in <code>utf-8</code></li> </ol> <p>Execution of this keyword in robot file w...
0
2016-06-17T16:03:45Z
37,908,405
<p>Try to use the <a href="http://www.tutorialspoint.com/python/string_decode.htm" rel="nofollow">Str.decode(encoding='UTF-8',errors='strict')</a> method. See <a href="https://docs.python.org/2/library/stdtypes.html#str.decode" rel="nofollow">Python doc</a>.</p> <p>Example:</p> <pre><code>"{}".format(msg.decode(error...
0
2016-06-19T14:40:54Z
[ "python", "encoding", "utf-8", "robotframework" ]
How can I compile/install VScode on ARM Linux?
37,885,903
<p>I'm trying to compile VScode 1.2 branch from git repo. The platform is Ubuntu trusty running in crouton on a Chomebook. The CPU is the Nvidia Tegra K1, 32bit ARMv7. </p> <p>Why can't this compile on ARM? It looks like it's written mainly in Node.JS and Python, both of which I have on ARM, both of which are CPU ...
1
2016-06-17T16:04:11Z
37,890,980
<p>Had the same issue on CentOS 6 (x64) with:</p> <pre><code>./scripts/npm.sh install --arch=x64 </code></pre> <p>It is treating this OS X specific module as a non-optional dependency. Only thing I see is that dependencies were flattened out in a <a href="https://github.com/Microsoft/vscode/commit/570b63910fff42ef0ee...
0
2016-06-17T22:01:12Z
[ "python", "node.js", "compilation", "vscode", "armv7" ]
How to compress and decompress a file using lzop in python?
37,885,913
<p>I know to compress and decompress a file using <code>lzop</code> in command line scripts using following syntax:</p> <pre><code>lzop [-dxlthIVL19] [-qvcfFnNPkUp] [-o file] [-S suffix] [file..] </code></pre> <p>but I would like to see compress and decompress a file in a Python script. I don't want to use as </p> <...
3
2016-06-17T16:04:49Z
37,885,932
<p>Maybe that is the python package that you are looking for ?</p> <p><a href="https://pypi.python.org/pypi/python-lzo/1.08" rel="nofollow">https://pypi.python.org/pypi/python-lzo/1.08</a></p>
2
2016-06-17T16:05:56Z
[ "python", "python-2.7" ]
Spatial Accuracy Analysis in Python
37,885,947
<p>I have a, <em>hopefully</em>, simple spatial analysis I'd like to perform in python. However, I haven't fully figured out how to get python to do what I want it to do.</p> <p>I have a CSV file with 3 critical columns: Hit or Miss, X Location, Y Location. Each row is an instance of whether a hit or miss occurred, an...
-1
2016-06-17T16:06:18Z
37,886,165
<p>You could use the Kernel Density Estimator from scipy.stats. I think this should do just what you want. It will show where data tends to cluster. The KDE will build an estimate of the 2d probabilty density. You then evaluate that KDE estimator over your 100x100 grid. You can plot the result with a counter plot....
0
2016-06-17T16:20:35Z
[ "python", "spatial", "analysis", "bins" ]
Exiting program for any input that is not a list
37,886,159
<p>My goal is to create a little program that converts angle from radiant to degree and vice-versa. I need the program to close with no error message from python if the user enters the information to convert in the wrong format.</p> <p>After assigning the variable ‘angle’ to both values of the input. The angle var...
0
2016-06-17T16:20:19Z
37,886,300
<p>What you want:</p> <pre><code>if not isinstance(angle, list): break </code></pre> <p>What you've done: <code>if angle is not list():break</code> will always evaluate to <code>True</code> as no object will ever have the same identity as the list <code>list()</code>; since <code>is</code> is a check for identity.</p...
0
2016-06-17T16:29:24Z
[ "python", "numpy", "exit-code" ]
Exiting program for any input that is not a list
37,886,159
<p>My goal is to create a little program that converts angle from radiant to degree and vice-versa. I need the program to close with no error message from python if the user enters the information to convert in the wrong format.</p> <p>After assigning the variable ‘angle’ to both values of the input. The angle var...
0
2016-06-17T16:20:19Z
37,886,496
<p>You can use <code>isinstance(angle, list)</code> to check if it is a list. But it won't help you achieve what you really want to do.</p> <p>The following code will help you with that.</p> <pre><code>question = """Please enter the angle you want to convert. If you wish to convert degree in radiant or vice-versa. Fo...
1
2016-06-17T16:42:30Z
[ "python", "numpy", "exit-code" ]
Exiting program for any input that is not a list
37,886,159
<p>My goal is to create a little program that converts angle from radiant to degree and vice-versa. I need the program to close with no error message from python if the user enters the information to convert in the wrong format.</p> <p>After assigning the variable ‘angle’ to both values of the input. The angle var...
0
2016-06-17T16:20:19Z
37,886,882
<p><em>break</em> statements are used to get out of <em>for</em> and <em>while</em> <strong>loops</strong>. Try using a <em>while</em> loop after the <em>input</em> statement to evaluate the input. Use a possible <strong>set</strong> as a conditional. You do not need to break from an <em>if</em> statement because it...
0
2016-06-17T17:08:22Z
[ "python", "numpy", "exit-code" ]
Re-run script in Python 3.5
37,886,214
<p>How do I get <code>main</code> to run again without executing the whole script again?</p> <pre><code>import sys #importing module that is used to exit the script def main (): #doing stuff main () #Re-run the script - looking for a cleaner way to do this! def restart (): restart = input("Press any key + En...
-4
2016-06-17T16:23:09Z
37,886,573
<p>You can re-run the <code>main</code> module-method as many times as you want by directly calling <code>main()</code> sequentially:</p> <pre><code>def main( ): # Code goes here... return; main(); main(); main(); </code></pre> <p>However, if you want the user-interaction like your restart method has, you migh...
0
2016-06-17T16:47:19Z
[ "python" ]
Re-run script in Python 3.5
37,886,214
<p>How do I get <code>main</code> to run again without executing the whole script again?</p> <pre><code>import sys #importing module that is used to exit the script def main (): #doing stuff main () #Re-run the script - looking for a cleaner way to do this! def restart (): restart = input("Press any key + En...
-4
2016-06-17T16:23:09Z
37,887,753
<p>In addition to Tommy's great advice, (I'm not sure of your goal in continually restarting main() as main is an empty function that doesn't do anything yet, but..) one way to have main continually repeat until the user enters <code>x</code> may be to use a <code>while True</code> loop:</p> <pre><code>import sys #imp...
0
2016-06-17T18:06:24Z
[ "python" ]
numpy where operation on 2D array
37,886,246
<p>I have a numpy array 'A' of size 571x24 and I am trying to find the index of zeros in it so I do:</p> <pre><code>&gt;&gt;&gt;A.shape (571L, 24L) import numpy as np z1 = np.where(A==0) </code></pre> <p>z1 is a tuple with following size:</p> <pre><code>&gt;&gt;&gt; len(z1) 2 &gt;&gt;&gt; len(z1[0]) 29 &gt;&gt;&gt;...
1
2016-06-17T16:25:29Z
37,886,429
<p>You can just check this with the equality operator in python with numpy. Example:</p> <pre><code>&gt;&gt;&gt; A = np.array([[0,2,2,1],[2,0,0,3]]) &gt;&gt;&gt; A == 0 array([[ True, False, False, False], [False, True, True, False]], dtype=bool) </code></pre> <p><code>np.where()</code> does something else, ...
1
2016-06-17T16:37:40Z
[ "python", "numpy" ]
numpy where operation on 2D array
37,886,246
<p>I have a numpy array 'A' of size 571x24 and I am trying to find the index of zeros in it so I do:</p> <pre><code>&gt;&gt;&gt;A.shape (571L, 24L) import numpy as np z1 = np.where(A==0) </code></pre> <p>z1 is a tuple with following size:</p> <pre><code>&gt;&gt;&gt; len(z1) 2 &gt;&gt;&gt; len(z1[0]) 29 &gt;&gt;&gt;...
1
2016-06-17T16:25:29Z
37,886,437
<p>Try this:</p> <pre><code>import numpy as np myarray = np.array([[0,3,4,5],[9,4,0,4],[1,2,3,4]]) ix = np.in1d(myarray.ravel(), 0).reshape(myarray.shape) </code></pre> <p>Output of ix:</p> <pre><code>array([[ True, False, False, False], [False, False, True, False], [False, False, False, False]], dtyp...
1
2016-06-17T16:38:23Z
[ "python", "numpy" ]
Member functions for numpy records
37,886,361
<p>I have to use numpy arrays of records to save RAM and to have fast access. But I want to use member functions on that records. For example,</p> <pre><code>X=ones(3, dtype=dtype([('foo', int), ('bar', float)])) X[1].incrementFooBar() </code></pre> <p>For ordinary python class,I can make</p> <pre><code>class QQQ: ...
0
2016-06-17T16:33:29Z
37,886,631
<p>I may be wrong, but I don't think there is a way to use member functions on the records in the numpy array like that. Alternatively, you could very easily construct a function to accomplish the same thing:</p> <pre><code>X=ones(3, dtype=dtype([('foo', int), ('bar', float)])) def incrementFooBar(X, index): X['...
3
2016-06-17T16:52:32Z
[ "python", "numpy" ]
Extracting nationalities and countries from text
37,886,534
<p>I want to extract all country and nationality mentions from text using nltk, I used POS tagging to extract all GPE labeled tokens but the results were not satisfying. </p> <pre><code> abstract="Thyroid-associated orbitopathy (TO) is an autoimmune-mediated orbital inflammation that can lead to disfigurement and blin...
3
2016-06-17T16:44:30Z
37,894,334
<p>If you want the country names to be extracted, what you need is NER tagger, not POS tagger.</p> <p>Named-entity recognition (NER) is a subtask of information extraction that seeks to locate and classify elements in text into pre-defined categories such as the names of persons, organizations, locations, expressions ...
2
2016-06-18T07:12:27Z
[ "python", "nlp", "nltk", "pos-tagger" ]
Extracting nationalities and countries from text
37,886,534
<p>I want to extract all country and nationality mentions from text using nltk, I used POS tagging to extract all GPE labeled tokens but the results were not satisfying. </p> <pre><code> abstract="Thyroid-associated orbitopathy (TO) is an autoimmune-mediated orbital inflammation that can lead to disfigurement and blin...
3
2016-06-17T16:44:30Z
37,942,886
<p>Here's <a href="https://github.com/ushahidi/geograpy" rel="nofollow">geograpy</a> that uses NLTK to perform entity extraction. It stores all places and locations as a gazetteer. It then performs a lookup on the gazetteer to fetch relevant places and locations. Look up the docs for more usage details -</p> <pre><co...
0
2016-06-21T11:13:39Z
[ "python", "nlp", "nltk", "pos-tagger" ]
Extracting nationalities and countries from text
37,886,534
<p>I want to extract all country and nationality mentions from text using nltk, I used POS tagging to extract all GPE labeled tokens but the results were not satisfying. </p> <pre><code> abstract="Thyroid-associated orbitopathy (TO) is an autoimmune-mediated orbital inflammation that can lead to disfigurement and blin...
3
2016-06-17T16:44:30Z
37,968,305
<p>So after the fruitful comments, I digged deeper into different NER tools to find the best in recognizing nationalities and country mentions and found that SPACY has a NORP entity that extracts nationalities effeciently. <a href="https://spacy.io/docs#annotation-ner" rel="nofollow">https://spacy.io/docs#annotation-ne...
1
2016-06-22T12:40:00Z
[ "python", "nlp", "nltk", "pos-tagger" ]
Django payments integration
37,886,555
<p>I have a shopping cart rendered by view method A, I want to get the details in the cart to be submitted to the pesapal api, via a <a href="https://github.com/odero/django-pesapal" rel="nofollow">pesapal package</a>. I'm using the same method as the <a href="https://github.com/odero/django-pesapal/blob/master/sandbox...
1
2016-06-17T16:45:59Z
37,887,158
<p>Looking at the documentation and the <a href="https://github.com/odero/django-pesapal" rel="nofollow">source code</a>, there doesn't seem to be a method to set any data. Do you have an example where this is done?</p>
0
2016-06-17T17:29:08Z
[ "python", "django" ]
Django payments integration
37,886,555
<p>I have a shopping cart rendered by view method A, I want to get the details in the cart to be submitted to the pesapal api, via a <a href="https://github.com/odero/django-pesapal" rel="nofollow">pesapal package</a>. I'm using the same method as the <a href="https://github.com/odero/django-pesapal/blob/master/sandbox...
1
2016-06-17T16:45:59Z
37,895,673
<p>you would get off it quickly by letting django parse your data to the template or in this case your cart. This can be done by letting your method return the data you want. Something like:</p> <pre><code>return render(request, 'yourpage.html', {'yourvariable':yourvariable}, context_instance=Reques...
1
2016-06-18T09:57:48Z
[ "python", "django" ]
Pygame inflate not working
37,886,574
<p>So I'm making a game using python and I'm looking to make a rectangle grow.</p> <p>I saw on the pygame website that you use the inflate method and saw a demo of it and tried it but it does not work.</p> <p>Here is my code:</p> <pre><code># defining statement player = Rect(300, 100, 50, 50) grow = player.inflate(1...
0
2016-06-17T16:47:19Z
37,886,624
<p><code>grow</code> is a variable, and it is not callable.</p> <p>If you want to inflate the <code>player</code>, do this - </p> <pre><code>player = Rect(300, 100, 50, 50) if player.colliderect(food): foods.remove(food) player = player.inflate(100, 100) </code></pre>
0
2016-06-17T16:52:03Z
[ "python", "pygame", "android-inflate" ]
array not being emptied in python
37,886,579
<pre><code>from bin import pmGetter from threading import Thread import time possibleRequests = ['test', 'test1'] inbox = [] inbox = pmGetter.getPms() # time to do threading def pmGetterLoop(): while True: inbox = pmGetter.getPms() def inboxReader(): print('triggered') while True: temp...
0
2016-06-17T16:47:56Z
37,886,701
<p>Here is a problem</p> <pre><code>inbox = pmGetter.getPms() def pmGetterLoop(): while True: inbox = pmGetter.getPms() </code></pre> <p>The <code>inbox</code> inside the <code>pmGetterLoop</code> function is not the same <code>inbox</code> that is outside the function. The are separate variables in sep...
1
2016-06-17T16:56:25Z
[ "python", "arrays" ]
Python Special Characters Encoding
37,886,596
<p>I have a python script that reads a <strong>CSV</strong> file and writes in a <strong>XML</strong> file. I have been hitting a wall trying to find out how to read special characters such as: ç, á, é, í, etc. The script runs perfectly fine without special characters. That is the script header:</p> <pre><code># c...
0
2016-06-17T16:49:13Z
37,886,791
<p>That's unicode. csv can't read unicode if you are in python 2.7. In python 3.x you can pass the utf-8 option while opening the file.</p> <p>In python you can decode the data[1] to utf-8 like below.</p> <pre><code>title = data[1].decode('utf-8') </code></pre> <p>Some of the windows legacy windows components in eng...
0
2016-06-17T17:01:57Z
[ "python", "xml", "csv" ]
What are the drawbacks to storing a single value as an attribute of a DataFrame instead of as a column?
37,886,785
<p>I came across some code that calculates a single value, based on a DataFrame, and stores it as an attribute of the DataFrame instead of a separate variable or a new column.</p> <p>Here's an example. The portfolio has two securities, each with a price and quantity.</p> <pre><code>import pandas data = {"Prices" : [...
1
2016-06-17T17:01:41Z
37,887,312
<p>I'm guessing this was a coding error. I've done this before.</p> <p>Assume:</p> <pre><code>df = pd.DataFrame([1], ['x']) </code></pre> <p>I thought I had:</p> <pre><code>df['y'] = 2 </code></pre> <p>But actually didn't.</p> <p>Later, I:</p> <pre><code>df.y = df.x.sum() </code></pre> <p>Had I actually done <...
1
2016-06-17T17:38:40Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Why won't this check for an element work using python elementtree
37,886,842
<p>I finally decided to learn how to parse xml in python. I'm using elementtree just to get a basic understanding. I'm on CentOS 6.5 using python 2.7.9. I've looked through the following pages:</p> <p><a href="http://www.diveintopython3.net/xml.html" rel="nofollow">http://www.diveintopython3.net/xml.html</a></p> <...
0
2016-06-17T17:05:04Z
37,888,239
<p>I think you're missing one important line from the Dive Into Python tutorial (just up from <a href="http://www.diveintopython3.net/xml.html#autopre10" rel="nofollow">here</a>):</p> <blockquote> <p>There <em>is</em> a way to search for <em>descendant</em> elements, i.e. children, grandchildren, and any element at ...
0
2016-06-17T18:37:59Z
[ "python", "xml", "celementtree" ]
python find specific pattern at end of string
37,886,859
<p>I need to find a timestamp pattern at the end of a string. For example, blahblahblah_tsYYYMMDDHHMMSS. I need to extract the time string and replace it with current timestamp. What is the regex for such pattern?</p>
-2
2016-06-17T17:06:07Z
37,887,731
<p>Thanks @rock321987, i did this:</p> <pre><code>match = re.compile("_ts\d{14}$").match(pathstring) if match: do something </code></pre> <p>It works pretty well.</p>
0
2016-06-17T18:04:58Z
[ "python", "regex" ]
python find specific pattern at end of string
37,886,859
<p>I need to find a timestamp pattern at the end of a string. For example, blahblahblah_tsYYYMMDDHHMMSS. I need to extract the time string and replace it with current timestamp. What is the regex for such pattern?</p>
-2
2016-06-17T17:06:07Z
37,888,643
<p>You might try making a function.</p> <pre><code>def tsExtractor(SomeString): #your String LenSomeString = len(SomeString) #get length of String TargetString = SomeString[(LenSomeString - 14):LenSomeString] #Get placeholder of numeric data try: int(TargetString) #attempt to change to integ...
0
2016-06-17T19:01:18Z
[ "python", "regex" ]
How is list += implemented in Python?
37,886,917
<p>What is its time and space complexity?</p> <p>I haven't been able to find an authoritative answer elsewhere on the web.</p> <p>Also, not sure why, but StackOverflow won't let me post this question until I write more text in this box.</p>
-3
2016-06-17T17:10:32Z
37,887,069
<p><code>l += other_thing</code> is mostly equivalent to</p> <pre><code>l.extend(other_thing) </code></pre> <p>or</p> <pre><code>for thing in other_thing: l.append(thing) </code></pre> <p>Under the hood, the list stores an array of pointers to its elements, usually with extra space at the end to accommodate fut...
4
2016-06-17T17:22:19Z
[ "python" ]
How is list += implemented in Python?
37,886,917
<p>What is its time and space complexity?</p> <p>I haven't been able to find an authoritative answer elsewhere on the web.</p> <p>Also, not sure why, but StackOverflow won't let me post this question until I write more text in this box.</p>
-3
2016-06-17T17:10:32Z
37,887,109
<p>the source code for python is freely available on github so you can always go look at it </p> <pre><code>static PyObject * list_inplace_concat(PyListObject *self, PyObject *other) { PyObject *result; result = listextend(self, other); if (result == NULL) return result; Py_DECREF(result); ...
3
2016-06-17T17:25:24Z
[ "python" ]
How to translate entire .txt file using Google Translate API in Python?
37,886,964
<p>I am trying to translate an entire <code>.txt</code> file using Google Translate API in Python. </p> <p>The default code is: </p> <pre><code>print(service.translations().list(source='zh', target='en', q=['上海熙缘节能环保科技服务有é™...
1
2016-06-17T17:14:13Z
37,887,177
<p>The simple and efficient solution from my own perspective without knowing the complex details and I assume the parameter <code>q</code> is the sequence of sentences/words that you want to translate will be: </p> <pre><code>print(service.translations().list( source='zh', target='en', q= (line.rstrip() for line in op...
0
2016-06-17T17:30:36Z
[ "python", "google-api", "translate" ]
Having problems keeping a simulation deterministic with random.Random(0) in python
37,886,997
<p>I have a very large simulation in python with lots of modules. I call a lot of random functions. To keep the same random results I have a variable keep_seed_random.</p> <p>As so:</p> <pre><code>import random keep_seed_random = True if keep_seed_random is False: fixed_seed = random.Random(0) else: fixed_s...
1
2016-06-17T17:16:27Z
37,888,152
<p>This is difficult to diagnose without a good reproduce case as @mart0903 mentions. However, in general, there are several sources of randomness that can occur. A few things come to mind:</p> <p>If for example you are using the <code>multiprocessing</code> and/or <code>subprocess</code> packages to spawn several p...
1
2016-06-17T18:32:19Z
[ "python", "random", "deterministic" ]
GAE NDB Confused about Models and duplicating attributes
37,887,070
<p>I'm trying to learn Google App Engine's NDB and I'm confused about the structure of models.</p> <p>My situation is similar to a CMS platform with Post Types (like in WordPress), so I have "Blogs" and "Pages". All of these Post Types require the same set of attributes: Parent, Name, Slug, Template, Content, Status, ...
0
2016-06-17T17:22:23Z
37,887,306
<blockquote> <p>How can I create many Models with the same attributes?</p> </blockquote> <p>You can subclass:</p> <pre><code>class SpecialPost(Post): """Special post type that is a different kind than Post.""" </code></pre> <p>Though it's often easy enough to use the same kind and just add an extra field that ...
2
2016-06-17T17:38:21Z
[ "python", "django", "google-app-engine", "models", "app-engine-ndb" ]
GAE NDB Confused about Models and duplicating attributes
37,887,070
<p>I'm trying to learn Google App Engine's NDB and I'm confused about the structure of models.</p> <p>My situation is similar to a CMS platform with Post Types (like in WordPress), so I have "Blogs" and "Pages". All of these Post Types require the same set of attributes: Parent, Name, Slug, Template, Content, Status, ...
0
2016-06-17T17:22:23Z
37,887,679
<p>Basically a simple example of subclassing, which @mgilson mentioned already.</p> <pre><code>class Post(ndb.Expando): parent = ndb.StringProperty() name = ndb.StringProperty() slug = ndb.StringProperty() template = ndb.StringProperty() content = ndb.StringProperty(indexed=False) status = ndb....
1
2016-06-17T18:01:59Z
[ "python", "django", "google-app-engine", "models", "app-engine-ndb" ]
Escape special characters to copy file to path
37,887,102
<p>I have a program that reads some directories and copies those files to dynamically created. The thing is shutil.copy() keeps failing in some files because they have special characters like ',&amp;,(,),',' so I want to know how to escape them dynamically also. This destination path is created dynamically and just by ...
-1
2016-06-17T17:24:33Z
37,888,194
<p>There is an encoding problem, just add this two lines to your python code:</p> <pre><code># -*- coding: utf-8 -*- import unicode_literals </code></pre>
0
2016-06-17T18:34:53Z
[ "python", "regex" ]
pandas series add fill_value from left side only
37,887,180
<p>When applying an arithmetic operator via methods on a a pandas series or dataframe, you can pass an argument <code>fill_value</code> to specify how to handle missing values. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.add.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/sta...
0
2016-06-17T17:30:43Z
37,887,181
<p>To do this from the left side's perspective:</p> <pre><code>s1.fillna(0).add(s2) 0 2.0 1 2.0 2 NaN dtype: float64 </code></pre> <p>From the right:</p> <pre><code>s1.add(s2.fillna(0)) s1.fillna(0).add(s2) 0 2.0 1 NaN 2 2.0 dtype: float64 </code></pre> <p>From both:</p> <pre><code>s1.fillna(0...
1
2016-06-17T17:30:43Z
[ "python", "pandas" ]
List comprehensions leak their loop variable in Python2: how making it be compatible with Python3
37,887,289
<p>I just learnt from <a href="http://stackoverflow.com/questions/19848082/why-do-list-comprehensions-write-to-the-loop-variable-but-generators-dont">Why do list comprehensions write to the loop variable, but generators don't?</a> that <strong>List comprehensions also "leak" their loop variable into the surrounding sco...
1
2016-06-17T17:37:42Z
37,887,328
<p>The best way is usually to just not reuse variable names like that, but if you want something that gets the Python 3 behavior in both 2 and 3:</p> <pre><code>list(x for x in (1, 2, 3)) </code></pre>
2
2016-06-17T17:40:11Z
[ "python", "python-2.7", "python-3.x", "list-comprehension", "compatibility" ]
List comprehensions leak their loop variable in Python2: how making it be compatible with Python3
37,887,289
<p>I just learnt from <a href="http://stackoverflow.com/questions/19848082/why-do-list-comprehensions-write-to-the-loop-variable-but-generators-dont">Why do list comprehensions write to the loop variable, but generators don't?</a> that <strong>List comprehensions also "leak" their loop variable into the surrounding sco...
1
2016-06-17T17:37:42Z
37,887,362
<p>@mgilson's comment is probably the truth, but if you want to write code that works in both python2 and python3, you could wrap a generator function in a list function, Example:</p> <pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13) &gt;&gt;&gt; x = 'before' &gt;&gt;&gt; a = list(x for x in (1, 2, 3)) &gt;&gt...
2
2016-06-17T17:42:28Z
[ "python", "python-2.7", "python-3.x", "list-comprehension", "compatibility" ]
Increment by one everytime loop runs
37,887,304
<p>How can I make the cell number increase by one every time it loops through all of the sheets? I got it to loop through the different sheets itself but I'm not sure how to add +1 to the cell value.</p> <pre><code>for sheet in sheetlist: wsX = wb.get_sheet_by_name('{}'.format(sheet)) ws2['D4'] = wsX[...
0
2016-06-17T17:38:17Z
37,887,339
<pre><code>for i, sheet in enumerate(sheetlist): wsX = wb.get_sheet_by_name('{}'.format(sheet)) cell_no = 'D' + str(i + 4) ws2[cell_no] = wsX['P6'].value </code></pre>
1
2016-06-17T17:41:25Z
[ "python", "excel", "loops", "openpyxl" ]
Increment by one everytime loop runs
37,887,304
<p>How can I make the cell number increase by one every time it loops through all of the sheets? I got it to loop through the different sheets itself but I'm not sure how to add +1 to the cell value.</p> <pre><code>for sheet in sheetlist: wsX = wb.get_sheet_by_name('{}'.format(sheet)) ws2['D4'] = wsX[...
0
2016-06-17T17:38:17Z
37,887,366
<p>write this outside of the loop :<br></p> <pre><code>x = 'D4' </code></pre> <p>write this in the loop :<br></p> <pre><code>x = x[0] + str(int(x[1:])+1) </code></pre>
0
2016-06-17T17:42:49Z
[ "python", "excel", "loops", "openpyxl" ]
Increment by one everytime loop runs
37,887,304
<p>How can I make the cell number increase by one every time it loops through all of the sheets? I got it to loop through the different sheets itself but I'm not sure how to add +1 to the cell value.</p> <pre><code>for sheet in sheetlist: wsX = wb.get_sheet_by_name('{}'.format(sheet)) ws2['D4'] = wsX[...
0
2016-06-17T17:38:17Z
37,887,375
<h2>DELETED</h2> <p><em>cannot delete an accepted answer</em></p>
0
2016-06-17T17:43:10Z
[ "python", "excel", "loops", "openpyxl" ]
Increment by one everytime loop runs
37,887,304
<p>How can I make the cell number increase by one every time it loops through all of the sheets? I got it to loop through the different sheets itself but I'm not sure how to add +1 to the cell value.</p> <pre><code>for sheet in sheetlist: wsX = wb.get_sheet_by_name('{}'.format(sheet)) ws2['D4'] = wsX[...
0
2016-06-17T17:38:17Z
37,887,387
<p>Try this one... it's commented so you can understand what it's doing.</p> <pre><code>#counter i = 4 for sheet in sheetlist: #looping from D4 to D25 while i &lt;= 25: wsX = wb.get_sheet_by_name('{}'.format(sheet)) #dynamic way to get the cell cell1 = 'D' + str(i) ws2[cell1]...
0
2016-06-17T17:44:19Z
[ "python", "excel", "loops", "openpyxl" ]
Increment by one everytime loop runs
37,887,304
<p>How can I make the cell number increase by one every time it loops through all of the sheets? I got it to loop through the different sheets itself but I'm not sure how to add +1 to the cell value.</p> <pre><code>for sheet in sheetlist: wsX = wb.get_sheet_by_name('{}'.format(sheet)) ws2['D4'] = wsX[...
0
2016-06-17T17:38:17Z
37,889,520
<p>No need for counters or clumsy string conversion: openpyxl provides an API for programmatic access.</p> <pre><code>for idx, sheet in enumerate(sheetlist, start=4): wsX = wb[sheet] cell = ws2.cell(row=idx, column=16) cell.value = wsX['P6'] </code></pre>
2
2016-06-17T20:00:50Z
[ "python", "excel", "loops", "openpyxl" ]