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
Retrieve yum repos and save as list in json format
38,748,692
<p>I am new to the site and have just started with Python. I am trying to think how to begin working on this problem...basically I need Python to retrieve a list of all yum repos in /etc/yum.repos.d and then save the list in a json format such as below:</p> <pre><code>{ "[repo_name]" : { "name" : "repo_nam...
0
2016-08-03T16:09:09Z
38,750,213
<p>This a example file structure</p> <pre><code>[examplerepo] name=Example Repository baseurl=http://mirror.cisp.com/CentOS/6/os/i386/ enabled=1 gpgcheck=1 gpgkey=http://mirror.cisp.com/CentOS/6/os/i386/RPM-GPG-KEY-CentOS-6 </code></pre> <p>And this is a code I used</p> <pre><code>#!/usr/bin/python import json tes...
0
2016-08-03T17:32:06Z
[ "python" ]
Convert RGB to HSV using [0, 255] range
38,748,737
<p>I have an RGB image that I want to convert to the HSV colorspace. The RGB values in the image array have a range of 0 to 255. However, almost all of the colorspace conversion functions out there require the data to have a range of 0 to 1. </p> <p>Is there anyway to get around this (short of writing my own conversio...
-1
2016-08-03T16:10:48Z
38,748,994
<p>You can use <code>preprocessing.MinMaxScaler()</code> from <code>scikit-learn</code>. </p> <p>Here is link for more <a href="http://scikit-learn.org/stable/modules/preprocessing.html" rel="nofollow">information</a> and examples. </p>
1
2016-08-03T16:23:47Z
[ "python", "image", "rgb", "python-3.5", "hsv" ]
Nesting classes 3 levels deep within Python - Is it bad practice?
38,748,749
<p>I'm working on a Python script at work that is used to interact with XLS/XLSX/CSV spreadsheets. There are three main classes which are nested inside one another (<strong>not</strong> extending one another, the classes are literally inside the other class)</p> <p>The three primary classes are explained below:</p> <...
-1
2016-08-03T16:11:34Z
38,748,975
<p>Turning your question around: is there any advantage in writing the classes as nested? Unlike functions, classes don't use "lexical scoping" (<em>i.e.</em> unlike functions, a name that can't be resolved from the current class's namespace will not be resolved from surrounding classes). This is why you have to refer ...
3
2016-08-03T16:22:50Z
[ "python", "class", "oop", "subclass" ]
Nesting classes 3 levels deep within Python - Is it bad practice?
38,748,749
<p>I'm working on a Python script at work that is used to interact with XLS/XLSX/CSV spreadsheets. There are three main classes which are nested inside one another (<strong>not</strong> extending one another, the classes are literally inside the other class)</p> <p>The three primary classes are explained below:</p> <...
-1
2016-08-03T16:11:34Z
38,767,304
<p>Setting aside some of the questions raised elsewhere, like whether you need all these classes, I'm going to say no: it's better not to nest these classes. It's better to merely document how they are intended to be used. Consider alternate names that make the classes themselves less attractive, for example WorksheetR...
0
2016-08-04T12:25:49Z
[ "python", "class", "oop", "subclass" ]
Removing header from column
38,748,752
<p>I am trying to do something similar to awk in Python to retrieve a specific column but need to remove the column header. Is there a quick simple way to remove the header from a column after using split? Below is my sample code.</p> <pre><code>du = '''Filesystem Size Used Avail Use% Mounted on /dev/sda3 ...
0
2016-08-03T16:11:42Z
38,748,831
<p>You can do this:</p> <pre><code>for line in du.splitlines()[1:]: fields = line.split() f4 = (fields[4].strip('%')) print(f4) # 14 # 0 # 1 # 1 # 0 # 58 # 69 # 1 # 0 </code></pre>
1
2016-08-03T16:15:43Z
[ "python", "multiple-columns" ]
Replacing previous text printed in shell - Windows
38,748,756
<p>I have been researching this question, and it seems that it is possible, but not possible on Windows.</p> <p>I am trying to achieve a loading bar that will print 'Loading', then 'Loading.', 'Loading..'... etc.</p> <p>This code seems to work on Linux but not Windows(Python 3.5):</p> <pre><code>x = 0 for x in range...
0
2016-08-03T16:11:54Z
38,748,943
<p>The problem is buffering: everything appears at once when the script ends. You can <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow">force Python >3.3 to flush after each print output</a>:</p> <pre><code>import time print("Loading", end="", flush=True) for x in range(0,5): print(".",...
2
2016-08-03T16:21:18Z
[ "python", "windows-console" ]
Get object with specific hour in django
38,748,899
<p>I have model like this:</p> <pre><code>class Order(models.Model): dateTime = models.DateTimeField() </code></pre> <p>and I want to get object with specific hour how can I do that? the code below doesn't work:</p> <pre><code>o=Order.objects.get(dateTime.hour=12) </code></pre> <p>and has this problem: <code>ke...
0
2016-08-03T16:18:39Z
38,749,013
<p><a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#hour" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/querysets/#hour</a></p> <pre><code>o = Order.objects.filter(dateTime__hour=12) </code></pre>
0
2016-08-03T16:24:48Z
[ "python", "django" ]
Get object with specific hour in django
38,748,899
<p>I have model like this:</p> <pre><code>class Order(models.Model): dateTime = models.DateTimeField() </code></pre> <p>and I want to get object with specific hour how can I do that? the code below doesn't work:</p> <pre><code>o=Order.objects.get(dateTime.hour=12) </code></pre> <p>and has this problem: <code>ke...
0
2016-08-03T16:18:39Z
38,749,125
<p>The following will give you all the objects having <code>hour</code> value as 12.</p> <pre><code>o = Order.objects.filter(dateTime__hour=12) </code></pre> <p>which can be used in place of </p> <pre><code>o = Order.objects.get(dateTime__hour=12)` </code></pre> <p>to get that one object, in case you have unique <...
1
2016-08-03T16:31:03Z
[ "python", "django" ]
looping through dictionary built from csv and write certain key values to file
38,748,931
<p>I am trying to open a file and read it into a dictionary. I've done this successfully, but I need to write the 'values' to variable and then take the variable and write it to another file in a certain location. Or is there a way to not putting them all into a variable. </p> <p>The 'person1' in the write section is ...
1
2016-08-03T16:20:34Z
38,749,207
<p>I'm not sure what your desired output is. What about this? In this code, I first write the beginning of the html file, then I loop through the csv file and add a few spans for each row of the file.</p> <pre><code>import csv with open('registrant_data.csv') as csvFile: readCSV = list(csv.DictReader(csvFile)) w...
0
2016-08-03T16:36:10Z
[ "python", "csv", "dictionary" ]
Errors Following Michael Halls-Moore Algorithmic Trading
38,749,037
<p>I am following Michael Halls-Moore Algorithmic Trading book and having some problems with the code. When I paste the code into python I get a load of errors.</p> <p>Am I missing something here because its exactly the same as what is written in the book?</p> <pre><code>from __future__ import print_function from nu...
0
2016-08-03T16:26:32Z
38,749,856
<p>Looks like you're pasting the code into a python interactive window. When you use the interactive window to write a block of indented code (like when defining a function or starting a for loop), pressing enter twice ends the code block section (this is why you get the error after a blank line when the code is suppos...
2
2016-08-03T17:12:24Z
[ "python", "python-2.7", "numpy", "quantitative-finance" ]
Azure WebJob in Python: How to access azure python package?
38,749,082
<p>I have a simple Azure WebJob written in Python that utilizes the azure python package (which is located in a venv within my solution). The job executes as expected on my local machine, but when I deploy it to the Azure WebJob instance, I get the following error:</p> <p>ImportError: No module named azure.storage.ta...
1
2016-08-03T16:29:41Z
38,749,600
<p>The only solution I found currently is to push yourself the packages. This might help you:</p> <p><a href="http://nicholasjackson.github.io/azure/python/python-packages-and-azure-webjobs/" rel="nofollow">http://nicholasjackson.github.io/azure/python/python-packages-and-azure-webjobs/</a></p>
0
2016-08-03T16:57:21Z
[ "python", "azure", "azure-webjobs", "azure-table-storage" ]
Azure WebJob in Python: How to access azure python package?
38,749,082
<p>I have a simple Azure WebJob written in Python that utilizes the azure python package (which is located in a venv within my solution). The job executes as expected on my local machine, but when I deploy it to the Azure WebJob instance, I get the following error:</p> <p>ImportError: No module named azure.storage.ta...
1
2016-08-03T16:29:41Z
38,757,917
<p>By default, if you leverage <code>venv</code> in your python application on Azure Web apps, after you deploying your web app to Azure, the <code>venv</code> folder will locate in <code>D:\home\site\wwwroot\env\</code>. And also the python libraries will lie at <code>D:\home\site\wwwroot\env\Lib\site-packages</code>....
2
2016-08-04T03:14:27Z
[ "python", "azure", "azure-webjobs", "azure-table-storage" ]
sizeof(string) not equal to string length
38,749,094
<p>I used to think that each character is one byte (at least that is the case in c/c++) so the size of string should be equal to <code>len(string)</code> bytes. However, a simple experiment tells me that it is not the case in python:</p> <pre><code>import string, sys, random # abstracted code, removed unnecessary part...
0
2016-08-03T16:30:05Z
38,749,126
<p>Python string objects contain <em>more information</em> than just the characters. They contain a reference count, a reference to the type definition, the length of the string, the cached hash and the interning state. See the <a href="https://hg.python.org/cpython/file/v2.7.11/Include/stringobject.h#l27" rel="nofollo...
5
2016-08-03T16:31:10Z
[ "python", "string", "python-2.7", "sizeof" ]
Fine-tuning a deep neural network in Tensorflow
38,749,120
<p>I want to partially fine-tune a pre-trained deep neural network in Tensorflow (as in, load weights for all layers but only update weights on higher level layers). </p> <p>Is there any method in Tensorflow that allows the selection of variables that should be changed and those that should be kept the same?</p> <p>T...
0
2016-08-03T16:30:57Z
38,749,587
<p>When you create an optimizer (e.g. <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#AdagradOptimizer" rel="nofollow"><code>tf.train.AdagradOptimizer</code></a>) to train your model, you can pass an explicit <code>var_list=[...]</code> argument to the <a href="https://www.tensorflow.org/v...
2
2016-08-03T16:56:56Z
[ "python", "machine-learning", "computer-vision", "tensorflow", "deep-learning" ]
Select a valid choice..That choice is not one of the available choices
38,749,132
<p>Here is my models and form in Django postgres database.When I try to create the mapspot object I get a error "Select a valid choice" even though its just a relational object.</p> <p>models.py</p> <pre><code>from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.pos...
0
2016-08-03T16:31:27Z
38,750,731
<p>Default form field for <code>ForeignKey</code> is <code>ModelChoiceField</code>. <code>ModelChoiceField</code> "validates that given id exists in the queryset". Try next:</p> <pre><code>spotform = MapSpotForm({'map': Map.objects.get(id=2).id, 'position': '10,20'}) </code></pre> <ul> <li><a href="https://docs.djang...
1
2016-08-03T18:04:11Z
[ "python", "django", "postgresql" ]
How to make a matrix out of existing xyz data
38,749,140
<p>I want to use matplotlib.pyplot.pcolormesh to plot a depth plot.</p> <p>What I have is a xyz file Three columns i.e. x(lat), y(lon), z(dep). </p> <p>All columns are of equal length</p> <p>pcolormesh require matrices as input. So using numpy.meshgrid I can transform the x and y into matrices:</p> <pre><code>xx,yy...
0
2016-08-03T16:31:44Z
38,751,293
<p>Depending on whether you're generating <code>z</code> or not, you have at least two different options.</p> <p>If you're generating <code>z</code> (e.g. you know the formula for it) it's very easy (see <code>method_1()</code> below).</p> <p>If you just have just a list of (<code>x</code>,<code>y</code>,<code>z</cod...
1
2016-08-03T18:38:22Z
[ "python", "numpy", "matrix", "matplotlib", "coordinates" ]
django deploy - ubuntu 14.04 and apache2
38,749,160
<p><a href="https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/" rel="nofollow">https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/</a></p> <p>and</p> <p><a href="https://www.youtube.com/watch?v=hBMVVruB9Vs" rel="nofollow">https://www.youtube.com/watch?v=hBMVVru...
0
2016-08-03T16:32:52Z
38,755,726
<p>The connection refused error is likely going to come down to Apache being incorrectly configured for the <code>VirtualHost</code> or you accessing wrong port. You also have other basic mistakes in your <code>wsgi.py</code> file as well.</p> <p>Starting with the <code>wsgi.py</code> file, the <code>DJANGO_SETTINGS_M...
0
2016-08-04T00:32:31Z
[ "python", "django", "apache", "ubuntu", "mod-wsgi" ]
Spark DataFrame mapPartitions
38,749,179
<p>I need to proceed distributed calculation on Spark DataFrame invoking some arbitrary (not SQL) logic on chunks of DataFrame. I did:</p> <pre><code>def some_func(df_chunk): pan_df = df_chunk.toPandas() #whatever logic here df = sqlContext.read.parquet(...) result = df.mapPartitions(some_func) </code></pre>...
1
2016-08-03T16:34:03Z
38,749,349
<p>Try this:</p> <pre><code>&gt;&gt;&gt; columns = df.columns &gt;&gt;&gt; df.rdd.mapPartitions(lambda iter: [pd.DataFrame(list(iter), columns=columns)]) </code></pre>
1
2016-08-03T16:44:07Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
represent a django model which combines data from 2 other models
38,749,188
<p><strong>Background</strong>:</p> <p>I scrape data from 2 sources for upcoming properties for sale, lets call one <code>SaleAnnouncement</code>, and the other <code>SellerMaintainedData</code>. They share many of the same field names (although some data can only be found in one and not the other). If an item is comi...
0
2016-08-03T16:34:55Z
38,749,622
<p>I would suggest another solution. What about using inheritance? You could create base class that would be abstract (<a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes</a>). You can put al...
0
2016-08-03T16:58:36Z
[ "python", "django", "django-models" ]
Python Multiprocessing: Topping off multiprocessing queue before becoming empty
38,749,215
<p>I'm trying to make a multiprocessing Queue in Python 2.7 that fills up to it's maxsize with processes, and then while there are more processes to be done that haven't yet been put into the Queue, will refill the Queue when any of the current procs finish. I'm trying to maximize performance so size of the Queue is nu...
1
2016-08-03T16:36:35Z
38,750,207
<p>Why don't you use a multiprocessing Pool to accomplish this? </p> <pre><code>import multiprocessing pool = multiprocessing.Pool() pool.map(your_function, dataset) ##dataset is a list; could be other iterable object pool.close() pool.join() </code></pre> <p>The <code>multiprocessing.Pool()</code> can have the argum...
2
2016-08-03T17:31:47Z
[ "python", "queue", "multiprocessing" ]
Change django admin template for a calendar
38,749,296
<p>I have some models, one of them it's about gym sessions, </p> <pre><code>class Gym_Class(models.Model): name = models.CharField(max_length=200) icon = models.ImageField() instructor = models.ForeignKey(Instructor, related_name="instructor") program = models.ForeignKey(Program) short_review = mod...
2
2016-08-03T16:40:46Z
38,749,777
<p>The admin template files are located in the contrib/admin/templates/admin directory.</p> <p>In order to override Gym_Class, create an admin directory in your project’s templates directory. Inside admin directory, create sub-directories named [your app name]. Inside this directory create a directory names Gym_Clas...
0
2016-08-03T17:07:59Z
[ "python", "django", "calendar", "django-templates", "django-admin" ]
Change django admin template for a calendar
38,749,296
<p>I have some models, one of them it's about gym sessions, </p> <pre><code>class Gym_Class(models.Model): name = models.CharField(max_length=200) icon = models.ImageField() instructor = models.ForeignKey(Instructor, related_name="instructor") program = models.ForeignKey(Program) short_review = mod...
2
2016-08-03T16:40:46Z
38,750,066
<p>You can change the display of the django admin by <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#overriding-admin-templates" rel="nofollow">overriding the admin templates</a>.</p> <p>The template you're specifically looking to override is named <code>change_list.html</code>. This file can be foun...
0
2016-08-03T17:23:48Z
[ "python", "django", "calendar", "django-templates", "django-admin" ]
LabelEncoder order of fit for a Pandas df
38,749,305
<p>I am fitting a scikit-learn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn-preprocessing-labelencoder" rel="nofollow">LabelEncoder</a> on a column in a pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow...
2
2016-08-03T16:41:21Z
38,749,529
<p>It's done in sort order. In the case of strings, it is done in alphabetic order. There's no documentation for this, but looking at the source code for <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/preprocessing/label.py#L130" rel="nofollow">LabelEncoder.transform</a> we can see the work ...
1
2016-08-03T16:53:48Z
[ "python", "pandas", "scikit-learn" ]
Python: No Module named Zlib, Mac OS X El Capitan 10.11.6
38,749,403
<p>I'm trying to convert my python command line application to an app with py2app. Everytime I try to import zlib or try to install setuptools , I get an error : no module named zlib.</p> <p>Python was installed with brew. I searched every corner of the internet and stack overflow, I have reinstalled python with brew ...
1
2016-08-03T16:47:37Z
38,750,903
<p>Finally found the answer.</p> <p>After using:</p> <pre><code>brew doctor </code></pre> <p>I found out that I had more config scripts in my path, according to brew doctor.</p> <p>So I did:</p> <pre><code>sudo rm -rf /Library/Frameworks/Python.framework/ </code></pre> <p>next :</p> <pre><code>brew prune </code>...
1
2016-08-03T18:14:33Z
[ "python", "osx", "homebrew", "zlib" ]
Python Get Returned Object From Called Module
38,749,431
<p>Given this module (sample.py):</p> <pre><code>def calculation(x): r = x + 1 return r </code></pre> <p>In my main .py file in Spyder, I'm calling it like this:</p> <pre><code>import sample b = sample.calculation(2) </code></pre> <p>My (dumb) question is: how to I access r, as defined in the sample module, ...
-1
2016-08-03T16:49:27Z
38,749,592
<blockquote> <p>My (dumb) question is: how to I access r, as defined in the sample module, for other calculations in the main .py file from which I'm calling sample?</p> </blockquote> <p>You use that <code>b</code> variable you assigned the value to.</p> <blockquote> <p>But what if the module returns 2 different ...
1
2016-08-03T16:57:08Z
[ "python", "object", "module", "spyder" ]
Python Get Returned Object From Called Module
38,749,431
<p>Given this module (sample.py):</p> <pre><code>def calculation(x): r = x + 1 return r </code></pre> <p>In my main .py file in Spyder, I'm calling it like this:</p> <pre><code>import sample b = sample.calculation(2) </code></pre> <p>My (dumb) question is: how to I access r, as defined in the sample module, ...
-1
2016-08-03T16:49:27Z
38,749,677
<p>Accessing another module's variable is possible by making it global. But it is not a good practice and often avoided. You can do this instead</p> <pre><code>import sample r = sample.calculation(2) </code></pre> <p>This way, you can use the same variable name 'r' but it is now a local variable. </p> <p>For your se...
1
2016-08-03T17:01:28Z
[ "python", "object", "module", "spyder" ]
How to list all unused elastic IPs and release them using boto3
38,749,484
<p>I am using boto3, I need to list all elastic IPs, find the ones that are not associated with any instance and release them.</p> <p>What I am doing is:</p> <pre><code>import boto3 ec2 = boto3.resource('ec2') </code></pre> <p>Then I could list all volumes as this:</p> <pre><code>for volume in ec2.volumes.all():...
1
2016-08-03T16:51:57Z
38,752,197
<p>I got it working with this code:</p> <pre><code>def elastic_ips_cleanup(): """ Cleanup elastic IPs that are not being used """ client = boto3.client('ec2') addresses_dict = client.describe_addresses() for eip_dict in addresses_dict['Addresses']: if "InstanceId" not in eip_dict: p...
0
2016-08-03T19:33:28Z
[ "python", "amazon-web-services", "amazon-ec2", "boto", "boto3" ]
Python: draw scatter with marker size coming from a dictionary?
38,749,490
<p>Say I have a regular grid of <code>nxn</code> points, and a dictionary telling me how many times something happens in each one of the points:</p> <pre><code>d={ (0, 0): 1114, (0, 1): 270, (3, 2): 217, (5, 6): 189, (10, 10): 164} </code></pre> <p>I want to plot a scatter of these points, the size of the marker...
0
2016-08-03T16:52:23Z
38,749,704
<p><code>X</code> <code>Y</code> and <code>S</code> are all parallel lists, so for every <code>x[n]</code> will corrospond to <code>y[n]</code> and <code>s[n]</code>. You can just iterate over the dictionary and append to all three lists simultaneously:</p> <pre><code>x_arr,y_arr,s_arr = [], [], [] for (x,y),s in d.it...
2
2016-08-03T17:03:14Z
[ "python", "dictionary", "matplotlib", "scatter-plot" ]
Global Python package
38,749,534
<p>so I have this package. In the cmd I go to <code>hp@HP-PC C:\Users\hp\Documents\scripts</code>:</p> <pre><code>hp@HP-PC C:\Users\hp\Documents\scripts &gt; python Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "licen...
-2
2016-08-03T16:53:53Z
38,749,710
<p>Run</p> <pre><code>python -m site </code></pre> <p>It'll list 2 important pieces of information:</p> <ul> <li>The Python module search path, <code>sys.path</code></li> <li>The location for the <code>USER_SITE</code> directory, and wether or not this exists.</li> </ul> <p>Python looks for modules along those loca...
1
2016-08-03T17:03:42Z
[ "python" ]
Python 3 - Tkinter button commands
38,749,620
<p>I am new to Tkinter and Python as well. I have three buttons with commands in my Tkinter frame. Button 1 calls open_csv_dialog(), opens a file dialog box to select a .csv file and returns the path. Button 2 calls save_destination_folder(), opens a file dialog box to open the preferred directory and return the path...
1
2016-08-03T16:58:30Z
38,750,155
<p>This was probably just an error typing the question.... but for completeness on this line</p> <pre><code>button3 = ttk.Button(root, text="Run", command=lambda: modify_word_doc(open_csv_dialog, save_destination_folder).pack() </code></pre> <p>You're missing the closing parenthesis for <code>ttk.Button(*)*.pack()</c...
1
2016-08-03T17:28:46Z
[ "python", "tkinter" ]
operations with elements in list of list in python
38,749,675
<p>This is my list:</p> <pre><code>volume = [['1.986', '3000'], ['1.987', '2000'], ['1.986', '700'],['1.987', '4000']] </code></pre> <p>How can I get the sum of volume[1] when volume[0] is the same price?</p> <pre><code>results = [['1.986', '3700'], ['1.987', '6000']] </code></pre>
-4
2016-08-03T17:01:21Z
38,749,795
<p>Dictionaries would be a good data structure to use here. The default dict holds unique strings as the keys and assumes empty values are 0 because I set it to be based off of int. </p> <pre><code>from collections import defaultdict d = defaultdict(int) for v in volume: d[v[0]] += int(v[1]) print d </code></pre> ...
2
2016-08-03T17:09:07Z
[ "python", "list" ]
Clean unicode before adding to Dictionary
38,749,676
<p>When parsing a page, I am pulling:</p> <pre><code>'label_value': [u'\n\t\t\t\t\t\t\t\t\t\tabc123\n\t\t\t\t\t\t\t\t\t']} </code></pre> <p>My goal is to just pull the relevant "abc123" from that xpath when it writes to the CSV. Currently, due to the "\n\t" in the string, it isn't writing anything. Looking around, I ...
3
2016-08-03T17:01:25Z
38,751,148
<p>Aren't you simply looking for <code>strip()</code> ?<br> Consider this example (see it <a href="http://ideone.com/CuRgKP" rel="nofollow"><strong>working on ideone.com</strong></a>)</p> <pre><code>label_value = ''' abc123 ''' print(label_value) print(label_value.strip()) </code></...
2
2016-08-03T18:30:07Z
[ "python", "regex", "xpath" ]
Clean unicode before adding to Dictionary
38,749,676
<p>When parsing a page, I am pulling:</p> <pre><code>'label_value': [u'\n\t\t\t\t\t\t\t\t\t\tabc123\n\t\t\t\t\t\t\t\t\t']} </code></pre> <p>My goal is to just pull the relevant "abc123" from that xpath when it writes to the CSV. Currently, due to the "\n\t" in the string, it isn't writing anything. Looking around, I ...
3
2016-08-03T17:01:25Z
38,751,151
<p>Probably the best way is to trim the whitespaces. </p> <p>Something like do a global<br> Find <code>^\s+|\s+$</code><br> and replace with nothing. </p> <p>You mentioned stripping Unicode.<br> If you want to strip Unicode as well, use <code>^\s+|[\x{100}-\x{10ffff}]+|\s+$</code><br> Not sure what Python uses for...
0
2016-08-03T18:30:16Z
[ "python", "regex", "xpath" ]
Clean unicode before adding to Dictionary
38,749,676
<p>When parsing a page, I am pulling:</p> <pre><code>'label_value': [u'\n\t\t\t\t\t\t\t\t\t\tabc123\n\t\t\t\t\t\t\t\t\t']} </code></pre> <p>My goal is to just pull the relevant "abc123" from that xpath when it writes to the CSV. Currently, due to the "\n\t" in the string, it isn't writing anything. Looking around, I ...
3
2016-08-03T17:01:25Z
38,753,900
<p>I credit @Martjin for this solution... (I take credit for the comment)</p> <pre><code>#UNICODE is a pain in my ass! below is a function to strip-out and replace with a space. def remove_non_ascii(text): return ''.join([i if ord(i) &lt; 128 else ' ' for i in text]) </code></pre>
0
2016-08-03T21:25:01Z
[ "python", "regex", "xpath" ]
python no such element: unable to locate element {"method": "id","selector":"email"}
38,749,756
<p>having trouble with my python code. i keep getting python no such element: unable to locate element {"method": "id","selector":"email"}</p> <pre><code> self.driver.get(redirecturl) email = "testmail02015@gmail.com" Password = "Passw0rd123" emailFieldID = "email" passwordField...
-3
2016-08-03T17:06:48Z
38,750,001
<p>Usually the problem is that <code>find_element</code> runs too quickly before page fully loaded. So try to wait for elements to appear (in the example it waits for maximum of 10 seconds; less if element appears earlier):</p> <pre><code>... emailFieldID = "email" ... WebDriverWait(browser, 10).until(EC.presence_of_...
3
2016-08-03T17:19:50Z
[ "python", "selenium-webdriver" ]
sympy array of expressions to numpy array
38,749,771
<p>I got a sympy array</p> <pre><code>sympyarray = Matrix([[2/(dx**2*(exp(I*theta) + 1)), -2*exp(-I*theta)/dx**2, 2*exp(-I*theta)/(dx**2*(exp(I*theta) + 1))]]) </code></pre> <p>and want to transform it into a numpy array</p> <pre><code>numpyarray=np.array([2/(dx**2*(np.exp(1j*theta) + 1)), -2*np.exp(-1j*theta)/dx**2...
1
2016-08-03T17:07:45Z
38,775,519
<p>Use <code>lambdify</code>:</p> <pre><code>In [10]: expr = Matrix([[2/(dx**2*(exp(I*theta) + 1)), -2*exp(-I*theta)/dx**2, 2*exp(-I*theta)/(dx**2*(exp(I*theta) + 1))]]) In [12]: f = lambdify([dx, theta], expr, 'numpy') In [15]: f(np.array([1], dtype=complex), np.array([np.pi], dtype=complex)) Out[15]: array([[[ 0. ...
1
2016-08-04T19:10:54Z
[ "python", "arrays", "numpy", "sympy" ]
Pandas - DataFrame reindex function returns a warning
38,749,887
<p>Whats wrong with the code?: Its returning a warning :</p> <blockquote> <p>Warning (from warnings module): File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 2515 return bool(asarray(a1 == a2).all()) FutureWarning: elementwise comparison failed; returning scalar instead, but in the future w...
2
2016-08-03T17:13:58Z
38,751,503
<p>You must use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow"><code>rename</code></a> instead of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> as you are trying to change...
0
2016-08-03T18:51:12Z
[ "python", "pandas", "dataframe" ]
Pandas - DataFrame reindex function returns a warning
38,749,887
<p>Whats wrong with the code?: Its returning a warning :</p> <blockquote> <p>Warning (from warnings module): File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 2515 return bool(asarray(a1 == a2).all()) FutureWarning: elementwise comparison failed; returning scalar instead, but in the future w...
2
2016-08-03T17:13:58Z
38,751,823
<p>Try this: </p> <pre><code>Frame4 =pd.DataFrame(Data1) print('\n') print Frame4 Frame4.index = ['a','b','c','d','e'] print Frame4 POP State Year 0 1.5 Ohio 2000 1 1.7 Ohio 2001 2 3.6 Ohio 2002 3 2.4 Nevada 2001 4 2.9 Nevada 2002 POP State Year a 1.5 Ohio 2000 b 1.7 Ohio...
0
2016-08-03T19:09:43Z
[ "python", "pandas", "dataframe" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ...
-2
2016-08-03T17:14:24Z
38,750,004
<p>I'm not sure exactly what result is desired, but perhaps this?</p> <pre><code>&gt;&gt;&gt; matchObj = re.findall(r'~+(.*?)\^', target) &gt;&gt;&gt; print(matchObj) [' ABC '] </code></pre>
0
2016-08-03T17:19:53Z
[ "python" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ...
-2
2016-08-03T17:14:24Z
38,750,011
<p>Without regex:</p> <pre><code>&gt;&gt;&gt; "".join([x for x in target if x.isalpha() or x == ' ']).split() ['ABC', 'DEF', 'HGK', 'LMN'] </code></pre> <p>This takes space and alpha characters and creates a new string then splits it into words in a list</p> <p>Here is my exact code from python 3 command line:</p> ...
0
2016-08-03T17:20:15Z
[ "python" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ...
-2
2016-08-03T17:14:24Z
38,750,046
<p>Your idea of using a lazy quantifier is good, but that still doesn't necessarily give you the shortest possible match - only the shortest match from the current position of the regex engine. If you want to disallow the start/end separators from being part of the match, you need to explicitly exclude them from the li...
0
2016-08-03T17:22:22Z
[ "python" ]
Python-get string between to characters
38,749,896
<p>I need to one give me the string between <code>~</code> and <code>^</code>.<br> I have a string like this:</p> <pre><code>~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ </code></pre> <p>I need to get the string between them with python.<br> I've tried this:</p> <pre><code>import re target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ...
-2
2016-08-03T17:14:24Z
38,752,819
<p>here is my solution:</p> <p>your input:</p> <pre><code>In [12]: target = ' ~~~~ ABC ^ DEF ^ HGK &gt; LMN ^ ' </code></pre> <p>replace all the symbols or delimiters with <code>' '</code> and split the result</p> <pre><code>In [13]: b = re.sub(r'[^\w]', ' ', target).split() In [14]: b Out[14]: ['ABC', 'DEF', 'HG...
0
2016-08-03T20:14:27Z
[ "python" ]
Can't get data from Django View into template
38,749,924
<p>I'm trying to send some data for rendering a table in a template. The data is not a <code>QuerySet</code> or anything, it's a custom list of tuples that I get from a Django Rest Framework endpoint.</p> <p>I have the following view:</p> <pre><code>class GetPointsView(FormView): form_class = forms.GetPointsForm ...
0
2016-08-03T17:15:44Z
38,750,244
<p>The key in your rendering context is 'mydata', so you should use <code>{% if mydata %}</code>. Also you have an extra <code>}</code> at the end of that line.</p>
0
2016-08-03T17:33:32Z
[ "python", "django", "django-templates" ]
Inserting data into XML file with python
38,749,937
<p>I'm working with specific sets of data that I want to insert into an existing file in a fixed section. I want to alter the XML file from looking like this:</p> <pre><code>&lt;SBEDataUploadFile&gt; &lt;ApplicationData&gt; &lt;firmware&gt; &lt;SoftwareVersion&gt;1.0&lt;/SoftwareVersion&gt; ...
0
2016-08-03T17:16:27Z
38,750,196
<p>You don't need a <code>SubElement</code>. Just set the text node on the root element:</p> <pre><code>xml_root.text = toString </code></pre>
0
2016-08-03T17:31:18Z
[ "python", "xml", "parsing", "insert", "elementtree" ]
Calling a python script from a Java jar file
38,749,991
<p>I am working on a project using Java and Python using Java for the GUI and Python for the backend. The Java program calls a Python script when a button is pressed using the following code:</p> <pre><code>Runtime r = Runtime.getRuntime(); String pyScript = "resources/script.py"; String scriptPath = getClass().getRes...
0
2016-08-03T17:19:12Z
38,759,120
<p>In this solution, we run the script if the file exists. The script could be on a full or relative path. The script is not in the jar file.</p> <blockquote> <p>TestPython.java</p> </blockquote> <pre><code>import java.lang.*; import java.io.*; public class TestPython { public static void main(String[] args) {...
0
2016-08-04T05:30:34Z
[ "java", "python", "pywin32" ]
Selenium execute_script adding "AI" to function
38,750,116
<p>I've selected a search button:</p> <pre><code>&lt;input type="button" name="Submit" value="Submit" onclick="FnAddSearchParameters();" class="myButton rightButton buttonGroup"&gt; </code></pre> <p>Using the chrome driver, I've been trying to click the button, to no avail. The regular <code>button.click()</code> fu...
1
2016-08-03T17:26:41Z
38,753,863
<p>Actually you are executing wrong using <code>execute_script</code>, you should try as below :-</p> <pre><code>button = driver.find_element_by_name("Submit") driver.execute_script("arguments[0].click()", button) </code></pre>
1
2016-08-03T21:21:51Z
[ "javascript", "python", "selenium" ]
python add items to list and stop when you get an empty value
38,750,174
<p>I have an excel document that I am reading, it has an unknown number of lines, I want to add each line and the three values of columns A B and C into a list and then stop once I reach none. I then want to run an action on each item in the list.</p> <p>I am terrible with <code>if/for loops</code> if someone could he...
2
2016-08-03T17:29:41Z
38,751,980
<p><code>worksheet.rows</code> returns a list of all rows, no matter how many there are. Each row in that list is itself a list of the cells in that row. Knowing this, it would be fairly easy to implement a <code>for</code> loop that iterates through each row and appends the first three cells to a new list.</p> <p>Thi...
1
2016-08-03T19:19:19Z
[ "python", "python-3.x", "if-statement", "for-loop" ]
Function that defines a function in python
38,750,177
<p>I have a program that defines the function <code>verboseprint</code> to either print or not print to the screen based on a boolean:</p> <pre><code># define verboseprint based on whether we're running in verbose mode or not if in_verbose_mode: def verboseprint (*args): for arg in args: print ...
0
2016-08-03T17:29:50Z
38,750,404
<p>Usually you don't want define a function in this way.</p> <p>And I think the easy way to achieve this is you pass the boolean as a function parameter and define the behavior based on the parameter:</p> <pre><code>def verboseprint (*args, mode): if mode == in_verbose_mode: for arg in args: p...
3
2016-08-03T17:44:00Z
[ "python", "function", "definition", "function-declaration", "helper-functions" ]
Function that defines a function in python
38,750,177
<p>I have a program that defines the function <code>verboseprint</code> to either print or not print to the screen based on a boolean:</p> <pre><code># define verboseprint based on whether we're running in verbose mode or not if in_verbose_mode: def verboseprint (*args): for arg in args: print ...
0
2016-08-03T17:29:50Z
38,750,405
<p>You should look up the factory design pattern. It's basically designed to do exactly what you are talking about, though it would be with classes not functions. That being said, you can get the behavior that you want by having a class that returns one of two possible objects (based on your boolean). They both have...
3
2016-08-03T17:44:13Z
[ "python", "function", "definition", "function-declaration", "helper-functions" ]
python logging not displaying %(name)s format property as expected
38,750,178
<p>I have some ideas about what is going on but can't necessarily figure out how to fix it.</p> <p>I have an Abstract Base Class (ABC) that has an attribute of <code>logger = logging.getLogger(__name__)</code>. This happens in the <code>__init__</code></p> <p>I then have a concrete class that overwrites the attribut...
0
2016-08-03T17:29:55Z
38,750,574
<p>The way you are writing out your example code, it looks like the two classes are defined in the same file. Is that the case? Because <code>__name__</code> will give you the module name, which is essentially the file name. So in that case, the two should be the same</p> <p>Additional answer after it was verified tha...
1
2016-08-03T17:54:37Z
[ "python", "oop", "inheritance", "logging" ]
how to choose and upload a file in python
38,750,191
<p>I am writing a program where it asks you what text file the user wants to read then it begins to read whatever file name the user inputs. Here is what I have so far:</p> <pre><code>import sys import os import re #CHOOSE FILE print "Welcome to the Parsing Database" raw_input=raw_input("enter file name to parse: ") ...
-1
2016-08-03T17:30:50Z
38,750,259
<p>Off the top of my head, I think that <code>f = open("raw_input", "r")</code> needs to be <code>f=open(raw_input, "r")</code>, because you are trying to reference the string contained in the variable <code>raw_input</code>, as opposed to trying to open a file named raw_input. Also you should probably change the name ...
1
2016-08-03T17:34:37Z
[ "python", "python-2.7", "file", "import", "text-files" ]
how to choose and upload a file in python
38,750,191
<p>I am writing a program where it asks you what text file the user wants to read then it begins to read whatever file name the user inputs. Here is what I have so far:</p> <pre><code>import sys import os import re #CHOOSE FILE print "Welcome to the Parsing Database" raw_input=raw_input("enter file name to parse: ") ...
-1
2016-08-03T17:30:50Z
38,750,671
<p><code>f=open("raw_input", "r")</code></p> <p>"raw_input" is a plain string. You have to referente to it as <code>raw_input</code>.</p> <p>Also, there's no lines if you don't use <code>.read()</code> with <code>open()</code> method so you can't parse them. Read lines from a file given from <code>raw_input</code> ca...
0
2016-08-03T18:00:08Z
[ "python", "python-2.7", "file", "import", "text-files" ]
Counting Inversion for a large text file
38,750,193
<p>The objective of the code is to find out the total no. of inversions for an array. My code works successfully. Tested successfully for 6 elements (all elements in reverse order starting with the highest) with inversion count= 15. Also,tested successfully for 10 elements(all elements in reverse order starting with th...
0
2016-08-03T17:31:09Z
38,754,583
<p>I found it (and verified with profile)</p> <pre><code> #total_count+=len(left_half[i:]) total_count += len(left_half) - i </code></pre> <p>left_half[i:] creates a new list with a copy of several elements, many times, in the main loop of your recursive function. It was a clever use of splicing, but t...
1
2016-08-03T22:19:05Z
[ "python", "mergesort", "inversion" ]
Importing package installed with pip3 causes ImportError
38,750,206
<p>I installed the <strong>pillow 3.3.0</strong> package for Python 3.5.2 Mac by using the <strong>pip3 install statement</strong> in terminal, it successfully downloaded and installed. (I did the same for other pacakges.)</p> <p>When trying to call <em>import pillow</em>, following warning is displayed:</p> <pre><co...
0
2016-08-03T17:31:41Z
38,750,312
<p>The importable name of the Pillow library is <code>PIL</code> because it is a fork of the original PIL. Just do</p> <pre><code>from PIL import * </code></pre> <p>Or even better, only import those names you actually need—see this <a href="http://stackoverflow.com/questions/2386714/why-is-import-bad">SO thread</a>...
1
2016-08-03T17:37:57Z
[ "python", "python-3.x", "import", "package", "pillow" ]
Importing package installed with pip3 causes ImportError
38,750,206
<p>I installed the <strong>pillow 3.3.0</strong> package for Python 3.5.2 Mac by using the <strong>pip3 install statement</strong> in terminal, it successfully downloaded and installed. (I did the same for other pacakges.)</p> <p>When trying to call <em>import pillow</em>, following warning is displayed:</p> <pre><co...
0
2016-08-03T17:31:41Z
38,750,341
<p>the package name is PIL</p> <p>use </p> <pre><code>from PIL import * </code></pre>
0
2016-08-03T17:40:25Z
[ "python", "python-3.x", "import", "package", "pillow" ]
Cannot get an output Python Classes and Functions code
38,750,364
<p>I recently submitted this homework but couldn't get the code of either problems working. I would love to know what I could have done to make sure I do it right the next time.</p> <p><strong>Question 1</strong> (5 points) Create a base/parent class called 'InterestCalculator'. Create a child class called 'CICalcula...
-1
2016-08-03T17:41:42Z
38,751,180
<p>There are many errors in your code. Most of them being indent errors. I have only sorted the errors, the core algorithm you wanted to implement is unaltered. </p> <pre><code>class InterestCalculator: def __init__(self, p, r,t,n=1,A=0): self.A = A self.p = p self.r = r self.n = n self.t = t ...
-2
2016-08-03T18:31:54Z
[ "python", "python-2.7", "function", "class" ]
Cannot get an output Python Classes and Functions code
38,750,364
<p>I recently submitted this homework but couldn't get the code of either problems working. I would love to know what I could have done to make sure I do it right the next time.</p> <p><strong>Question 1</strong> (5 points) Create a base/parent class called 'InterestCalculator'. Create a child class called 'CICalcula...
-1
2016-08-03T17:41:42Z
38,751,415
<p>A way to implement Q1 in a similar way that you have implemented in Solution 1 is :</p> <pre><code>class InterestCalculator: def __init__(self,p, r, y, t): self.p = p self.r = r self.y = y self.t = t class CICalculator(InterestCalculator): def __init__(self,InterestCalculato...
-1
2016-08-03T18:46:06Z
[ "python", "python-2.7", "function", "class" ]
Emulating Behavior of Java String's Split Method in Python
38,750,387
<p>I am parsing sets of csv-type data into Python tuples by splitting the strings across a delimiting character. Very simple stuff.</p> <p>My issue is that any of the fields could potentially contain empty strings as valid data. This is fine, except if the very last field is a empty string, in which case the length of...
-1
2016-08-03T17:43:03Z
38,750,494
<p>I think python directly gives the correct output. Do you have any specific example where this is not the case? :</p> <pre><code>x = "5|6|7||8|9||" x.split("|") Out: ['5', '6', '7', '', '8', '9', '', ''] </code></pre>
0
2016-08-03T17:49:44Z
[ "python", "string", "split" ]
Using the hover tool with vbar glyphs
38,750,508
<h2>Question</h2> <p>Is it possible to use the hover tool with bokeh <code>vbar</code> glyphs?</p> <h2>Problem</h2> <p>Using the same basic setup, I can get great tool tips with the hover tool on <code>circle</code> glyphs, but not <code>vbar</code> glyphs</p> <h2>Demonstration</h2> <h3>Setup</h3> <pre><code>impo...
1
2016-08-03T17:50:20Z
38,751,463
<p><strong>UPDATE</strong>: This feature has been implemented and will be in <code>0.12.2</code></p> <p>Not yet, as of Bokeh <code>0.12.1</code>. Given the choice to add <code>vbar</code>/<code>hbar</code> without hit-testing support, or not add them at all, it was decided to be useful to the most number of users to m...
1
2016-08-03T18:49:26Z
[ "python", "bokeh" ]
pysnmp error on specific query
38,750,540
<p>I have been trying to implement code that loads my device MIBS and walks through all the OIDS. In this one case when I try to load the OID for snmp 1.3.6.1.2.1.11 smi throws an exception when trying to load a specific OID. The previous OID works successfully: '.1.3.6.1.2.1.11.29.0' but this one generates the error...
0
2016-08-03T17:52:23Z
38,937,615
<p>Your SNMP agent responded with <em>1.3.6.1.2.1.11.30.0=808466736</em> while OID 1.3.6.1.2.1.11.30.0 identifies MIB object <em>snmpEnableAuthenTraps</em> of type INTEGER with only two values permitted: 1 and 2.</p> <p>Here is formal definition from SNMPv2-MIB:</p> <pre><code>snmpEnableAuthenTraps OBJECT-TYPE SY...
0
2016-08-13T22:45:23Z
[ "python", "snmp", "pysnmp" ]
PySerial: TypeError: 'float' object is not iterable
38,750,542
<p>So I'm writing a program to adjust the speed of a rotating magnetic field. Basically, I'm just trying to send a float through the serial port to represent the user's intended speed. But I'm getting an error that doesn't really make sense. I've isolated the error in a much smaller portion of code.</p> <p>Code:</p> ...
0
2016-08-03T17:52:24Z
38,750,630
<p><code>serial.Serial.write()</code> expects to be passed in a <code>str</code> object, not a floating point value. A <code>str</code> object is iterable.</p> <p>From the <a href="http://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.write" rel="nofollow"><code>pyserial</code> documenation</a>:</p>...
1
2016-08-03T17:58:01Z
[ "python", "arduino", "iteration", "typeerror", "pyserial" ]
Killing a process on an open socket from another class
38,750,567
<p>Alright I have a program that opens a socket to a local port and starts processes, the code goes as follows:</p> <blockquote> <p>socket_opener.py</p> </blockquote> <pre><code>processes=[] Handler = CGIHTTPServer.CGIHTTPRequestHandler Handler.cgi_directories = ["/maps"] httpd = SocketServer.TCPServer(("", PORT), ...
0
2016-08-03T17:53:45Z
38,752,445
<p>The proximate cause here is that you're running all the code in <code>socket_opener</code> again by importing the module. That fails because there's already a socket bound to the port numbered <code>PORT</code> and you're attempting to bind another one. </p> <p>(As far as I can tell, you're adding <code>server_name...
1
2016-08-03T19:50:24Z
[ "python", "python-2.7", "sockets", "process" ]
django orm join three tables
38,750,667
<p>I have three models (A, B, C) and I need to join them like so:</p> <p>Model A fk1 to Model B pk1 and then Model B fk1 to Model C.</p> <p>It is joining tables but not joining them correctly. I can join model a to b but it won't let me pull fields from the last table (c) after the first join.</p> <p>Sample SQL that...
0
2016-08-03T17:59:55Z
38,751,018
<p><strong>Update</strong>: Question was edited, so this answer is not relevant anymore.</p> <pre><code>TableA.objects.filter(field2=var, b__isnull=False, b__c__isnull=True).values( 'field1', 'field2', 'b__char1', 'b__c__var1', 'b__c__var2', ) </code></pre> <ol> <li><code>b__isnull=False</code> is for <code>INNER...
0
2016-08-03T18:22:29Z
[ "python", "sql", "django", "join" ]
OpenCV Python copying certain portion of image to another
38,750,688
<p>I want to calculate the difference betwwn two images. I'm only interested in the difference value for a certain portion of image. For that i am copying the required portion of image to a temp images, and operating on those images. However using the pixel allocation using as specified on <a href="http://docs.opencv.o...
0
2016-08-03T18:01:10Z
38,753,881
<p>You are getting the error because your command is trying to slice the string 'carparking2_1.jpg' as if it were the image data.</p> <pre><code>#First assign the file names: file_name_without_car='carparking2_1.jpg' file_name_with_car='carparking2.jpg' #load the images img_withoutcar= cv2.imread(file_name_without_ca...
0
2016-08-03T21:23:18Z
[ "python", "image", "opencv" ]
How can I print multiple lines, having subsequent lines replacing each of them independently (Python)
38,750,727
<p>I am running a program that works in parallel, utilizing the <code>Pool</code> object from the multiprocessing module.</p> <p>What I am trying to do is run a function n number of times in parallel, each having a separate loading %, and I would like it to be updating the percentage for each function without replacin...
0
2016-08-03T18:03:47Z
38,751,532
<h1>Curses</h1> <p>As @Keozon mentioned in the comments, one way to achieve this would be to use the <a href="https://docs.python.org/3/library/curses.html" rel="nofollow">curses</a> library.</p> <p>There is a <a href="https://docs.python.org/3/howto/curses.html" rel="nofollow">good guide for curses</a> on the python...
0
2016-08-03T18:52:53Z
[ "python", "printing", "parallel-processing", "percentage", "lines" ]
Trying to transfer 5009 rows from csv file to xlsx
38,750,729
<pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2['Location']=df1['Location'] df2['Sublocation']=df1['Sublocation'] df2['Zone']=df1['Zone'] df2['Subnet Type']=df1['Subnet Type'] df2['Description']=df1['Description'] newfile = input("Enter a name for the combined xlsx fil...
0
2016-08-03T18:04:05Z
38,750,991
<p>I think you should append data</p> <pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2.append(df1) newfile = input("Enter a name for the combined xlsx file: ") print('Saving to new xlsx file...') writer = pd.ExcelWriter(newfile) df2.to_excel(writer, index=False) writer...
0
2016-08-03T18:21:02Z
[ "python", "python-3.x", "csv", "pandas", "xls" ]
Trying to transfer 5009 rows from csv file to xlsx
38,750,729
<pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2['Location']=df1['Location'] df2['Sublocation']=df1['Sublocation'] df2['Zone']=df1['Zone'] df2['Subnet Type']=df1['Subnet Type'] df2['Description']=df1['Description'] newfile = input("Enter a name for the combined xlsx fil...
0
2016-08-03T18:04:05Z
38,752,996
<p>I am little confused about the problem, so i came up with 2 options 1. append df1 to df2 2. Merge df1 to df2 (adds new columns to existing df) . I think in your case you dont have same number of rows in csv and excel and for that reason last 10 rows dont have value in the output</p> <pre><code>import numpy as np i...
1
2016-08-03T20:25:17Z
[ "python", "python-3.x", "csv", "pandas", "xls" ]
Trying to transfer 5009 rows from csv file to xlsx
38,750,729
<pre><code>import pandas as pd df1=pd.read_csv('out.csv') df2=pd.read_excel('file.xls') df2['Location']=df1['Location'] df2['Sublocation']=df1['Sublocation'] df2['Zone']=df1['Zone'] df2['Subnet Type']=df1['Subnet Type'] df2['Description']=df1['Description'] newfile = input("Enter a name for the combined xlsx fil...
0
2016-08-03T18:04:05Z
38,773,531
<p>Most likely there is a way to do what you want within <code>pandas</code>, but in case there isn't, you can use lower-level packages to accomplish your task.</p> <p>To read the CSV file, use the <code>csv</code> module that comes with Python. The following code loads all the data into a Python list, where each elem...
1
2016-08-04T17:09:41Z
[ "python", "python-3.x", "csv", "pandas", "xls" ]
Filtering itertools combinations for dynamic number of constraints
38,750,858
<p>I have python program and function that returns a series of rows from my MySQL database. These returned rows are filtered by a set of IDs contained in a tuple, I then use itertools and list comprehension to form 'combinations' that conform to a fixed set of constraints (the attributes of each combination must be eit...
0
2016-08-03T18:12:12Z
38,751,054
<p>As Martijn stated in the comment, you may look at doing the filtering in SQL, which is bound to be probably more efficient. If the filtering must be done in Python, the <em>"all equal" or "all different"</em> check could easily be done with a set comprehension:</p> <pre><code>length = len(tuple_of_ids) valid_combin...
1
2016-08-03T18:23:59Z
[ "python", "python-2.7" ]
Filtering itertools combinations for dynamic number of constraints
38,750,858
<p>I have python program and function that returns a series of rows from my MySQL database. These returned rows are filtered by a set of IDs contained in a tuple, I then use itertools and list comprehension to form 'combinations' that conform to a fixed set of constraints (the attributes of each combination must be eit...
0
2016-08-03T18:12:12Z
38,751,363
<p>I think that passing functions by reference is a pretty pythonic way of easily adding or removing constraints from your code. This is a contrived example:</p> <pre><code>#Just an example class class Person(object): __slots__ = ["age","height","weight"] def __init__(self,age,height,weight): self.age ...
0
2016-08-03T18:42:42Z
[ "python", "python-2.7" ]
Python : While threading why does the conditional statement work differently?
38,750,970
<p>I was trying to write a simple function and call it from a thread for different values. The function worked perfectly when called normally. But as soon as we call it from a thread the conditional statements inside the function do not work.</p> <pre><code>def func(count): print "In func count = {0}".format(count...
0
2016-08-03T18:19:42Z
38,751,042
<p>You passed the index as a string to the function, but you are checking for equality with an integer.</p> <p>Also, doing <code>int(index)</code> is redundant. It's already an int.</p> <p>You can check this by doing <code>print type(count)</code></p> <p>Edit: Here's an example of what you're doing.</p> <pre><code>...
2
2016-08-03T18:23:21Z
[ "python", "multithreading", "conditional" ]
No module named 'django.core.context_processors', in views.py
38,751,005
<p>In my django app, When I run server I am getting the error.</p> <p>from . import views from django.core.context_processors import csrf ImportError: No module named 'django.core.context_processors'</p> <p>My views.py file is </p> <pre><code> from django.views.generic import View from django.utils import timezone...
1
2016-08-03T18:21:56Z
38,751,259
<p>Try to change this import to <code>from django.template.context_processors import csrf</code>. Your current import seems to be depreciated (via <a href="https://docs.djangoproject.com/en/1.9/releases/1.8/#django-core-context-processors" rel="nofollow">https://docs.djangoproject.com/en/1.9/releases/1.8/#django-core-c...
0
2016-08-03T18:36:20Z
[ "python", "django" ]
No module named 'django.core.context_processors', in views.py
38,751,005
<p>In my django app, When I run server I am getting the error.</p> <p>from . import views from django.core.context_processors import csrf ImportError: No module named 'django.core.context_processors'</p> <p>My views.py file is </p> <pre><code> from django.views.generic import View from django.utils import timezone...
1
2016-08-03T18:21:56Z
38,752,901
<p>First, remove the invalid import that is causing the error</p> <pre><code>from django.core.context_processors import csrf </code></pre> <p>Next, the <code>render_to_response</code> shortcut is obsolete, you should use <code>render</code> instead. For example:</p> <pre><code>from django.shortcuts import render de...
0
2016-08-03T20:19:24Z
[ "python", "django" ]
Sharing data with multiple python programms
38,751,024
<p>i am scraping data through multiple websites. To do that i have written multiple web scrapers with using selenium and PhantomJs.</p> <p>Those scrapers return values.</p> <p>My question is: is there a way i can feed those values to a single python program that will sort through that data in real time.</p> <p>What ...
0
2016-08-03T18:22:51Z
38,751,112
<p>You can try writing the data you want to share to a file and have the other script read and interpret it. Have the other script run in a loop to check if there is a new file or the file has been changed.</p>
-1
2016-08-03T18:27:27Z
[ "python", "osx", "os.system" ]
Sharing data with multiple python programms
38,751,024
<p>i am scraping data through multiple websites. To do that i have written multiple web scrapers with using selenium and PhantomJs.</p> <p>Those scrapers return values.</p> <p>My question is: is there a way i can feed those values to a single python program that will sort through that data in real time.</p> <p>What ...
0
2016-08-03T18:22:51Z
38,751,162
<p>Simply use files for data exchange and a trivial locking mechanism. Each writer or reader (only one reader, it seems) gets a unique number. If a writer or reader wants to write to the file, it renames it to its original name + the number and then writes or reads, renaming it back after that. The others wait until th...
-1
2016-08-03T18:31:00Z
[ "python", "osx", "os.system" ]
Sharing data with multiple python programms
38,751,024
<p>i am scraping data through multiple websites. To do that i have written multiple web scrapers with using selenium and PhantomJs.</p> <p>Those scrapers return values.</p> <p>My question is: is there a way i can feed those values to a single python program that will sort through that data in real time.</p> <p>What ...
0
2016-08-03T18:22:51Z
38,751,225
<p>Perhaps a <a href="http://linux.die.net/man/3/mkfifo" rel="nofollow">named pipe</a> would be suitable:</p> <p><code>mkfifo whatever</code> (you can also do this from within your python script; <a href="https://docs.python.org/2/library/os.html#os.mkfifo" rel="nofollow">os.mkfifo</a>)</p> <p>You can write to <code>...
0
2016-08-03T18:34:39Z
[ "python", "osx", "os.system" ]
lxml HtmlElement xpath parses more than it should be able to
38,751,203
<p>Trying to parse HTML, I fail to loop through all <code>li</code> elements:</p> <pre><code>from lxml import html page="&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;" tree = html.fromstring(page) for item in tree.xpath("//li"): print(html.tostring(item)) print(item.xpath("//li/text()")) ...
0
2016-08-03T18:33:05Z
38,751,250
<p><code>item.xpath("//li/text()")</code> would search for all <code>li</code> elements in the entire tree. Since you want the text of the current node, you can just get the <code>text()</code>: <code>item.xpath("text()")</code>.</p> <p>Or, even better, just get the <a href="http://lxml.de/lxmlhtml.html#html-element-m...
1
2016-08-03T18:35:44Z
[ "python", "xpath", "lxml" ]
lxml HtmlElement xpath parses more than it should be able to
38,751,203
<p>Trying to parse HTML, I fail to loop through all <code>li</code> elements:</p> <pre><code>from lxml import html page="&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;" tree = html.fromstring(page) for item in tree.xpath("//li"): print(html.tostring(item)) print(item.xpath("//li/text()")) ...
0
2016-08-03T18:33:05Z
38,751,517
<p>From <a href="http://stackoverflow.com/questions/1725268/lxml-html-xpath-context">Lxml html xpath context</a>:</p> <blockquote> <p>XPath expression <code>//input</code> will match all input elements, anywhere in your document, while <code>.//input</code> will match all inside current context.</p> </blockquote> <...
1
2016-08-03T18:52:05Z
[ "python", "xpath", "lxml" ]
Slicing a date range that includes time
38,751,223
<p>I have a dataframe which contains a column <code>Date</code> &amp; <code>Time</code>, with each row containing an entry in the format: <code>MM/DD/YYYY HH:MM:SS</code></p> <p>I would like to be able to slice the dataframe based on only a date range, say for instance: <code>5/01/2016 to 5/30/2016</code>.</p> <p>A...
0
2016-08-03T18:34:38Z
38,751,400
<p>for variables sdate and edate </p> <pre><code>frame = [] record = 0 for date,time in my_list: if date == sdate or record == 1: frame.append([date,time]) record = 1 if date == edate: break; print (frame) </code></pre>
0
2016-08-03T18:45:25Z
[ "python", "pandas" ]
Slicing a date range that includes time
38,751,223
<p>I have a dataframe which contains a column <code>Date</code> &amp; <code>Time</code>, with each row containing an entry in the format: <code>MM/DD/YYYY HH:MM:SS</code></p> <p>I would like to be able to slice the dataframe based on only a date range, say for instance: <code>5/01/2016 to 5/30/2016</code>.</p> <p>A...
0
2016-08-03T18:34:38Z
38,752,563
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> to select the subset of the dataframe for which the condition (<em>interval between dates</em>) is satisfied:</p> <p><strong>Data Preparation</strong></p> <pre><code>In [13]: ...
0
2016-08-03T19:58:44Z
[ "python", "pandas" ]
Can py2exe keep a py file as configure script?
38,751,240
<p>I want to distribute a python program as an executable file. I use py2exe with <code>options = {"py2exe":{"bundle_files": 1}}</code>. But I want to keep a py file as configure script ( including not just variables but also functions and classes ).</p> <p>Can py2exe do this? Or any other way to do it?</p>
0
2016-08-03T18:35:13Z
38,751,432
<p>It can if you exec () the contents of the .py file.</p>
0
2016-08-03T18:47:28Z
[ "python", "py2exe" ]
group and output on partial column value pandas python
38,751,299
<p>I have a sample data set:</p> <pre><code>import pandas as pd import re df = {'READID': [1,2,3 ,4,5 ,6,7 ,8,9], 'VG': ['LV5-F*01','LV5-F*01' ,'LV5-A*02','LV5-D*01','LV5-E*01','LV5-C*01','LV5-D*01','LV5-E*01','LV5-F*01'], 'Pro': [1,1,1,0.33,0.59,1,0.96,1,1]} df = pd.DataFrame(df) </code></pre> <p>it lo...
0
2016-08-03T18:38:48Z
38,751,428
<p>You'll have to adjust the function below <code>to_csv</code> to suit your needs. In particular, instead of printing, just provide a file name somehow.</p> <p>But I'd structure it this way:</p> <pre><code>def to_csv(df): print df.to_csv() # extract # within # parens # /------\ # r'^([^\*]+)' # ...
1
2016-08-03T18:47:21Z
[ "python", "pandas" ]
group and output on partial column value pandas python
38,751,299
<p>I have a sample data set:</p> <pre><code>import pandas as pd import re df = {'READID': [1,2,3 ,4,5 ,6,7 ,8,9], 'VG': ['LV5-F*01','LV5-F*01' ,'LV5-A*02','LV5-D*01','LV5-E*01','LV5-C*01','LV5-D*01','LV5-E*01','LV5-F*01'], 'Pro': [1,1,1,0.33,0.59,1,0.96,1,1]} df = pd.DataFrame(df) </code></pre> <p>it lo...
0
2016-08-03T18:38:48Z
38,751,759
<p>I modified my code with help from @piRSquared and it worked :</p> <pre><code>df.groupby(df.VG.str.extract(r'^([^\*]+)')).apply(lambda gp: gp.to_csv('{}.txt'.format(gp.name), sep='\t', index=False)) </code></pre>
0
2016-08-03T19:05:43Z
[ "python", "pandas" ]
Django rendering display name of choice field in form
38,751,300
<p>tl;dr: How do I make a form output the ‘nice’ name of the choices in a model?</p> <p>I have a Django model with choices, defined like this:</p> <pre><code>class City(models.Model): AMSTERDAM = 'AMS' ROTTERDAM = 'ROT' THE_HAGUE = 'THE' UTRECHT = 'UTR' CITY_CHOICES = ( (AMSTERDAM, 'Am...
1
2016-08-03T18:38:53Z
38,751,737
<p>In your line <code>'city': forms.RadioSelect(),</code>, you need to define the choices for it. It should look like:</p> <pre><code>from blah.models import City class ArticleForm(ModelForm): class Meta: model = Article fields = ['title', 'text', 'categories', 'city'] widgets = {'title': ...
1
2016-08-03T19:04:47Z
[ "python", "django", "django-forms", "jinja2" ]
Django rendering display name of choice field in form
38,751,300
<p>tl;dr: How do I make a form output the ‘nice’ name of the choices in a model?</p> <p>I have a Django model with choices, defined like this:</p> <pre><code>class City(models.Model): AMSTERDAM = 'AMS' ROTTERDAM = 'ROT' THE_HAGUE = 'THE' UTRECHT = 'UTR' CITY_CHOICES = ( (AMSTERDAM, 'Am...
1
2016-08-03T18:38:53Z
38,805,327
<p>I got the <a href="https://www.reddit.com/r/django/comments/4w051c/how_to_render_display_name_for_choice_field_in/d641ose" rel="nofollow">following answer</a> from reddit user roambe:</p> <p>Since city is a foreign key, Django will use the __str__ (or __unicode__) method of the City model for the choice label. This...
0
2016-08-06T14:27:15Z
[ "python", "django", "django-forms", "jinja2" ]
Microsoft Emotion API for video with Python
38,751,315
<p>I'm using the following code to send my video and apparently I got no error. But the response is coming blank. How can I read the response?</p> <pre><code>########### Python 2.7 ############# import httplib, urllib, base64, json headers = { # Request headers 'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxxxxxxxx...
0
2016-08-03T18:39:46Z
38,753,882
<p>The Cognitive Service Video APIs, including Emotion, operate asynchronously, and by design return an empty response body when the POST succeeds. What you must do instead is retrieve the operation URL from the headers, as shown here:</p> <pre><code>response = conn.getresponse() location = response.getheader('operat...
1
2016-08-03T21:23:31Z
[ "python", "azure", "microsoft-cognitive" ]
Microsoft Emotion API for video with Python
38,751,315
<p>I'm using the following code to send my video and apparently I got no error. But the response is coming blank. How can I read the response?</p> <pre><code>########### Python 2.7 ############# import httplib, urllib, base64, json headers = { # Request headers 'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxxxxxxxx...
0
2016-08-03T18:39:46Z
38,790,995
<p>@FelipeSouzaLima, To getting the operation result from Emotion Recognition in Video, you need to do two steps as below.</p> <ol> <li><p>Call the REST API for <a href="https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/56f8d40e1984551ec0a0984e" rel="nofollow">Emotion Recognition in Video<...
0
2016-08-05T13:53:30Z
[ "python", "azure", "microsoft-cognitive" ]
MiniBatchKMeans gives different centroids after subsequent iterations
38,751,364
<p>I am using the <code>MiniBatchKMeans</code> model from the <code>sklearn.cluster</code> module in anaconda. I am clustering a data-set that contains approximately 75,000 points. It looks something like this:</p> <p><code>data = np.array([8,3,1,17,5,21,1,7,1,26,323,16,2334,4,2,67,30,2936,2,16,12,28,1,4,190...])</cod...
0
2016-08-03T18:42:47Z
38,751,473
<p>The behavior you are experiencing probably has to do with the under the hood implementation of k-means clustering that you are using. k-means clustering is an NP-hard problem, so all the implementations out there are heuristic methods. What this means practically is that for a given seed, it will converge toward a l...
0
2016-08-03T18:49:52Z
[ "python", "statistics", "scikit-learn", "cluster-analysis", "k-means" ]
MiniBatchKMeans gives different centroids after subsequent iterations
38,751,364
<p>I am using the <code>MiniBatchKMeans</code> model from the <code>sklearn.cluster</code> module in anaconda. I am clustering a data-set that contains approximately 75,000 points. It looks something like this:</p> <p><code>data = np.array([8,3,1,17,5,21,1,7,1,26,323,16,2334,4,2,67,30,2936,2,16,12,28,1,4,190...])</cod...
0
2016-08-03T18:42:47Z
38,754,035
<p>Read up on what mini-batch k-means is.</p> <p>It will never even <em>converge</em>. Do one more iteration, the result will change <em>again</em>.</p> <p>It is design for data sets so huge you cannot load them into memory at once. So you load a batch, pretend this were the full data set, do one iterarion. Repeat wo...
0
2016-08-03T21:36:12Z
[ "python", "statistics", "scikit-learn", "cluster-analysis", "k-means" ]
Retrive a column in pandas
38,751,369
<pre><code>print(pd.read_excel(File,Sheet_Name,0,None,0,None,["Column_Name"],1)) </code></pre> <p>Since i am a noob to pandas i want to retrive a column of ExcelSheet using pandas in the form of array. I tried the code above but it didn't really work. </p>
0
2016-08-03T18:42:58Z
38,751,524
<p>The way to do it is:</p> <pre><code>import pandas as pd df = pd.read_excel(File,sheetname=Sheet_Name) print(df['column_name']) </code></pre>
2
2016-08-03T18:52:24Z
[ "python", "pandas", "machine-learning", "analytics" ]
Iotivity scons build error
38,751,482
<p>This is my build environment</p> <ul> <li>OS:OS X El Capitan 10.11.5</li> <li>Android SDK build-tool : 24.0.1</li> <li>Android NDK : 12</li> <li>Scons version : 2.5.0</li> </ul> <p>This is build command</p> <ul> <li>SCons TARGET_OS=android TARGET_ARCH=armeabi-v7a TARGET_TRANSPORT=ALL RELEASE=1 SECURED=0 ANDROID_H...
0
2016-08-03T18:50:20Z
38,822,955
<p>Looks like a typo - please confirm. SCons command is not found. Maybe use 'scons' ?</p>
0
2016-08-08T06:57:05Z
[ "android", "python", "scons", "iotivity" ]
How to avoid defunct python processes in Linux?
38,751,498
<p>With python3 (3.4.3) on Ubuntu 14.04 I have created a <code>Forker</code> class which I use in two different processes to create child processes. Here is the <code>Forker</code> class:</p> <pre><code>class Forker(object): def __init__(self): self.active_children = [] def reap_child...
0
2016-08-03T18:51:01Z
38,897,057
<p>Children which exited are <code>&lt;defunct&gt;</code> until the parent waits for them. Since you are calling <em>wait</em> in <code>reap_children()</code> only when you <code>fork()</code> a new child, the exited children stay <code>&lt;defunct&gt;</code> until the next child is forked. To get rid of them earlier, ...
1
2016-08-11T12:57:06Z
[ "python", "linux", "python-3.x" ]
How to avoid defunct python processes in Linux?
38,751,498
<p>With python3 (3.4.3) on Ubuntu 14.04 I have created a <code>Forker</code> class which I use in two different processes to create child processes. Here is the <code>Forker</code> class:</p> <pre><code>class Forker(object): def __init__(self): self.active_children = [] def reap_child...
0
2016-08-03T18:51:01Z
38,897,577
<p>Process marked as <code>&lt;defunct&gt;</code> are called zombie processes. The system keeps them in that defunct state to allow their parent to read their status after they have finished running.</p> <p>There are two ways to remove them:</p> <ul> <li>wait for them in the caller <em>shortly</em> after they have fi...
1
2016-08-11T13:19:58Z
[ "python", "linux", "python-3.x" ]
Why doesn't except object catch everything in Python?
38,751,530
<p>The python language reference states in <a href="https://docs.python.org/2.7/reference/compound_stmts.html#the-try-statement" rel="nofollow">section 7.4</a>: </p> <blockquote> <p>For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is ...
13
2016-08-03T18:52:50Z
38,752,183
<p>I believe the answer can be found in the <a href="https://github.com/tadhgmister/cpython/blob/2.7/Python/ceval.c#L4841" rel="nofollow">source code for python 2.7</a>:</p> <pre><code> else if (Py_Py3kWarningFlag &amp;&amp; !PyTuple_Check(w) &amp;&amp; !Py3kExceptionClass_Che...
3
2016-08-03T19:32:45Z
[ "python", "exception", "python-2.x", "python-internals" ]
How to Access Spark PipelineModel Parameters
38,751,536
<p>I am running a linear regression using <a href="https://spark.apache.org/docs/latest/ml-pipeline.html#ml-pipelines" rel="nofollow">Spark Pipelines</a> in pyspark. Once the linear regression model is trained, how do I get the coefficients out?</p> <p>Here is my pipeline code:</p> <pre><code># Get all of our featur...
2
2016-08-03T18:52:58Z
38,752,234
<p>You looking at the wrong property. <code>params</code> can be used to extract <code>Estimator</code> or <code>Transformer</code> <code>Params</code> like input or output columns (see <a href="https://spark.apache.org/docs/latest/ml-pipeline.html#parameters" rel="nofollow">ML Pipeline parameters docs</a> and not esti...
1
2016-08-03T19:35:58Z
[ "python", "apache-spark", "pyspark", "pyspark-sql", "apache-spark-ml" ]
Python 3 Tkinter notebook tabid. How to return the text of all tabs instead of the number ids?
38,751,559
<p>Hey guys I've been learning about Tkinter and making some GUI apps. I'm experimenting with the notebook widget and I'm stuck at one spot. I was wondering if there is a way to use a for loop for all of the current tabs and return the text names of all the tabs instead of the number id. I would like to use it to keep ...
-1
2016-08-03T18:54:01Z
38,753,930
<p>According to the official documentation, the <a href="https://docs.python.org/3.5/library/tkinter.ttk.html#tkinter.ttk.Notebook.tab" rel="nofollow">tab</a> method of the notebook can be used to return information about a tab, such as the text on the tab.</p> <p>Thus, you can get a list of the text for all of the ta...
1
2016-08-03T21:26:57Z
[ "python", "python-3.x", "tkinter" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> ...
-1
2016-08-03T18:55:09Z
38,751,679
<p>you can retrieve elements by the order you specified</p> <pre><code>for k in sorted(My_dic, key=My_criteria.index): print(k,":",My_dic.get(k)) </code></pre>
2
2016-08-03T19:01:27Z
[ "python", "python-2.7", "python-3.x" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> ...
-1
2016-08-03T18:55:09Z
38,751,685
<p>Dictionaries are not sortable, due to the way the information is stored (<a href="http://www.python-course.eu/dictionaries.php" rel="nofollow">http://www.python-course.eu/dictionaries.php</a>).</p> <p>You could create a new list of tuple values using list comprehension, like:</p> <p><code>ordered_info = [(i,my_dic...
0
2016-08-03T19:01:51Z
[ "python", "python-2.7", "python-3.x" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> ...
-1
2016-08-03T18:55:09Z
38,751,831
<p>You could use an OrderedDict:</p> <pre><code>from collections import OrderedDict My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} My_criteria = ['gender', 'age', 'car', 'name'] My_dic = OrderedDict([(x, My_dic[x]) for x in My_criteria]) # OrderedDict([('gender', 'male'), # ('age'...
1
2016-08-03T19:10:13Z
[ "python", "python-2.7", "python-3.x" ]
Retrieve dictionary items according to a list or priority keys
38,751,577
<p>I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:</p> <pre><code>My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'} </code></pre> <p>And the list of criteria is:</p> <pre><code>My_criteria = ['gender', 'age', 'car', 'name'] </code></pre> ...
-1
2016-08-03T18:55:09Z
38,751,916
<p>Just iterate through your priority keys, not your dict, then get values using those keys:</p> <pre><code>for key in My_criteria: print My_dic[key] </code></pre> <p>will print the values of your keys in the order that <code>My_criteria</code> is in.</p>
0
2016-08-03T19:15:40Z
[ "python", "python-2.7", "python-3.x" ]