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
Send client requests to broker only when a worker is available and broker is available
38,817,889
<p>With <strong><code>ZeroMQ</code></strong> for distributed messaging, I'm using the example code provided for the paranoid pirate pattern in python. I have a single <strong>client</strong> (potentially may have more clients) a <strong>broker</strong> and multiple <strong>workers</strong>.</p> <p>I have modified the...
0
2016-08-07T19:46:33Z
38,831,699
<h2>A: add a HeartBeat signalling to the Control Layer</h2> <p><strong>If there is the only</strong></p> <blockquote> <p><em>(cit.:)</em> "<strong>problem</strong> I'm seeing is that when the <strong>broker goes down</strong> (becomes unavailable), the client is unable to tell that the broker is unavailable and it ...
0
2016-08-08T14:20:28Z
[ "python", "zeromq", "pyzmq" ]
Python Tools for Visual Studio - tell the IDE what type a parameter will be
38,817,895
<p>I just started using Visual Studio 2015, and I really like it, especially the code completion features. Right now I'm writing some simple Python code to draw an object on a Tkinter Canvas:</p> <pre><code> def draw(self, can): """ can is a Tkinter canvas on which this node will draw itself. """ c...
2
2016-08-07T19:47:15Z
38,883,783
<p>Yes, you can use an assertion statement. This will trigger VS autocomplete settings. It's not the most beautiful way to do it, but I think right now that's the best option. </p> <pre><code>assert isinstance(can, tkinter.Canvas) </code></pre> <p>Take a look at <a href="http://stackoverflow.com/questions/36602807...
1
2016-08-10T21:21:24Z
[ "python", "visual-studio", "code-completion" ]
Python Tools for Visual Studio - tell the IDE what type a parameter will be
38,817,895
<p>I just started using Visual Studio 2015, and I really like it, especially the code completion features. Right now I'm writing some simple Python code to draw an object on a Tkinter Canvas:</p> <pre><code> def draw(self, can): """ can is a Tkinter canvas on which this node will draw itself. """ c...
2
2016-08-07T19:47:15Z
38,906,235
<p>I'm going to preface this by saying I haven't used Python Tools for Visual Studio (although I use Visual Studio for C# and it's a great IDE) and so this isn't a direct answer for your question. However, I'm guessing from "I just started using Visual Studio 2015" that you might be checking out different tools, so may...
1
2016-08-11T21:11:21Z
[ "python", "visual-studio", "code-completion" ]
Python shared read memory
38,817,914
<p>I'm working with a data set that is ~ 8GB big and I'm also using scikit-learn to train various ML models on it. The data set is basically a list of 1D vectors of ints. </p> <p>How can I make the data set available to multiple python processes or how can I encode the data set so I can make it use <code>multiprocessi...
5
2016-08-07T19:49:21Z
38,837,870
<p>Might be duplicate of <a href="https://stackoverflow.com/questions/17785275/share-large-read-only-numpy-array-between-multiprocessing-processes">Share Large, Read-Only Numpy Array Between Multiprocessing Processes</a></p> <p>You could convert your dataset from current representation to new numpy memmap object, and ...
1
2016-08-08T20:22:16Z
[ "python", "python-2.7", "scikit-learn", "ctypes", "python-multiprocessing" ]
Python shared read memory
38,817,914
<p>I'm working with a data set that is ~ 8GB big and I'm also using scikit-learn to train various ML models on it. The data set is basically a list of 1D vectors of ints. </p> <p>How can I make the data set available to multiple python processes or how can I encode the data set so I can make it use <code>multiprocessi...
5
2016-08-07T19:49:21Z
38,838,264
<p>I am assuming you are able to load the whole dataset into RAM in a numpy array, and that you are working on Linux or a Mac. (If you are on Windows or you can't fit the array into RAM, then you should probably copy the array to a file on disk and use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy...
2
2016-08-08T20:49:13Z
[ "python", "python-2.7", "scikit-learn", "ctypes", "python-multiprocessing" ]
Python Dependency Injection for Lazy Callables
38,817,923
<p>In programming for fun, I've noticed that managing dependencies feels like a boring chore that I want to minimize. <a href="http://code.activestate.com/recipes/413268-dependency-injection-the-python-way/" rel="nofollow">After reading this</a>, I've come up with a super trivial dependency injector, whereby the depend...
1
2016-08-07T19:50:42Z
38,819,044
<blockquote> <p>I've noticed that managing dependencies feels like a boring chore that I want to minimize. </p> </blockquote> <p>First of all, you shouldn't assume that dependency injection is a means to minimize the chore of dependency management. It doesn't go away, it is just deferred to another place and time an...
1
2016-08-07T22:12:40Z
[ "python", "dependency-injection", "lazy-evaluation" ]
Field names from dtype listing?
38,817,932
<p>I'm using code from <a href="http://stackoverflow.com/questions/7008608/scipy-io-loadmat-nested-structures-i-e-dictionaries">scipy.io.loadmat nested structures (i.e. dictionaries)</a> to read a matlab structure into Python. I want to make a list of names of fields that appear in the dtype listing. My code is:</p> ...
0
2016-08-07T19:51:43Z
38,817,957
<p>Just use a list comprehension and pick up the first item from each tuple, in each iteration:</p> <pre><code>thisList = [item[0] for item in dtype] </code></pre> <p>Or as a functional approach use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip()</code></a>:</p> <pre><code>t...
0
2016-08-07T19:55:22Z
[ "python", "matlab", "numpy", "scipy" ]
Field names from dtype listing?
38,817,932
<p>I'm using code from <a href="http://stackoverflow.com/questions/7008608/scipy-io-loadmat-nested-structures-i-e-dictionaries">scipy.io.loadmat nested structures (i.e. dictionaries)</a> to read a matlab structure into Python. I want to make a list of names of fields that appear in the dtype listing. My code is:</p> ...
0
2016-08-07T19:51:43Z
38,819,062
<pre><code>In [168]: dt=np.dtype([ ( 'Aircraft_Name', 'O'), ('Low_Mass', 'O') ]) In [169]: dt Out[169]: dtype([('Aircraft_Name', 'O'), ('Low_Mass', 'O')]) In [170]: dt.names Out[170]: ('Aircraft_Name', 'Low_Mass') </code></pre> <p>This tuple is handy for setting, or fetching, all fields, one by one:</p> <pre><code>In...
0
2016-08-07T22:16:41Z
[ "python", "matlab", "numpy", "scipy" ]
Python: reading ID3v1 tag with Kaitai Struct
38,817,956
<p>I'm trying to get Kaitai Struct to parse a ID3v1 tag format for MP3s. According to the <a href="http://id3.org/ID3v1" rel="nofollow">standard</a>, it is a fixed format structure located at the certain offset - but the trick is that this offset is calculated not from the beginning of the file, but from the end.</p> ...
3
2016-08-07T19:55:21Z
38,827,362
<p>There's a new feature in upcoming v0.4 of Kaitai Struct that addresses exactly this issue. You can use <code>_io</code> to get current stream object and then you can use <code>.size</code> to get full length of current stream in bytes. Thus, if you'd want to address some structure by a fixed offset from the end of t...
1
2016-08-08T10:54:36Z
[ "python", "id3", "kaitai-struct" ]
Using Python to change the date on an xml document
38,817,961
<p>I have an xml in this form</p> <pre><code>&lt;project name="Hello World"&gt; &lt;testfile name="testfile1"&gt; &lt;type&gt;TXT&lt;/type&gt; &lt;size&gt;1000&lt;/size&gt; &lt;lastModified&gt;2014-08-03 03:40:00&lt;/lastModified&gt; &lt;/testfile&gt; ...
0
2016-08-07T19:55:37Z
38,818,409
<p>Your definition of <code>self.getMetadataTree()</code> re-parse the input file every time it gets called. So in the line <code>self.getMetadataTree().write(self.meta_file)</code>, it parse the meta file and write it back (the same info). All previous modification to timestamp is not relevant (it's a different instan...
2
2016-08-07T20:47:21Z
[ "python", "xml", "datetime" ]
Python 3 - need from exec() to return values
38,817,962
<p>I have a small problem with <code>exec()</code>. I have string from Kivy GUI which I need to execute and store values from the executed code. </p> <pre><code>class gui(BoxLayout): def proces(self): t = threading.Thread(target=self.graf) t.daemon = True t.start() def graph(self): ...
0
2016-08-07T19:55:45Z
38,818,071
<p>You should call <code>exec</code> with a local namespace:</p> <pre><code>loc = {} exec(Code, {}, loc) x = loc['x'] y = loc['y'] </code></pre>
0
2016-08-07T20:06:50Z
[ "python", "return", "exec" ]
convert elastic search timestamp attribute to seconds
38,818,126
<p>How can i convert this timestamp value to an integer representing seconds-since-the-epoch in python</p> <pre><code> 2016-08-06T06:07:36.349Z </code></pre> <p>This is the timestamp value i received in elastic search query.</p> <p>I tried searching but the timestamp format was different from this and <a href="http:...
0
2016-08-07T20:13:43Z
38,818,222
<p>You can use python inbuilt datetime package and its strptime method to convert string into datetime object.</p> <pre><code>from datetime import datetime datetime.strptime("2016-08-06T06:07:36.349Z","%Y-%m-%dT%H:%M:%S.%fZ") </code></pre> <p>after that you should get epoch datetime object which you can get by </p> ...
1
2016-08-07T20:25:25Z
[ "python", "elasticsearch", "timestamp" ]
Filter only TCP SYN segments in scapy
38,818,131
<p>How can I filter only TCP SYN segments in Scapy? Could someone give me a simple example, please? I tried hard but I dont know scapy!</p>
1
2016-08-07T20:14:07Z
38,818,177
<p>Only TCP SYN segments:</p> <pre><code>tcp[tcpflags] &amp; tcp-syn != 0 </code></pre>
2
2016-08-07T20:20:25Z
[ "python", "scapy" ]
Have Code Change Terminal Settings Upon Load
38,818,150
<p>I have a program that requires me to enter <code>chcp 65001</code> and <code>set PYTHONIOENCODING=utf-8</code> before I run the code, or it cannot process characters properly. Is there a way to have the code automatically do this upon opening? Its a pain, and easy to forget, to do this every time.</p>
1
2016-08-07T20:17:06Z
38,819,626
<p>Actually, you should be able to do this within Python, but supposing that its runtime has this requirement, you can do these settings in a batch file before calling python with your script. For example, suppose this script is called <strong><code>pyutf8.bat</code></strong> :</p> <pre><code>@echo off setlocal chcp ...
0
2016-08-07T23:51:51Z
[ "python", "windows", "cmd", "windows-console" ]
Locating a graphic function (Python)
38,818,220
<p>First off, thanks to the site and everybody on it. I am taking my first python class and have come across this site many times when trouble-shooting coding problems. Thanks to everybody who have already helped me out a little thus far. But, I do have a problem I can't figure out:</p> <p>I have to draw the "5" si...
0
2016-08-07T03:15:24Z
38,842,725
<p>I was finally able to get this one. I wasn't aware you could command after the window arguement. So, the Dot(win, 350,150) etc. with the different coordinates worked well. Thanks for the responses and help!</p>
0
2016-08-09T05:29:33Z
[ "python", "graphics" ]
Beautifulsoup constructors and its arguments
38,818,274
<p>I've seen here on SO many ways to initialize a Beautifulsoup object. As far as I can see, you can either pass a string=url or to pass some object. For instance, it's common to use <code>urllib</code>:</p> <pre><code>url="https://somesite.com" url_html="&lt;html&gt;&lt;body&gt;&lt;h1&gt;Some header&lt;/h1&gt;&lt;p&g...
0
2016-08-07T20:31:40Z
38,818,338
<p><code>urlopen()</code> returns an open file-like object. The constructor of Beautifulsoup uses type-checking to see whether it got a file or a string (to be precise, it does <code>markup.hasattr("read")</code>. In the first case, it simply calls its <code>read()</code> method.</p> <p>This is a common pattern in Pyt...
2
2016-08-07T20:40:18Z
[ "python", "beautifulsoup" ]
Python, multiprocessing: How to optimize the code? Make the code faster?
38,818,285
<p>I use Python. I have 100 zip files. Each zipfile contains more than 100 xmlfiles. Using the xmlfiles I create csvfiles. </p> <pre><code>from xml.etree.ElementTree import fromstring import zipfile from multiprocessing import Process def parse_xml_for_csv1(data, writer1): root = fromstring(data) for node i...
0
2016-08-07T20:33:28Z
38,818,692
<p>You just need to define one method, with parameters. Split the processing of your 100 .zip files across a given number of threads or processes. The more processes you'll add, the more CPU you'll use, and maybe you can use more than 2 processes, it will be faster (there can be a bottleneck because of disk I/O at some...
2
2016-08-07T21:22:05Z
[ "python", "file", "multiprocessing", "python-multithreading", "zipfile" ]
Python for-loop with modification of the iterationlist
38,818,339
<p>I have this .txt file:</p> <pre><code>king james version of the bible the first book of moses called genesis </code></pre> <p>I use a python-script for statistics on .txt files, the file is read into the list <code>final_list</code> and then I execute this code (part of longer script):</p> <pre><code>for word...
-1
2016-08-07T20:40:19Z
38,818,418
<p>The trouble is that you're modifying the list. After the first iteration, Python's iterator stops looking at "position 0" in the list and moves to "position 1." You removed the element originally in position 0 (<code>king</code>), so the element that used to be in position 1 (<code>james</code>) is now in position 0...
1
2016-08-07T20:49:06Z
[ "python" ]
Python for-loop with modification of the iterationlist
38,818,339
<p>I have this .txt file:</p> <pre><code>king james version of the bible the first book of moses called genesis </code></pre> <p>I use a python-script for statistics on .txt files, the file is read into the list <code>final_list</code> and then I execute this code (part of longer script):</p> <pre><code>for word...
-1
2016-08-07T20:40:19Z
38,818,440
<p>You should not modify the list you are iterating on inside the for loop. Otherwise you will get this kind of weird behavior. You'd better use a copy of the final_list likeso:</p> <pre><code>final_copy = final_list[:] for word in final_list: output_list.append((word,final_copy.count(word))) final_copy = [x...
2
2016-08-07T20:51:39Z
[ "python" ]
Does flask session variable maintain state across threads?
38,818,350
<p>According to the <a href="http://flask.pocoo.org/docs/0.11/api/#sessions" rel="nofollow">docs</a>: </p> <blockquote> <p>A session basically makes it possible to remember information from one request to another.</p> </blockquote> <p>But elsewhere, <a href="http://flask.pocoo.org/docs/0.10/reqcontext/#how-the-co...
1
2016-08-07T20:41:35Z
38,818,411
<p>From the <em>very next sentence</em> after the one you quoted:</p> <blockquote> <p>The way Flask does this is by using a signed cookie.</p> </blockquote> <p>Flask stores the information in the cookie before sending the response, and reads it back at the beginning of the next request.</p>
2
2016-08-07T20:48:07Z
[ "python", "multithreading", "flask" ]
Custom User Model ValueError: Related Model Django(1.9)
38,818,370
<p>There is an error when I try to add CustomUser model as ForiegnKey to a field in django. The authentication is working using the CustomUser model but for some reason I have getting this error:</p> <pre><code>ValueError: Related model 'authentication.UserModel' cannot be resolved </code></pre> <p>Here is the app/m...
0
2016-08-07T20:43:16Z
38,818,514
<p>You seem to be missing a dependency for the migration that adds the user model. I'm not sure why it's missing, but try adding it manually and running your migrations again:</p> <pre><code>dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Forms', '0009_revised_tender_changes'), ] ...
1
2016-08-07T21:00:43Z
[ "python", "django", "django-models" ]
No output with .duplicated in pandas?
38,818,401
<p>I want to find all of the rows which have duplicates in the columns of city, round_latitude, and round_longitude. So, if two rows share the same values in each of those columns, it would be returned.</p> <p>I'm not exactly sure what is going on here: I'm certain that there are duplicates in the dataset. No error is...
-1
2016-08-07T20:46:33Z
38,819,324
<p><code>dl_by_loc(path)</code> returns a Series with a MultiIndex:</p> <pre><code>round_latitude round_longitude city 30.0 -95.0 Houston 1 40.0 -75.0 Philadelphia 3 Name: downloads, dtype: int64 </code></pre> <p>If you take a look at the definition of ...
1
2016-08-07T22:58:54Z
[ "python", "pandas", "numpy" ]
pandas.to_datetime: which format to choose?
38,818,459
<p>I have a .csv like that:</p> <pre class="lang-none prettyprint-override"><code>"Date","Time","Open","High","Low","Close","Volume" 12/30/2002,0930,0.94,0.94,0.94,0.94,571466 </code></pre> <p>I want to convert the "Time" column values with pandas.to_datetime module, but I can't find the correct format to use because...
0
2016-08-07T20:53:51Z
38,818,576
<p>This should work, but I'm not sure if there's a better way:</p> <pre><code>from StringIO import StringIO fh = StringIO('''"Date","Time","Open","High","Low","Close","Volume" 12/30/2002,0930,0.94,0.94,0.94,0.94,571466''') df = pd.read_csv(fh, dtype={'Time':object}) df['Timestamp'] = pd.to_datetime(df['Date'] + ' ' ...
1
2016-08-07T21:09:01Z
[ "python", "python-2.7", "datetime", "pandas", "datetime-format" ]
pandas.to_datetime: which format to choose?
38,818,459
<p>I have a .csv like that:</p> <pre class="lang-none prettyprint-override"><code>"Date","Time","Open","High","Low","Close","Volume" 12/30/2002,0930,0.94,0.94,0.94,0.94,571466 </code></pre> <p>I want to convert the "Time" column values with pandas.to_datetime module, but I can't find the correct format to use because...
0
2016-08-07T20:53:51Z
38,819,065
<p>You can tell pandas that there is no separator there by specifying the format of the date. <code>%H%M</code> tells python that you have a time that has no divider. If you had a divider of <code>:</code>, for example, then you would use <code>format='%H:%M'</code>.</p> <p>Assuming you have loaded everything in and y...
0
2016-08-07T22:17:48Z
[ "python", "python-2.7", "datetime", "pandas", "datetime-format" ]
pandas.to_datetime: which format to choose?
38,818,459
<p>I have a .csv like that:</p> <pre class="lang-none prettyprint-override"><code>"Date","Time","Open","High","Low","Close","Volume" 12/30/2002,0930,0.94,0.94,0.94,0.94,571466 </code></pre> <p>I want to convert the "Time" column values with pandas.to_datetime module, but I can't find the correct format to use because...
0
2016-08-07T20:53:51Z
38,824,333
<p>You can a pass a list of the columns to parse as a complete <code>datetime</code> by passing a list of lists to <code>parse_dates</code> param:</p> <pre><code>In [6]: import io import pandas as pd t='''"Date","Time","Open","High","Low","Close","Volume" 12/30/2002,0930,0.94,0.94,0.94,0.94,571466''' df = pd.read_csv(...
0
2016-08-08T08:20:24Z
[ "python", "python-2.7", "datetime", "pandas", "datetime-format" ]
Python Installing issu
38,818,484
<p><a href="http://i.stack.imgur.com/MofXs.png" rel="nofollow"><img src="http://i.stack.imgur.com/MofXs.png" alt="enter image description here"></a></p> <p>I reinstalled it many times but nothing is solved , what should I do ?</p>
-8
2016-08-07T20:56:29Z
39,382,523
<p>Although this question is a little old, I have a possible solution.</p> <p>In English the message is:</p> <blockquote> <p>Unable to start the program because api-ms-win-crt-runtime-l1-1-0.dll cannot be found on your computer. Try to reinstall the program to fix this problem.</p> </blockquote> <p>The problem is ...
0
2016-09-08T04:18:32Z
[ "python", "installer" ]
Skip rows with missing values in read_csv
38,818,609
<p>I have a very large csv which I need to read in. To make this fast and save RAM usage I am using read_csv and set the dtype of some columns to np.uint32. The problem is that some rows have missing values and pandas uses a float to represent those. </p> <ol> <li>Is it possible to simply skip rows with missing valu...
0
2016-08-07T21:12:55Z
38,819,013
<p>If you show some data, SO ppl could help. </p> <pre><code>pd.read_csv('FILE', keep_default_na=False) </code></pre> <p>For starters try these: </p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.re...
-1
2016-08-07T22:08:12Z
[ "python", "pandas" ]
Skip rows with missing values in read_csv
38,818,609
<p>I have a very large csv which I need to read in. To make this fast and save RAM usage I am using read_csv and set the dtype of some columns to np.uint32. The problem is that some rows have missing values and pandas uses a float to represent those. </p> <ol> <li>Is it possible to simply skip rows with missing valu...
0
2016-08-07T21:12:55Z
38,819,123
<p>There is no feature in Pandas that does that. You can implement it in regular Python like this:</p> <pre><code>import csv import pandas as pd def filter_records(records): """Given an iterable of dicts, converts values to int. Discards any record which has an empty field.""" for record in records: ...
0
2016-08-07T22:26:05Z
[ "python", "pandas" ]
Skip rows with missing values in read_csv
38,818,609
<p>I have a very large csv which I need to read in. To make this fast and save RAM usage I am using read_csv and set the dtype of some columns to np.uint32. The problem is that some rows have missing values and pandas uses a float to represent those. </p> <ol> <li>Is it possible to simply skip rows with missing valu...
0
2016-08-07T21:12:55Z
38,819,282
<p>It would be dainty if you could fill <code>NaN</code> with say <code>0</code> during read itself. Perhaps a feature request in Pandas's git-hub is in order...</p> <h1>Using a converter function</h1> <p>However, for the time being, you can define your own function to do that and pass it to the <code>converters</cod...
2
2016-08-07T22:52:52Z
[ "python", "pandas" ]
How to create a new column based on one of three other columns?
38,818,626
<p>I have a Dataframe that has a movie name column and 3 other columns (let's call them A, B, and C) that are ratings from 3 different sources. There are many movies with only one rating, some movies with a combination from the 3 forums, and some with no ratings. I want to create a new column that will: </p> <ol> <li...
0
2016-08-07T21:14:45Z
38,818,720
<p>You are returning <code>rating</code> in your original function .. but <code>rating</code> is the <strong>row</strong>, not the value of any column</p> <pre><code>&gt;&gt;&gt; df A B C Genre Title Year 0 7 6 \N g1 m1 y1 1 \N 5 7 g2 m2 y2 2 \N \N \N g3 m3 y3 3 \N 4 1...
1
2016-08-07T21:25:34Z
[ "python", "pandas" ]
How to create a new column based on one of three other columns?
38,818,626
<p>I have a Dataframe that has a movie name column and 3 other columns (let's call them A, B, and C) that are ratings from 3 different sources. There are many movies with only one rating, some movies with a combination from the 3 forums, and some with no ratings. I want to create a new column that will: </p> <ol> <li...
0
2016-08-07T21:14:45Z
38,818,758
<p>I would do something like this:</p> <pre><code>df = df.replace('\\N', np.nan) # this requires import numpy as np (df['Yahoo Rating'].fillna(df['Movie Mom Rating'] .fillna(df['Critic Rating'] .fillna("Unrated")))) </code></pre> <p>The reason that your code doesn't work is that...
4
2016-08-07T21:30:41Z
[ "python", "pandas" ]
Python - TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
38,818,817
<p>I have a program that allows a user to convert between currencies and allow them to have bank accounts for five different currencies. </p> <p>When I try to display the bank account balance to the user, I get a message saying that 'value' is a <code>Nonetype</code>, yet I don't understand how <code>None</code> is be...
0
2016-08-07T21:38:41Z
38,818,873
<p>You should ensure that your USDCheckBalance method does return an int. It seems that there are cases where it doesn't return anything, causing the error. (The "you don't have an account" case)</p>
2
2016-08-07T21:48:12Z
[ "python", "methods" ]
Python - TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
38,818,817
<p>I have a program that allows a user to convert between currencies and allow them to have bank accounts for five different currencies. </p> <p>When I try to display the bank account balance to the user, I get a message saying that 'value' is a <code>Nonetype</code>, yet I don't understand how <code>None</code> is be...
0
2016-08-07T21:38:41Z
38,818,923
<p>If there is no bank account, you implicitly return <code>None</code>. Best use exceptions in that case:</p> <pre><code>def USDCheckBalance(self, USDaccountName): for account in self.USDaccountList: if USDaccountName == account.owner: return account.value raise KeyError("You don't have an...
3
2016-08-07T21:54:49Z
[ "python", "methods" ]
Selenium - Login raises ElementNotVisibleException
38,818,840
<p>I am using Selenium Webdriver to login to a site. I've tried multiple different selectors, and have tried implicit waits, but cannot locate the element. </p> <pre><code> from selenium import webdriver from selenium.webdriver.common.by import By browser = webdriver.Firefox() url = "https://www.exampl...
3
2016-08-07T21:42:40Z
38,819,149
<p>Actually you are locating element, problem with the <code>send_keys</code>, here could not be set value on the email input due to invisibility of element. But as I see in provided HTML no style attribute property exists on email input element which could make it invisible. </p> <p>May be possible there are more ele...
1
2016-08-07T22:31:18Z
[ "python", "selenium", "selenium-webdriver" ]
Scrapy Pipeline not insert data to MySQL
38,818,846
<p>I'm making a pipeline in scrapy to store scraped data in a mysql database. When the spider is run in terminal it works perfectly. Even the pipeline is opened. However the data is not being sent to the database. Any help appreciated! :)</p> <p>here's the pipeline code:</p> <pre><code>import scrapy from scrapy.pipe...
0
2016-08-07T21:43:14Z
38,826,691
<p>I got this working a few weeks ago but switched to a different database. At the time I based some code off of this: <a href="https://gist.github.com/tzermias/6982723" rel="nofollow">https://gist.github.com/tzermias/6982723</a></p> <p>Also remember to update your settings.py file as well if you use the above code....
0
2016-08-08T10:20:09Z
[ "python", "mysql", "scrapy" ]
add timestamps related fields from existing unix timestamp field dataframe in python
38,818,924
<p>I am new to Python Programing language. For my learning I took sample sales data that contain <strong>orderid, product_name, no_items, amount, total_amount, sale_time</strong>. I am using pandas to load the data.</p> <pre><code>import pandas as pd sale_data = pd.read_csv("test_sale_data.csv") </code></pre> <p><str...
0
2016-08-07T21:54:58Z
38,819,189
<p>Use the <a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/basics.html#basics-dt-accessors" rel="nofollow"><code>.dt</code> accessor</a> in pandas; all of <a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/timeseries.html#time-date-components" rel="nofollow">these components</a> are available. Fo...
0
2016-08-07T22:38:13Z
[ "python", "python-2.7", "datetime", "pandas", "time-series" ]
Most efficient way to check twitter friendship? (over 5000 check)
38,818,981
<p>I'm facing problem like this. I used tweepy to collect +10000 tweets, i use nltk naive-bayes classification and filtered the tweets into +5000. I want to generate a graph of user friendship from that classified 5000 tweet. The problem is that I am able to check it with tweepy.api.show_frienship(), but it takes so m...
2
2016-08-07T22:03:37Z
38,819,049
<p>I don't know much about the limits with Tweepy, but you can always write a basic web scraper with urllib and BeautifulSoup to do so.</p> <p>You could take a website such as <code>www.doesfollow.com</code> which accomplishes what you are trying to do. (not sure about request limits with this page, but there are doze...
0
2016-08-07T22:14:19Z
[ "python", "twitter", "tweepy" ]
ImgurPython ConfigParser error
38,819,009
<p>I've come back to Python after a couple of years of not having used it. I'm testing the <a href="https://github.com/Imgur/imgurpython" rel="nofollow">Imgur Python library</a>. After a fresh install of Python 2.7.12, I did a quick pip install of ImgurPython, then dragged a small folder of the sample scripts to my des...
0
2016-08-07T22:07:49Z
38,819,610
<p>You may have a bad format of <code>auth.ini</code> file. In my python 2.7, the extraction works totally fine with <code>ConfigParser</code>:</p> <pre><code>$ cat auth.ini [credentials] client_id=foo client_secret=bar </code></pre> <p>In my Ipython:</p> <pre><code>In [1]: import ConfigParser In [2]: config = Con...
0
2016-08-07T23:47:47Z
[ "python", "imgur" ]
Python 3.5 - Tkinter Using variables for filenames + paths
38,819,048
<p>I have a combo box which always sets two variables<br> 1) is a filename (.csv)<br> 2) is a file path location</p> <p>Depending on what is selected in the combo box, a particular .csv file is allocated to variable <code>csvfilename</code> and a path is allocated to <code>path</code> </p> <p>I'm trying to feed these...
-1
2016-08-07T22:14:14Z
38,819,067
<p><code>path</code> is a <code>StringVar</code> object, and you are trying to add <code>/</code> to it.</p> <p>Instead of trying to define a keyword argument, pass in the <code>StringVar</code> objects (<code>path</code> and <code>linkname</code>) and get their values <em>in the <code>lambda</code></em>:</p> <pre><c...
0
2016-08-07T22:18:09Z
[ "python", "python-3.x", "combobox", "tkinter" ]
Python 3.5 - Tkinter Using variables for filenames + paths
38,819,048
<p>I have a combo box which always sets two variables<br> 1) is a filename (.csv)<br> 2) is a file path location</p> <p>Depending on what is selected in the combo box, a particular .csv file is allocated to variable <code>csvfilename</code> and a path is allocated to <code>path</code> </p> <p>I'm trying to feed these...
-1
2016-08-07T22:14:14Z
38,819,137
<p>A tkinter Stringvar is not a python string. To return the value of a Stringvar you use <code>variable.get()</code></p> <p>Since <code>path</code> is not a string you cant add a string to it, put <code>path.get() + ...</code> . What happens if tye path entered doesn't exist? Does the progrsm crash?</p>
1
2016-08-07T22:28:35Z
[ "python", "python-3.x", "combobox", "tkinter" ]
Unicode Python Windows Consle
38,819,079
<p>I have a program for a Blackjack game. It is not completed but I am having an issue with Unicode. When it prints a string it is not in the correct format (Look Below). It is Python 3.</p> <pre><code>from unicurses import * import sys import time from random import choice as rc import random def total(hand): #total...
1
2016-08-07T22:19:27Z
38,820,585
<p>On Windows, unicurses uses ctypes to wrap <a href="https://sourceforge.net/projects/pdcurses" rel="nofollow">PDCurses</a>. This library is optionally built with Unicode support in the 32-bit DLLs that are distributed on the project site. FYI, the Unicode versions call console wide-character APIs such as <code>WriteC...
1
2016-08-08T02:40:05Z
[ "python", "windows", "unicode", "utf-8", "utf" ]
How to kill Finished threads in python
38,819,091
<p>My multi-threading script raising this error :</p> <pre><code>thread.error : can't start new thread </code></pre> <p>when it reached 460 threads :</p> <pre><code>threading.active_count() = 460 </code></pre> <p>I assume the old threads keeps stack up, since the script didn't kill them. This is my code:</p> <pre>...
0
2016-08-07T22:21:19Z
38,820,283
<p>Your <code>threader</code> function never exits, so your threads never die. Since you're just processing one fixed set of work and never adding items after you start working, you could set the threads up to exit when the queue is empty.</p> <p>See the following altered version of your code and the comments I added:...
0
2016-08-08T01:54:12Z
[ "python", "multithreading" ]
Reading a TTree in root using PyRoot
38,819,098
<p>I just started using pyroot to read root files and I can't read the data from a file using jupyter notebook. Here is how the TBrowser looks like:</p> <p><a href="http://i.stack.imgur.com/mt1ZZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/mt1ZZ.png" alt="enter image description here"></a></p> <p>I started...
0
2016-08-07T22:23:15Z
38,847,387
<p>Normally with pyROOT, you can just do something like:</p> <pre><code>import ROOT as root import numpy as np f = root.TFile("RealData.root") myTree = f.Get("tree") for entry in myTree: # Now you have acess to the leaves/branches of each entry in the tree, e.g. events = entry.events </code></pre> ...
0
2016-08-09T09:47:53Z
[ "python", "root-framework", "pyroot" ]
Python Script Pexpect SSH
38,819,147
<p>I'm trying to do a Python script (with a loop) to connect in SSH,it works if everything is good ( password and route) but stop when it's not working(wrong password or no routes to host ).Here is the important part of the script, how can I control if everything is working ? </p> <pre><code>connexion = pexpect.spawn(...
-1
2016-08-07T22:31:03Z
38,824,679
<p>The problem is that the host <code>10.9.128.5</code> was not reachable at the moment. <code>ssh</code> has returned this message:</p> <pre><code>connect to host 10.9.128.5 port 22: No route to host </code></pre> <p>And not that, what was expected.</p>
0
2016-08-08T08:40:29Z
[ "python", "shell", "ssh", "pexpect" ]
Python Script Pexpect SSH
38,819,147
<p>I'm trying to do a Python script (with a loop) to connect in SSH,it works if everything is good ( password and route) but stop when it's not working(wrong password or no routes to host ).Here is the important part of the script, how can I control if everything is working ? </p> <pre><code>connexion = pexpect.spawn(...
-1
2016-08-07T22:31:03Z
38,900,097
<p>You are getting an exception which needs to be handled correctly. Below is some code that you can use as an example to pass the exception and log it.</p> <pre><code>def ignore_exception_out(conn, text, timeout=10): try: conn.expect(text, timeout) except Exception as e: loggin...
2
2016-08-11T15:08:56Z
[ "python", "shell", "ssh", "pexpect" ]
pyinstaller not working with lxml
38,819,168
<p>I am trying to create an exe using pyinstaller but keep running into this error</p> <pre><code>Traceback (most recent call last): File "runautojama.py", line 28, in &lt;module&gt; File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module exec(bytecode, module.__dict__) ...
0
2016-08-07T22:34:25Z
38,834,030
<p>@WombatPM thanks for pointing it out. The problem gets resolved using the dev version <code>3.3.dev0+gd3e0cb4</code></p>
0
2016-08-08T16:14:57Z
[ "python", "lxml", "pyinstaller" ]
Scipy - Error while using spherical Bessel functions
38,819,303
<p>I'm trying to draw plots in Python with Scipy module. According to <a href="http://docs.scipy.org/doc/scipy/reference/special.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/special.html</a> I wrote code with <code>scipy.special.spherical_jn(n,x,0)</code>:</p> <pre><code>import matplotlib.pyplot as p...
0
2016-08-07T22:56:08Z
38,819,851
<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.spherical_jn.html" rel="nofollow"><code>scipy.special.spherical_jn</code></a> was added in scipy version 0.18.0, which was released on July 25, 2016. My guess is you are using an older version of scipy. To check, run</p> <pre><code>import ...
2
2016-08-08T00:34:16Z
[ "python", "scipy", "bessel-functions" ]
Unable to instantiate StanfordNERTagger on OS X
38,819,371
<p>I am trying to instantiate <strong><code>StanfordNERTagger</code></strong>. This is what I am trying:</p> <pre><code>st = StanfordNERTagger("/Users/attitude/Desktop/english.all.3class.caseless.distsim.crf.ser.gz","/Users/attitude/Desktop/stanford-ner-2015-12-09/stanford-ner.jar") </code></pre> <p>I have set the <c...
0
2016-08-07T23:05:19Z
38,819,496
<p><strong>TL;DR</strong>:</p> <p>Without setting environmental variable, use the keywords arguments, <code>model_filename</code> and <code>path_to_jar</code></p> <pre><code>from nltk.tag import StanfordNERTagger stanford_ner_dir = '/home/alvas/stanford-ner/' eng_model_filename= stanford_ner_dir + 'classifiers/engli...
1
2016-08-07T23:26:37Z
[ "python", "nltk", "osx-yosemite", "stanford-nlp", "pos-tagger" ]
Count repeating elements in a CSV column
38,819,444
<p>I'm currently trying to get used to Python and am trying to read a column and count the repeating elements from the strings.</p> <p>What I have so far:</p> <pre><code>i = 0 y = [i] fav_Split = row[9].split('|') #print fav_Split for x in fav_Split: #print x y[i] = x i = i+1 </code></pre> <p><code>prin...
0
2016-08-07T23:16:59Z
38,819,527
<p>First, let me give you an improvement to your original code:</p> <pre><code>y = [] fav_Split = row[9].split('|') #print fav_Split for x in fav_Split: y += x </code></pre> <p>Or, even shorter:</p> <pre><code>fav_split = row[9].split('|') y = [item for sublist in fav_Split for item in sublist] </code></pre> ...
1
2016-08-07T23:32:09Z
[ "python", "arrays", "list" ]
Jinja2 Flask Python button across many pages
38,819,551
<p>Using flasks render template function, you can sculpt complicated pages quickly. I want to have a small "up vote" "module" .html file that encases all the scripts and html needed to get the button working.</p> <p>In jinja you can use the "extends to" tag that inserts the current section into the section called by t...
0
2016-08-07T23:36:02Z
38,819,574
<p>You should use the <a href="http://jinja.pocoo.org/docs/dev/templates/#include" rel="nofollow"><code>include</code></a> statement. This is similar to using <code>import</code> in plain Python.</p> <p>However, note that Jinja2 also has an <code>import</code> statement. This is different than <code>include</code> in ...
1
2016-08-07T23:41:06Z
[ "python", "flask", "jinja2" ]
Use requests module in Python to log in to Barclays premier league fantasy football?
38,819,570
<p>I'm trying to write a Python script to let me log in to my fantasy football account at <a href="https://fantasy.premierleague.com/">https://fantasy.premierleague.com/</a>, but something is not quite right with my log in. When I login through my browser and check the details using Chrome developer tools, I find that ...
9
2016-08-07T23:40:22Z
38,925,310
<p>The following worked for me. I simply removed <code>headers = head</code></p> <pre><code>session.post('https://users.premierleague.com/accounts/login/', data = values) </code></pre> <p>I think you are trying to pick your team programmatically, like me. Your code got me started thanks.</p>
2
2016-08-12T19:34:32Z
[ "python", "session", "login", "request" ]
Multiple sessions and graphs in Tensorflow (in the same process)
38,819,576
<p>I'm training a model where the input vector is the output of another model. This involves restoring the first model from a checkpoint file while initializing the second model from scratch (using <code>tf.initialize_variables()</code>) in the same process. </p> <p>There is a substantial amount of code and abstractio...
1
2016-08-07T23:41:34Z
38,889,562
<p>The issue is most certainly happening due to concurrent execution of different session objects. I moved the first model's session from the background thread to the main thread, repeated the controlled experiment several times (running for over 24 hours and reaching convergence) and never observed <code>NaN</code>. O...
0
2016-08-11T07:09:55Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
Korean txt file encoding with utf-8
38,819,602
<p>I'm trying to process a Korean text file with python, but it fails when I try to encode the file with utf-8. </p> <pre><code>#!/usr/bin/python #-*- coding: utf-8 -*- f = open('tag.txt', 'r', encoding='utf=8') s = f.readlines() z = open('tagresult.txt', 'w') y = z.write(s) z.close </code></pre> <blockquote> <pre...
0
2016-08-07T23:45:02Z
38,819,716
<p>In Python 2 the <a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow">open function</a> does not take an encoding parameter. Instead you read a line and convert it to unicode. This <a href="https://pythonhosted.org/kitchen/unicode-frustrations.html" rel="nofollow">article</a> on kitchen (as ...
0
2016-08-08T00:08:51Z
[ "python", "encoding", "utf-8" ]
Korean txt file encoding with utf-8
38,819,602
<p>I'm trying to process a Korean text file with python, but it fails when I try to encode the file with utf-8. </p> <pre><code>#!/usr/bin/python #-*- coding: utf-8 -*- f = open('tag.txt', 'r', encoding='utf=8') s = f.readlines() z = open('tagresult.txt', 'w') y = z.write(s) z.close </code></pre> <blockquote> <pre...
0
2016-08-07T23:45:02Z
38,819,723
<p>I don't know Korean, and don't have sample string to try, but here are some advices for you:</p> <p>1</p> <pre><code>f = open('tag.txt', 'r', encoding='utf=8') </code></pre> <p>You have a typo here, <code>utf-8</code> not <code>utf=8</code>, this explains for the exception you got.</p> <p>The default mode of <co...
0
2016-08-08T00:10:11Z
[ "python", "encoding", "utf-8" ]
Several variables in if-statement
38,819,648
<p>This works as intended:</p> <pre><code>if c1 in r':6' or c2 in r':6': subst_weight = 1 </code></pre> <p>This doesn't:</p> <pre><code>if (c1 or c2) in r':6': subst_weight = 1 </code></pre> <p>Why and what is the differnce? The goal is to find out whether <code>c1</code> or <code>c2</code> is in the string...
2
2016-08-07T23:56:30Z
38,819,667
<p>This expression: </p> <pre><code>if (c1 or c2) in r':6': </code></pre> <p>Evaluates from left to right. Assuming that <code>(c1 or c2)</code> is truthy, it's equivalent to this:</p> <pre><code>if True in r':6': </code></pre> <p>Which obviously is not what you want. If you want it to work for several variables, t...
1
2016-08-08T00:00:21Z
[ "python", "if-statement", "logical-operators" ]
Several variables in if-statement
38,819,648
<p>This works as intended:</p> <pre><code>if c1 in r':6' or c2 in r':6': subst_weight = 1 </code></pre> <p>This doesn't:</p> <pre><code>if (c1 or c2) in r':6': subst_weight = 1 </code></pre> <p>Why and what is the differnce? The goal is to find out whether <code>c1</code> or <code>c2</code> is in the string...
2
2016-08-07T23:56:30Z
38,819,674
<p>It has to do with the precedent given to the operators. The use of ()'s means that <code>c1 or c2</code> is evaluated first. It evaluates to True or False. So your statement converts to </p> <pre><code>if bool in r':g' </code></pre> <p>Which is not what you are looking for.</p>
1
2016-08-08T00:00:45Z
[ "python", "if-statement", "logical-operators" ]
Several variables in if-statement
38,819,648
<p>This works as intended:</p> <pre><code>if c1 in r':6' or c2 in r':6': subst_weight = 1 </code></pre> <p>This doesn't:</p> <pre><code>if (c1 or c2) in r':6': subst_weight = 1 </code></pre> <p>Why and what is the differnce? The goal is to find out whether <code>c1</code> or <code>c2</code> is in the string...
2
2016-08-07T23:56:30Z
38,819,676
<p>The statement <code>one or two</code> will return <code>one</code> if defined, and <code>two</code> if <code>one</code> is not truthy, and I don't see a reason it wouldn't work with your logic because if either is truthy, and is contained in string, it will evaluate to <code>True</code></p> <pre><code>&gt;&gt;&gt; ...
3
2016-08-08T00:00:48Z
[ "python", "if-statement", "logical-operators" ]
Several variables in if-statement
38,819,648
<p>This works as intended:</p> <pre><code>if c1 in r':6' or c2 in r':6': subst_weight = 1 </code></pre> <p>This doesn't:</p> <pre><code>if (c1 or c2) in r':6': subst_weight = 1 </code></pre> <p>Why and what is the differnce? The goal is to find out whether <code>c1</code> or <code>c2</code> is in the string...
2
2016-08-07T23:56:30Z
38,819,694
<p>Because <code>(c1 or c1)</code> evaluates as the value of the first variable, if it is not "false"(which means false, 0 or an empty string) or the value of the second variable. </p> <p>Programming languages don't work like "natural languages".</p>
1
2016-08-08T00:04:22Z
[ "python", "if-statement", "logical-operators" ]
Several variables in if-statement
38,819,648
<p>This works as intended:</p> <pre><code>if c1 in r':6' or c2 in r':6': subst_weight = 1 </code></pre> <p>This doesn't:</p> <pre><code>if (c1 or c2) in r':6': subst_weight = 1 </code></pre> <p>Why and what is the differnce? The goal is to find out whether <code>c1</code> or <code>c2</code> is in the string...
2
2016-08-07T23:56:30Z
38,819,719
<p>Although not literally answering your question of why, this is an answer to "how then should I..."</p> <pre><code>if any(x in r':6' for x in [c1, c2]): something </code></pre> <p>If you ever get more of the 'c's, use a variable to define the list beforehand.</p> <p>(sauce: <a href="http://stackoverflow.com/ques...
2
2016-08-08T00:09:10Z
[ "python", "if-statement", "logical-operators" ]
How to give raw bytes as parameter to C program
38,819,683
<p>I'm working on an online CTF challenge and I need to somehow give raw bytes to this compiled C program. I've tried the following using python:</p> <pre><code>./program `python -c 'print "\x00\x00"'` </code></pre> <p>... but for some reason that doesn't seem to be giving me what I'm expecting. Is there some convers...
0
2016-08-08T00:02:33Z
38,819,709
<p>Command line args in C are an array of 0 terminated strings. There is no way to pass "raw bytes" (any 0 byte won't behave as expected).</p> <p>I'd suggest passing either reading the bytes from stdin or from a file specified on the command line.</p>
1
2016-08-08T00:07:34Z
[ "python", "c", "byte" ]
Use of random.randint in Flask
38,819,796
<p>I am playing with Flask to understand it better. I have a simple app that queries a large database and returns a random element. The following code is not working but I know exactly where it fails. It fails when I can random.randint() to get a random element in the list. There is however no error shown in my logs, w...
-1
2016-08-08T00:24:27Z
38,819,926
<p>It is something I don't understand but here is what is happening. I need to import random inside the random() function. Otherwise the global "import random" statement does not seem to be sufficient. Not sure why. So adding one import line inside random() made it work. If anybody can explain this I would be grateful....
0
2016-08-08T00:50:35Z
[ "python", "random" ]
Use of random.randint in Flask
38,819,796
<p>I am playing with Flask to understand it better. I have a simple app that queries a large database and returns a random element. The following code is not working but I know exactly where it fails. It fails when I can random.randint() to get a random element in the list. There is however no error shown in my logs, w...
-1
2016-08-08T00:24:27Z
38,819,972
<p>You have redefined <code>random</code> by defining a function named <code>random()</code>.</p> <pre><code>@app.route('/element', methods=['POST', 'GET']) def random(): ... </code></pre> <p>This shadows the imported module, causing the problem that you see. When you <code>import random</code> again in <code>get...
0
2016-08-08T01:01:00Z
[ "python", "random" ]
How should I go about geolocating 1,100,000 lines of coordinate information?
38,819,915
<p>Okay, so I'm trying to envision a solution for this. I have a database with over a million lines which includes a city name in the US and a set of coordinates for that city. The problem is that there are multiple cities with the same name: Springfield, NJ and Springfield, MA, for example. So I need to get the state ...
1
2016-08-08T00:48:29Z
38,820,048
<p>Almost certainly the best way to avoid doing extra work will be to use a hash table to check if something already had a mapping:</p> <pre><code>processed_coords = {} def convert_to_state(lati, long): lat, lon = float(lati), float(long) if (lat, lon) not in processed_coords: g = geocoder.google([lat,...
2
2016-08-08T01:12:32Z
[ "python", "pandas", "geolocation", "google-geocoder" ]
How should I go about geolocating 1,100,000 lines of coordinate information?
38,819,915
<p>Okay, so I'm trying to envision a solution for this. I have a database with over a million lines which includes a city name in the US and a set of coordinates for that city. The problem is that there are multiple cities with the same name: Springfield, NJ and Springfield, MA, for example. So I need to get the state ...
1
2016-08-08T00:48:29Z
38,820,762
<p>I like the hash table idea, but here is an alternative using some pandas stuff: </p> <p>1) get a unique list of (lat, lon) coords</p> <pre><code>df['latlon'] = [(x,y) for x,y in zip(df['lati'].tolist(),df['long'].tolist())] unique_ll = df['latlon'].unique() </code></pre> <p>2) loop through unique coords and set ...
1
2016-08-08T03:10:41Z
[ "python", "pandas", "geolocation", "google-geocoder" ]
How should I go about geolocating 1,100,000 lines of coordinate information?
38,819,915
<p>Okay, so I'm trying to envision a solution for this. I have a database with over a million lines which includes a city name in the US and a set of coordinates for that city. The problem is that there are multiple cities with the same name: Springfield, NJ and Springfield, MA, for example. So I need to get the state ...
1
2016-08-08T00:48:29Z
39,775,543
<p>There's a geo-info service SmartyStreets that has a list tool that processes lists of searches and returns a bunch of information (can upload a spreadsheet or copy and paste). They focus on address validation so they expect search terms to be addresses, however, it can match just zip codes to cities and states. Do y...
0
2016-09-29T16:28:34Z
[ "python", "pandas", "geolocation", "google-geocoder" ]
Exporting values from a Spreadsheet using Python for webscraping (BeautifulSoup4)
38,819,951
<p>A. My Objective: Use Python to extract unique OCPO IDs from an Excel Spreadsheet and using these IDs to web-scrape for corresponding company names and NIN IDs. (Note: Both NIN and OCPO IDs are unique to one company).</p> <p>B. Details: i. Extract OCPO IDs from an Excel Spreadsheet using openpyxl. ii. Search OCPO ID...
0
2016-08-08T00:56:10Z
38,831,777
<p>1) Create an empty workbook to write to:</p> <pre><code>wb2 = Workbook() ws1 = wb2.active </code></pre> <p>2) Put all that code in the 2nd box into your for loop from the first box.</p> <p>3) Change "00044428" to str(cellobjc.value)</p> <p>4) At the end of each loop, append your row to the new worksheet:</p> <p...
0
2016-08-08T14:24:18Z
[ "python", "python-3.x", "web-scraping", "beautifulsoup", "openpyxl" ]
Vader Sentiment values not coming out correctly
38,819,968
<p>I'm using vader sentiment to analyze CSV files full of tweets. I'm try to get an average for each of the sentiment values for the entire set of Tweets. For some reason, many of the results tend to come out with values of 0 which doesn't make sense unless it's a rounding issue. Also len(result[i]) always returns 1. M...
-1
2016-08-08T01:00:26Z
38,820,398
<p>Nevermind, I realized I was stupidly placing result = { 'pos':[] , 'neg':[], 'compound':[], 'neu':[] } where I shouldn't have so it was clearing the data at each iteration of the loop. I can't believe that took me so long to figure out...</p>
0
2016-08-08T02:11:27Z
[ "python", "sentiment-analysis" ]
Python slow on for-loops and hundreds of attribute lookups. Use Numba?
38,820,040
<p>i am working on a simple showcase SPH (smoothed particle hydrodynamics, not relevant here though) implementation in python. The code works, but the execution is kinda sluggish. I often have to compare individual particles with a certain amount of neighbours. In an earlier implementation i kept all particle positions...
1
2016-08-08T01:11:47Z
38,820,116
<p>These kind of loop-intensive calculations are slow in Python. In these cases, the first thing you want to do is to see if you can vectorize these operations and get rid of the loops. Then actual calculations will be done in C or Fortran libraries and you will get a lot of speed up. If you can do it usually this is t...
2
2016-08-08T01:26:22Z
[ "python", "jit", "numba", "kdtree" ]
creating sparse matrix of unknown size
38,820,079
<p>I have a text file with each line indicating an edge on a graph, for example</p> <pre><code>2 5 1 </code></pre> <p>indicates an edge of weight 1 between nodes 2 and 5. I want to create a sparse adjacency matrix using these tuples. Typically, I'd initialize a sparse matrix as</p> <pre><code>G = scipy.sparse.lil_ma...
0
2016-08-08T01:20:07Z
38,821,384
<p>The original, and still prototypical, way of creating a sparse matrix is to collect all inputs in <code>row, col, data</code> arrays (or lists), and use <code>coo_matrix</code> to construct the matrix. Shape can be deduced from those inputs (maximum index values), or given as a parameter.</p> <p>To adapt your code...
1
2016-08-08T04:38:30Z
[ "python", "numpy", "scipy", "sparse-matrix" ]
Flask: AttributeError: 'UnboundField' object has no attribute '__call__'?
38,820,081
<p>Why do I get this error? What is the UnboundField and what do I need to know in order to fix and avoid this problem in the future?</p> <p><strong>Debug output when I visit <a href="http://127.0.0.1:5000/signup" rel="nofollow">http://127.0.0.1:5000/signup</a>:</strong></p> <pre><code>AttributeError AttributeError:...
-1
2016-08-08T01:20:17Z
38,820,288
<p>In routes.py, I think your <code>signup()</code> method should contain <code>form = SignupForm(request.form)</code>. Otherwise, form is set to a class instead of an instance.</p>
0
2016-08-08T01:54:46Z
[ "python", "flask", "jinja2" ]
How to scale a signal in python on the x axis?
38,820,132
<p>I need a function on python that can take an array and stretch it or compress it by a given rate. For example, lets say that I have an array a=[0,1,0,-1,0] and I want to stretch it by a factor of 2 then the result array would be b=[0,0.5,1,0.5,0,-0.5,-1,-0.5,0]</p> <p><a href="http://i.stack.imgur.com/jHsKE.png" re...
0
2016-08-08T01:28:55Z
38,820,560
<pre><code>def rescale(arr, factor=2): n = len(arr) return np.interp(np.linspace(0, n, factor*n+1), np.arange(n), arr) </code></pre>
1
2016-08-08T02:36:17Z
[ "python", "signal-processing" ]
How to return parents in path, and locate key in JSON
38,820,164
<p>I'm trying to figure out how to find a key called ['text'] and then get the parent keys from the nest. It's the third key that's different, all the other tags are the same.</p> <pre><code> html_data = data['data']['document_data']['dataItem-ihmty5rw']['text'] </code></pre> <p>I'm using this function to get the ...
0
2016-08-08T01:35:33Z
38,820,966
<p>I'm still not entirely sure if this is what you wanted, but if you just want the text per item dictionary, I think this should work:</p> <pre><code># a dictionary of item string to dictionary containing a "text" key item_map = data['data']['document_data'] for item_string, item_map in item_map.iteritems(): p...
0
2016-08-08T03:40:09Z
[ "python", "json", "key" ]
Impossible speedups when using JIT in python. What's going on?
38,820,207
<p>I'm trying to test the speed improvement of using JIT in python. Here's the code I'm using.</p> <pre class="lang-py prettyprint-override"><code>from numba import jit import timeit @jit # Commented out when testing pure python def sumof(): x = 0 for i in xrange(1000000000): x += 1 return x def ...
0
2016-08-08T01:42:28Z
38,820,740
<p>It seems pretty likely that the optimizer has replaced the loop with a single constant calculation. See <a href="https://en.wikipedia.org/wiki/Loop_optimization" rel="nofollow">https://en.wikipedia.org/wiki/Loop_optimization</a> for a list of classic loop optimizations. In this case, completely unrolling the loop,...
1
2016-08-08T03:07:47Z
[ "python", "jit" ]
Generate categorised data set from list in O(n)
38,820,229
<p>I am trying to generate a data set with the following structure from a list of items with properties <code>prop1</code> and <code>prop2</code>:</p> <p><code>result[p1][p2] =&gt; list of item with prop1=p1 and prop2=p2</code></p> <p>I have been able to do it in O(n2) with:</p> <pre><code>result = { item.prop1:...
0
2016-08-08T01:45:27Z
38,820,256
<p>You should only have to iterate over the items once:</p> <pre><code>from collections import defaultdict result = defaultdict(lambda: defaultdict(list)) for item in item_list: result[item.prop1][item.prop2].append(item) </code></pre>
2
2016-08-08T01:50:11Z
[ "python", "algorithm" ]
Generate categorised data set from list in O(n)
38,820,229
<p>I am trying to generate a data set with the following structure from a list of items with properties <code>prop1</code> and <code>prop2</code>:</p> <p><code>result[p1][p2] =&gt; list of item with prop1=p1 and prop2=p2</code></p> <p>I have been able to do it in O(n2) with:</p> <pre><code>result = { item.prop1:...
0
2016-08-08T01:45:27Z
38,820,310
<p>A solution using a <code>dict</code> (as opposed to a <code>defaultdict</code>):</p> <pre><code>result = {} for item in item_list: result.setdefault(item.prop1, {}).setdefault(item.prop2, []).append(item) </code></pre>
1
2016-08-08T01:56:48Z
[ "python", "algorithm" ]
Python - Printing and Classes
38,820,311
<p>I've read more posts and documentation on <code>__str__</code> and <code>__repr__</code> than is healthy, consulted various texts, and still cannot resolve this printing issue, so I'm putting this out there. </p> <p>Below is a function I'd like to test. The code isn't mine, but I would like to know how exactly it ...
-1
2016-08-08T01:57:20Z
38,820,891
<p>As per your comment, you are printing these within a list. The <code>print</code> function retrieves the string representation of each argument to be printed, defined by <code>__str__</code>. The string representation of a list consists of square brackets enclosing a comma+space-separated sequence of the <code>repr<...
1
2016-08-08T03:28:09Z
[ "python", "python-2.7", "oop", "methods", "printing" ]
Faster way to remove a dictionary of phrase from a list of string using Python
38,820,345
<p>I have to remove a dictionary of phrase from a list of string using Python</p> <p>A list of strings L1. Example: <code>L1 = ['Programmer New York', 'Programmer San Francisco']</code></p> <p>A dictionary of phrase L2 (all of them are more than one word). Example: <code>L2={'New York', 'San Francisco'}</code></p> <...
0
2016-08-08T02:03:25Z
38,820,619
<p>Try using map() and re,</p> <pre><code>import re res = map(lambda i, j: re.sub(" "+i, '', j), L2, L1) </code></pre> <p>The double quotes before the i are there to eliminate the trailing space after programmer.</p> <pre><code>return list(res) </code></pre> <p>P.S. returning a list explicitly is only necessary if ...
1
2016-08-08T02:46:10Z
[ "python" ]
Faster way to remove a dictionary of phrase from a list of string using Python
38,820,345
<p>I have to remove a dictionary of phrase from a list of string using Python</p> <p>A list of strings L1. Example: <code>L1 = ['Programmer New York', 'Programmer San Francisco']</code></p> <p>A dictionary of phrase L2 (all of them are more than one word). Example: <code>L2={'New York', 'San Francisco'}</code></p> <...
0
2016-08-08T02:03:25Z
38,820,713
<p>You can use list comprehension to do so as:</p> <pre><code>l1 = ['Programmer New York', 'Programmer San Francisco'] l2=['New York', 'San Francisco'] a=[x.split(y) for x in l1 for y in l2 if y in x] res=["".join(x) for x in a] </code></pre>
0
2016-08-08T03:02:33Z
[ "python" ]
How to specify log file name with spider's name in scrapy?
38,820,540
<p>I'm using scrapy,in my scrapy project,I created several spider classes,as the official document said,I used this way to specify log file name: </p> <pre><code> def logging_to_file(file_name): """ @rtype: logging @type file_name:str @param file_name: @return: """ import logging from scrapy.utils.log import configur...
0
2016-08-08T02:33:27Z
38,823,821
<p>It's because you initiate <code>logging_to_file</code> every time when you load up your package. You are using a class variable here where you should use instance variable.</p> <p>When python loads in your package or module ir loads every class and so on.</p> <pre><code>class MyClass: # everything you do here ...
1
2016-08-08T07:49:06Z
[ "python", "scrapy" ]
Python: Installing gooey using pip error
38,820,550
<p>I am trying to install Gooey for python and I keep on getting this error in cmd ... I installed the latest version of pip and am running on the latest version of python:</p> <pre><code>C:\Users\markj&gt;pip install Gooey Collecting Gooey Using cached Gooey-0.9.2.3.zip Complete output from command python setup...
0
2016-08-08T02:34:50Z
38,820,637
<p>You could try downloading the .zip file from the official website here <a href="http://chriskiehl.github.io/Gooey/" rel="nofollow">http://chriskiehl.github.io/Gooey/</a> and try downloading it to see if that will work.</p>
1
2016-08-08T02:50:18Z
[ "python", "cmd", "install", "pip" ]
Python: Installing gooey using pip error
38,820,550
<p>I am trying to install Gooey for python and I keep on getting this error in cmd ... I installed the latest version of pip and am running on the latest version of python:</p> <pre><code>C:\Users\markj&gt;pip install Gooey Collecting Gooey Using cached Gooey-0.9.2.3.zip Complete output from command python setup...
0
2016-08-08T02:34:50Z
38,820,739
<p>You're probably running the package under python 3 which is not fully compatible with the package. </p> <p>That exception means your python can't understand the syntax. In python 3 the comma (<code>,</code>) <a href="https://www.python.org/dev/peps/pep-3110/#grammar-changes" rel="nofollow">is not allowed</a>, corre...
0
2016-08-08T03:07:44Z
[ "python", "cmd", "install", "pip" ]
Printing specific records - error message says String indices must be integer
38,820,554
<p>I am struggling with a solution to my python code.<br> I want to print specific column_names (e.g. <strong>Date</strong>, <strong>Open</strong> etc...). When I attempt to print the <strong>Date</strong> record I get an error <code>String indices must be integers</code>. Below is a copy of my code and the json file....
0
2016-08-08T02:35:27Z
38,820,600
<p><code>"dataset_code"</code> is a string.</p> <p>When you do <code>data['dataset']['dataset_code']</code>, the result is <code>"FB"</code>. <code>"FB"</code> is a string, and therefore can't be indexed by another string. <code>data['dataset']['dataset_code']['Date']</code> is, in your example file, equivalent to <co...
1
2016-08-08T02:42:17Z
[ "python" ]
Can't get AJAX POST working in Django
38,820,720
<p>I can't do a POST ajax request in Django. If I do a GET request, it works fine. I think it may be a csrf token problem, but I can get it to work</p> <p>My view:</p> <pre><code>@login_required def add_share_points(request): user = request.user profile = request.user.profile if request.method == 'POST':...
0
2016-08-08T03:04:17Z
38,833,785
<p>I will point out several things to correct, some are just ways to do it in a django manner and not problems.</p> <p><strong>In your view</strong></p> <pre><code> return HttpResponse( json.dumps({'result': 'ok',}), content_type="application/json" ) </code></pre> <p><strong>In your a...
2
2016-08-08T16:01:58Z
[ "python", "ajax", "django", "python-3.x" ]
AttributeError: 'str' object has no attribute 'get' error in code
38,820,735
<p>I'm trying to make a login style screen and have the frame behind raised if the password matches I get the error <code>AttributeError: 'str' object has no attribute 'get'</code> when I run my program :</p> <pre><code>class StartPage(tk.Frame): entry = "placeholder" def framechange(self): if self.ent...
0
2016-08-08T03:06:06Z
38,820,747
<p>There are no <code>get()</code> requests called from inside the class. Also, you are missing a <code>self</code> in your input statement:</p> <p>Try:</p> <pre><code>class StartPage(tk.Frame): entry = "placeholder" def framechange(self): if self.entry == "password": # Changed command = l...
0
2016-08-08T03:08:34Z
[ "python", "get" ]
Denoise and filter an image
38,820,743
<p>I am doing a <strong>license-plate recognition</strong>. I have crop out the plate but it is very <strong>blurred</strong>. Therefore I cannot split out the digits/characters and recognize it.</p> <p>Here is my image:</p> <p><a href="http://i.stack.imgur.com/qQ8CF.jpg"><img src="http://i.stack.imgur.com/qQ8CF.jpg"...
9
2016-08-08T03:08:06Z
38,959,356
<p>First, this image seems to be more defaced by blur, than by noize, so there are no good reasons to denoise it, try debluring instead. </p> <p>The simplest would be inverse filtering or even Wiener filtering. Then you'll need to separate image's background from letters by the level of luminosity for example with wat...
6
2016-08-15T16:49:36Z
[ "python", "image", "opencv", "image-processing", "scikit-image" ]
Denoise and filter an image
38,820,743
<p>I am doing a <strong>license-plate recognition</strong>. I have crop out the plate but it is very <strong>blurred</strong>. Therefore I cannot split out the digits/characters and recognize it.</p> <p>Here is my image:</p> <p><a href="http://i.stack.imgur.com/qQ8CF.jpg"><img src="http://i.stack.imgur.com/qQ8CF.jpg"...
9
2016-08-08T03:08:06Z
38,971,196
<p>I concur with the opinion that you should probably try to optimize the input image quality.</p> <p>Number plate blur is a typical example of motion blur. How well you can deblur depends upon how big or small is the blur radius. Generally greater the speed of the vehicle, larger the blur radius and therefore more d...
7
2016-08-16T09:27:06Z
[ "python", "image", "opencv", "image-processing", "scikit-image" ]
Denoise and filter an image
38,820,743
<p>I am doing a <strong>license-plate recognition</strong>. I have crop out the plate but it is very <strong>blurred</strong>. Therefore I cannot split out the digits/characters and recognize it.</p> <p>Here is my image:</p> <p><a href="http://i.stack.imgur.com/qQ8CF.jpg"><img src="http://i.stack.imgur.com/qQ8CF.jpg"...
9
2016-08-08T03:08:06Z
38,987,741
<p><a href="http://i.stack.imgur.com/aHPAa.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/aHPAa.jpg" alt="result using ChanVeseBinarize with binarized kernel "></a></p> <p>ChanVeseBinarize with an image enhanced binarized kernel gave me this result. This is helpful to highlight 4,8,1 and 2. I guess you need to...
1
2016-08-17T03:40:07Z
[ "python", "image", "opencv", "image-processing", "scikit-image" ]
Convert all columns in a Dataframe to a single secondary index in a MultiIndex Dataframe
38,820,879
<p>I have a dataframe called Pop that looks like the following (Sorry, this doesn't format very well, but it's a single Index DataFrame (State is the index) with columns for each year. I only put a small sample of the data):</p> <pre><code> 2007 2008 2009 State Alabama 46...
0
2016-08-08T03:26:50Z
38,821,117
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow">melt</a> to convert columns into rows :</p> <pre><code>In [10]: df Out[10]: state 2007 2008 2009 0 Alabama 4637904 4677464 4708708 1 Maine 1234567 1432765 1432567 2 Flori...
1
2016-08-08T04:02:54Z
[ "python", "dataframe", "multi-index" ]
Invert first byte in file
38,820,954
<p>What is the most pythonic way to change first byte of file to its inversion copy? Now, I use this code:</p> <pre><code>with open(file_path, 'r+b') as f: b = bytearray(f.read(1)) b[0] = ~b[0] &amp; 255 f.seek(0) f.write(b) </code></pre>
1
2016-08-08T03:37:38Z
38,821,127
<p>Here's an alternative that uses a memory-mapped file:</p> <pre><code>import mmap with open(file_path, 'r+b') as f, mmap.mmap(f.fileno(), 1) as mm: mm[0] ^= 255 </code></pre>
2
2016-08-08T04:04:20Z
[ "python", "python-3.x" ]
Import large CSV file with utf-8(Chinese chars) contents in Python 3.5
38,820,981
<p>First of all, I know there is a standard way of doing the task I state in the title. For example, </p> <pre class="lang-python prettyprint-override"><code>import csv with open('test.txt', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: print(row) </code></pre> <p>I apply this code...
0
2016-08-08T03:42:14Z
38,822,652
<p>It is not a precise answer to the question. </p> <p>It turns out that the original data file -- although it contains unicode characters -- was encoded with ASCII. So I save a new data file and encode it with utf-8, and the standard method of reading CSV file just worked.</p>
0
2016-08-08T06:35:59Z
[ "python", "csv", "utf-8" ]
Scrapy Pull Same Data from Multiple Pages
38,821,027
<p>This is related to the previous question I wrote <a href="http://stackoverflow.com/questions/38781357/pro-football-reference-team-stats-xpath/38781659#38781659">here</a>. I am trying to pull the same data from multiple pages on the same domain. A small explanation, I'm trying to pull data like offensive yards, tur...
1
2016-08-08T03:49:32Z
38,821,054
<p>The subsequent requests you make <em>are filtered as offsite</em>, fix your <code>allowed_domains</code> setting:</p> <pre><code>allowed_domains = ['pro-football-reference.com'] </code></pre> <p>Worked for me.</p>
1
2016-08-08T03:52:45Z
[ "python", "scrapy" ]
Connecting to google using python stays blank
38,821,114
<p>I am learning python and I am running into an issue</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get('http://www.google.com') </code></pre> <p>my firefox launches but it does not go on google.com like it is supposed to be but rather stays as a blank page.</p>
2
2016-08-08T04:02:23Z
38,822,551
<p>I would recommend using chrome instead because your script does work. so... <a href="http://chromedriver.storage.googleapis.com/2.9/chromedriver_win32.zip" rel="nofollow">http://chromedriver.storage.googleapis.com/2.9/chromedriver_win32.zip</a> Download that and extract it to your <code>python27/scripts</code> folde...
0
2016-08-08T06:30:05Z
[ "python", "selenium", "firefox" ]
Python Multiprocessing using Process: Consuming Large Memory
38,821,247
<p>I am running multiple processes from single python code:</p> <p>Code Snippet:</p> <pre><code>while 1: if sqsObject.msgCount() &gt; 0: ReadyMsg = sqsObject.readM2Q() if ReadyMsg == 0: continue fileName = ReadyMsg['fileName'] dirName = ReadyMsg['dirName'] uuid ...
0
2016-08-08T04:18:55Z
38,821,501
<blockquote> <p>Not sure what is wrong in the process. </p> </blockquote> <p>It appears you are creating as many processes as there are messages, even when the maxProcess count is reached.</p> <blockquote> <p>I am thinking I have leak by reusing the process slots.</p> </blockquote> <p>There is no need to manage ...
0
2016-08-08T04:51:58Z
[ "python", "memory-leaks", "python-multiprocessing" ]
Python Multiprocessing using Process: Consuming Large Memory
38,821,247
<p>I am running multiple processes from single python code:</p> <p>Code Snippet:</p> <pre><code>while 1: if sqsObject.msgCount() &gt; 0: ReadyMsg = sqsObject.readM2Q() if ReadyMsg == 0: continue fileName = ReadyMsg['fileName'] dirName = ReadyMsg['dirName'] uuid ...
0
2016-08-08T04:18:55Z
38,821,785
<p>Your code is, in a word, weird :-)</p> <p>It's not <a href="http://stackoverflow.com/help/mcve">an mvce</a>, so no one else can test it, but just looking at it, you have this (slightly simplified) structure in the inner loop:</p> <pre><code>if count &lt; limit: ... start a new process, and increment count ... ...
0
2016-08-08T05:21:31Z
[ "python", "memory-leaks", "python-multiprocessing" ]
Scrapy Installation - Issue with lxml install
38,821,297
<p>I am new to Python and I am trying to install scrapy, I have python 2.7.12 and pip 8.1.2 on windows 10. when I give the command 'pip install scrapy' it tries to install lxml and gives the below error. I downloaded the libxml2 binary, extracted to a folder and added the bin folder in path variable.But still the same ...
0
2016-08-08T04:26:24Z
38,822,808
<p>Scrapy's docummentation <a href="http://doc.scrapy.org/en/latest/intro/install.html#anaconda" rel="nofollow">recommends using Anaconda</a> to install the package. Lxml package is really tricky to install on windows and anaconda is a really straigh-forward shortcut. </p> <p>There's also unnoficial binaries of lxml...
0
2016-08-08T06:48:03Z
[ "python", "scrapy", "lxml", "libxml2", "failed-installation" ]
RS-232 Device Echoing All Serial Writes in PySerial
38,821,350
<p>My Python 2.7 program is using pySerial to communicate with a RS232/RS485 device (<a href="http://www.lesker.com/newweb/gauges/pdf/manuals/375usermanual.pdf" rel="nofollow">manual here, page 40</a>).</p> <p><strong>Problem:</strong> However it appears that everything that is written to the serial port is being echo...
0
2016-08-08T04:34:05Z
39,060,400
<p>If your sending a string use a carriage return, not newline. You might have to use a carriage return to wake up the device before sending the command. Then strip out the extra characters on the print out statement. </p> <blockquote> <blockquote> <p>run cmd_send(x)</p> </blockquote> </blockquote> <p>x = '#...
0
2016-08-21T02:41:09Z
[ "python", "serialization", "pyserial" ]
sorting a python list by frequency of elements
38,821,352
<p>I have this code which sorts python list by frequency of elements. It works for all other cases except when frequency of two elements are same. If the frequency is same then I want to place smaller value first before higher value:</p> <pre><code>counts = collections.Counter(arr) new_list = sorted(arr, key=lambda x:...
1
2016-08-08T04:34:22Z
38,821,366
<p>You can set your key lambda function to a tuple, so, It will sort by <code>counts[x]</code> first and if there is a tie, it will sort by <code>x</code>, the value itself.</p> <pre><code> new_list = sorted(arr, key=lambda x: (counts[x], x)) </code></pre>
2
2016-08-08T04:35:46Z
[ "python", "list", "sorting" ]
sorting a python list by frequency of elements
38,821,352
<p>I have this code which sorts python list by frequency of elements. It works for all other cases except when frequency of two elements are same. If the frequency is same then I want to place smaller value first before higher value:</p> <pre><code>counts = collections.Counter(arr) new_list = sorted(arr, key=lambda x:...
1
2016-08-08T04:34:22Z
38,821,392
<p>You are only sorting by the number of item. Under this logic, all the items which appear once have the same "weight", so python retains their original relevant position. E.g., <code>3</code> and <code>1</code> both appear once, so as far as their sorting is concerned, they are equivalent. Since <code>3</code> comes ...
1
2016-08-08T04:39:33Z
[ "python", "list", "sorting" ]
How to get response page after auth in selenium?
38,821,391
<p>I need to get response page after form submit, but i have same page with empty form fields. I am trying use <code>time.sleep()</code>, but it dosen`t help.</p> <pre><code>from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import time phantom_js_executable_path = './bin/phantomjs.exe' us...
0
2016-08-08T04:39:25Z
38,821,465
<p>You need to wait for an element in the page that you get after submitting user name and password.</p> <pre><code>ff = webdriver.Firefox() ff.get("http://somedomain/url_that_delays_loading") try: element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement"))) finally: ff.qu...
0
2016-08-08T04:47:23Z
[ "python", "selenium" ]
How to get response page after auth in selenium?
38,821,391
<p>I need to get response page after form submit, but i have same page with empty form fields. I am trying use <code>time.sleep()</code>, but it dosen`t help.</p> <pre><code>from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import time phantom_js_executable_path = './bin/phantomjs.exe' us...
0
2016-08-08T04:39:25Z
38,823,481
<p>The following code will wait for an element to appear after your submit and will fail if the element is not located.</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait(self.driver, 10).until( EC.prese...
0
2016-08-08T07:28:36Z
[ "python", "selenium" ]