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 |
|---|---|---|---|---|---|---|---|---|---|
Error Executing Stored Procedure that References Linked Server with PyMSSQL | 38,837,327 | <p>I'm trying to execute a stored procedure from a python script, via pymssql, that communicates with a linked server. The SP works when run manually, but when run from the python script errors out with:</p>
<pre><code>(7391, 'The operation could not be performed because OLE DB
provider"SQLNCLI11" for linked server ... | 1 | 2016-08-08T19:45:13Z | 38,839,207 | <p>I was able to recreate the issue with an SP that tried to do an UPDATE on the linked server, e.g., </p>
<pre class="lang-sql prettyprint-override"><code>UPDATE LINKEDSERVERNAME...TableName SET ...
</code></pre>
<p>although my error message was slightly different</p>
<blockquote>
<p>(8501, "MSDTC on server 'PANO... | 2 | 2016-08-08T22:04:18Z | [
"python",
"sql-server",
"pymssql"
] |
Simple way to plot time series with real dates using pandas | 38,837,421 | <p>Starting from the following CSV data, loaded into a pandas data frame...</p>
<pre><code>Buchung;Betrag;Saldo
27.06.2016;-1.000,00;42.374,95
02.06.2016;500,00;43.374,95
01.06.2016;-1.000,00;42.874,95
13.05.2016;-500,00;43.874,95
02.05.2016;500,00;44.374,95
04.04.2016;500,00;43.874,95
02.03.2016;500,00;43.374,95
10.0... | 0 | 2016-08-08T19:51:09Z | 38,837,506 | <p>You need to convert your date column into the correct format:</p>
<pre><code>data['Buchung'] = pd.to_datetime(data['Buchung'], format='%d.%m.%Y')
</code></pre>
<p>Now your plot will work.</p>
<hr>
<p>Though you didn't ask, I think you will also run into a similar problem because your numbers (in <code>'Betrag'</... | 2 | 2016-08-08T19:56:26Z | [
"python",
"pandas",
"plot",
"time-series",
"seaborn"
] |
Python threads repeating values | 38,837,428 | <p>I am trying to write a python SHA512 brute forcer.</p>
<p>I use a Queue to store the values in the wordlist and then compare them against the encrypted hash.</p>
<p>The problem is that, instead of the values being popped out of the Queue, they are reused by other threads. So basically, instead of having the whole... | 0 | 2016-08-08T19:51:49Z | 38,837,659 | <p>This can be solved using the classic producer and consumer problem. You may find <a href="http://www.napuzba.com/story/producer-consumer-python/" rel="nofollow">Solution to producer and consumer problem in python</a> useful. </p>
| 0 | 2016-08-08T20:06:48Z | [
"python",
"multithreading",
"queue"
] |
Python threads repeating values | 38,837,428 | <p>I am trying to write a python SHA512 brute forcer.</p>
<p>I use a Queue to store the values in the wordlist and then compare them against the encrypted hash.</p>
<p>The problem is that, instead of the values being popped out of the Queue, they are reused by other threads. So basically, instead of having the whole... | 0 | 2016-08-08T19:51:49Z | 38,837,762 | <p>Let's look at this block of code :</p>
<pre><code>for i in range(threads):
t = threading.Thread(target=testPass,args=(cryptPass,user))
t.daemon = True
t.start()
</code></pre>
<p>And let's describe what this is doing for each thread you start : </p>
<ol>
<li><strong>create a new <code>Queue</code> obje... | 0 | 2016-08-08T20:15:04Z | [
"python",
"multithreading",
"queue"
] |
Update a dictionary value using python | 38,837,507 | <p>I have a json file, which when loaded in python using <code>json.loads()</code> becomes a <code>dictionary</code>. The json data is a <code>nested dictionary</code> which can contain a <code>'groups'</code> key inside another <code>'groups'</code> key. The values inside the <code>'groups'</code> key are a <code>'nam... | -3 | 2016-08-08T19:56:32Z | 38,839,283 | <p>A way to implement this recursive solution is with backtracking. When no more <code>'groups'</code> keys are are found nested inside the root key, the <code>'name'</code> key value is matched with <code>groups_name</code> parameter, which is 'SportCar' in our case. If this condition is satisfied check for the values... | 2 | 2016-08-08T22:11:54Z | [
"python",
"json"
] |
Django HTTP_HOST errors on AWS EC2 behind Load Balancer | 38,837,512 | <p>I have a Django app, using Apache and mod_wsgi running on an EC2 instance behind an AWS ELB balancer. The balancer maps SSL traffic (port 443) to port 8080 on the EC2 instance. Apache has a VirtualHost configured on port 8080 to serve the Django app, with ServerName set to the domain name for the website. Django run... | 1 | 2016-08-08T19:57:01Z | 38,837,931 | <p>I would suggest you only allow traffic on your EC2 instance from the load balancer using a security group AND the IP address of your office/home if you SSH'ing into the EC2 instance.</p>
<p><a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-security-groups.html#elb-vpc-instance-secur... | 1 | 2016-08-08T20:26:00Z | [
"python",
"django",
"apache",
"amazon-web-services",
"amazon-ec2"
] |
Getting the resource schedule from Office 365? | 38,837,540 | <p>I had a python script which could get fetch the schedule for a resource(room) from the company's Office 365 calendar by calling
<code>https://outlook.office365.com/api/v1.0/users/<roomName@companyName.com>/calendarview?startDateTime=2016-08-07 22:00:00&endDateTime=2016-08-08 22:00:00</code></p>
<p>This d... | 0 | 2016-08-08T19:59:25Z | 38,844,108 | <p>What's the error message you get? If you were getting the error like <code>The access token is acquired using an authentication method that is too weak to allow access for this application</code>, we need to use the certificate make to request the token instead of using the client id and secret. </p>
<p>Here is an ... | 0 | 2016-08-09T06:58:32Z | [
"c#",
"python",
"office365",
"office365api"
] |
How to properly read strings from SQL Database with NumPy | 38,837,569 | <p>I have a dataset which I am querying with SQL. My query returns a long string which simply contains the column names and then the data, with rows separated by newline characters. I then use <code>numpy.genfromtxt</code> to turn this long string into a numpy array.</p>
<p>However, there are a few columns that should... | 0 | 2016-08-08T20:01:08Z | 38,838,417 | <p>I'm guessing at how you're using genfromtxt, but this seems to work?</p>
<pre><code>import numpy as np
from StringIO import StringIO
s = b'bestObjID,ra,dec,z,zErr,zWarning,class,subClass,rChi2,DOF,rChi2Diff,z_noqso,zErr_noqso,zWarning_noqso,class_noqso,subClass_noqso,rChi2Diff_noqso,velDisp,velDispErr,velDispZ,vel... | 1 | 2016-08-08T20:58:08Z | [
"python",
"mysql",
"string",
"numpy"
] |
Changing time format in template is raising exception | 38,837,638 | <p>I can't figure out why <code>Django</code> returns <code>Exception</code> when I try to set time format in template. </p>
<p>This is a column in <code>Django-tables2</code> table.</p>
<pre><code>time_arrival = tables.TemplateColumn('{{record.time_arrival|time: "H:i"}}',verbose_name=u'Äas prÃchodu')
</code></pre>... | 0 | 2016-08-08T20:05:55Z | 38,837,695 | <p>Remove the space between <code>time:</code> and <code>"H:i"</code></p>
<pre><code>'{{record.time_arrival|time:"H:i"}}'
</code></pre>
| 2 | 2016-08-08T20:09:56Z | [
"python",
"django",
"django-templates"
] |
QT QFileSystemWatcher | 38,837,668 | <p>It seems simple but it doesn't work. I have usbautomount installed.</p>
<pre><code>#Watch the media directory and connect to enable save csv pb
self.usb_watcher = QFileSystemWatcher()
self.usb_watcher.addPaths(["/media/usb0"])
self.usb_watcher.directoryChanged.connect(self.enable_save_csv_pb)
self.usb_watcher.file... | -1 | 2016-08-08T20:07:14Z | 38,837,976 | <p>I think you should use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qfilesystemwatcher.html#addPath" rel="nofollow">addPath</a> instead of <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qfilesystemwatcher.html#addPaths" rel="nofollow">addPaths</a></p>
| 0 | 2016-08-08T20:29:09Z | [
"python",
"linux",
"pyqt",
"qt4"
] |
How to determine the functions available in DLL for use in Python | 38,837,849 | <p>A <a href="http://www.brooksinstrument.com/products/accessories-software/product-software/brooks-labview-dll" rel="nofollow">LabView dll file</a> is to be used from a Python 2.7 script. What can we do to figure out which are the methods in the DLL file that we can call from Python, without having to load the dll in ... | 2 | 2016-08-08T20:20:41Z | 39,337,307 | <p>What I understand is, that you are using a third party DLL created with LabView. In this case the LabView runtime has to be installed to use it which can be installed for free: <a href="http://digital.ni.com/public.nsf/allkb/B727BE0152F606D486256A22004DE82D" rel="nofollow">http://digital.ni.com/public.nsf/allkb/B727... | 0 | 2016-09-05T20:29:48Z | [
"python",
"python-2.7",
"dll",
"labview"
] |
Restart script on error | 38,837,851 | <p>so I have this script in selenium, that it sometimes crashes for various reasons. Sometimes it fails to click a button, gets confused, gets messed up and displays an error.</p>
<p>How can I command the script, so whenever it crashes, to re-run the script from the beginning again? I've heard about <code>try</code> a... | 0 | 2016-08-08T20:20:44Z | 38,838,161 | <p>generic answer to retry on any exception:</p>
<pre><code>while True:
try:
# run your selenium code which sometimes breaks
pass
except Exception as e:
print("something went wrong: "+repr(e))
</code></pre>
<p>you may try to refine the exception type to avoid retrying say, because of a python ... | 0 | 2016-08-08T20:42:03Z | [
"python",
"selenium"
] |
Numpy Uniform Distribution With Decay | 38,837,860 | <p>I'm trying to construct a matrix of uniform distributions decaying to 0 at the same rate in each row. The distributions should be between -1 and 1. What I'm looking at is to construct something that resembles:</p>
<pre><code>[[0.454/exp(0) -0.032/exp(1) 0.641/exp(2)...]
[-0.234/exp(0) 0.921/exp(1) 0.049/exp(2)...]... | 2 | 2016-08-08T20:21:33Z | 38,837,956 | <p>Alok Singhal's answer is best, but as another way to do this (perhaps more explicit)
you can duplicate the vector <code>[exp(0), ...,exp(9)]</code> and stack them all into matrix by doing an outer product with a vector of ones. Then divide the 'w' matrix by the new 'decay' matrix.</p>
<pre><code>n=10
w = np.array([... | 1 | 2016-08-08T20:28:02Z | [
"python",
"numpy"
] |
Numpy Uniform Distribution With Decay | 38,837,860 | <p>I'm trying to construct a matrix of uniform distributions decaying to 0 at the same rate in each row. The distributions should be between -1 and 1. What I'm looking at is to construct something that resembles:</p>
<pre><code>[[0.454/exp(0) -0.032/exp(1) 0.641/exp(2)...]
[-0.234/exp(0) 0.921/exp(1) 0.049/exp(2)...]... | 2 | 2016-08-08T20:21:33Z | 38,838,074 | <p>You can use numpy's broadcasting feature to do this:</p>
<pre><code>w = np.random.uniform(-1, 1, size=(10, 10))
weights = np.exp(np.arange(10))
w /= weights
</code></pre>
| 6 | 2016-08-08T20:35:10Z | [
"python",
"numpy"
] |
truncated incorrect value | 38,837,910 | <p>I have a python code that displays a range of dates. In the code below I have passed the dates in the select operation by casting the dates and using STR_TO_DATE function. I want to know how a range of values with start and end date can be passed in the query below. what i want to achieve is to give a range of dates... | -2 | 2016-08-08T20:24:23Z | 38,838,424 | <p>First off, <strong>Please include your error in your question</strong>. This makes it easier for people to help you. </p>
<p>I'm gussing from the title that your trying to do something like: </p>
<pre><code>s = "string"
l = ["list", "list2"]
print(l + s)
</code></pre>
<p>That is incorrect. You can't add a variabl... | 0 | 2016-08-08T20:58:41Z | [
"python",
"mysql",
"python-2.7",
"mysql-python"
] |
truncated incorrect value | 38,837,910 | <p>I have a python code that displays a range of dates. In the code below I have passed the dates in the select operation by casting the dates and using STR_TO_DATE function. I want to know how a range of values with start and end date can be passed in the query below. what i want to achieve is to give a range of dates... | -2 | 2016-08-08T20:24:23Z | 38,859,741 | <p>The correct way to convert date from varchar to date datatype and then perform select operation is as shown:</p>
<p>message = """SELECT stationId,datecol,airTemperature FROM cimishourly
WHERE STR_TO_DATE(datecol, '%m/%d/%Y')
BETWEEN STR_TO_DATE('8/10/2015', '%m/%d/%Y')
AND STR_TO_DATE('8/12/2015', '%m/%d/%Y')... | 0 | 2016-08-09T20:21:19Z | [
"python",
"mysql",
"python-2.7",
"mysql-python"
] |
psycopg for python 3? Unable to find vcvarsall.bat error | 38,837,920 | <p>I'm trying to install psycopg on my computer; I have Python3.5 and PostgreSQL9.5.3 installed. I get the error <code>Unable to find vcvarsall.bat error</code> when typing <code>python setup.py build</code> on cmd. Having read some answers, it appeared to me, that the 3rd python's version is what might have caused the... | 0 | 2016-08-08T20:24:55Z | 38,862,648 | <p><a href="http://www.stickpeople.com/projects/python/win-psycopg/" rel="nofollow">This</a> helped. Downloaded Python 3.5 release.</p>
| 0 | 2016-08-10T00:58:36Z | [
"python",
"postgresql",
"psycopg2",
"psycopg"
] |
Scrapy shell returning blank array with steam website? | 38,837,921 | <p>I've used scrapy before to some success with craiglist, but now that I'm trying to scrape steam for user names arbitrarily, I keep getting a blank array in the scrapy shell.</p>
<p>The user name element (which is xempy for example) is contained in:</p>
<pre><code><a class="searchPersonaName" href="https://steam... | 1 | 2016-08-08T20:24:59Z | 38,838,395 | <p>If you look at the actual source in your browser, right click and choose view source you will see no sign of the results, the data is dynamically added through an ajax request to <em><a href="https://steamcommunity.com/search/SearchCommunityAjax" rel="nofollow">https://steamcommunity.com/search/SearchCommunityAjax<... | 0 | 2016-08-08T20:56:51Z | [
"python",
"scrapy"
] |
Sympy's latex printer, folding short fractions | 38,837,942 | <p>I'm feeding <code>sympy.latex</code> a string involving fractions and I'd like to get its latex representation with fractions "folded", i.e., typeset as 3/2 rather than as \frac{3}{2}. I'm setting the <code>fold_short_fractions</code> keyword argument to <code>True</code>, but the results I'm getting are inconsisten... | 2 | 2016-08-08T20:26:45Z | 38,858,641 | <p>This is a bug in the SymPy latex printer. It isn't looking at the <code>fold_short_frac</code> option for rational numbers. I've got a fix <a href="https://github.com/sympy/sympy/pull/11497" rel="nofollow">here</a>. </p>
<p>In the meantime, you can use this is as workaround:</p>
<pre><code>from sympy.printing.late... | 0 | 2016-08-09T19:08:51Z | [
"python",
"latex",
"sympy"
] |
Python multiprocessing numpy.linalg.pinv cause segfault | 38,837,948 | <p>I wrote a function using multiprocessing packages from python and tried to boost the speed of my code. </p>
<pre><code>from arch.univariate import ARX, GARCH
from multiprocessing import Process
import multiprocessing
import time
def batch_learning(X, lag_array=None):
"""
X is a time series array
lag_ar... | 1 | 2016-08-08T20:27:38Z | 38,840,759 | <p>There's not much to go on here, and the code indentation is wrong so it's hard to guess what you're really doing. To the extent I <em>can</em> guess, what you're seeing could happen if the OS killed a process in a way that didn't raise a Python exception.</p>
<p>One thing to try: first make a list, <code>ps</code... | 0 | 2016-08-09T01:39:13Z | [
"python",
"numpy",
"python-multiprocessing",
"statsmodels"
] |
Python multiprocessing numpy.linalg.pinv cause segfault | 38,837,948 | <p>I wrote a function using multiprocessing packages from python and tried to boost the speed of my code. </p>
<pre><code>from arch.univariate import ARX, GARCH
from multiprocessing import Process
import multiprocessing
import time
def batch_learning(X, lag_array=None):
"""
X is a time series array
lag_ar... | 1 | 2016-08-08T20:27:38Z | 38,950,680 | <p>I have to answer this question by myself and providing my solutions. I have already solved this issue, thanks to the help from @Tim Peters and @aganders. </p>
<p>The multiprocessing usually hangs when you use numpy/scipy libraries on Mac OS because of the Accelerate Framework used in Apple OS which is a replacement... | 1 | 2016-08-15T07:07:42Z | [
"python",
"numpy",
"python-multiprocessing",
"statsmodels"
] |
How can I print two boxplots on the same axis in python? | 38,837,958 | <p>I'm using matplotlib to graph two boxplots. I am able to get them printed as subplots on the same figure, but I am having trouble getting them side by side on the same set of axes. </p>
| -2 | 2016-08-08T20:28:22Z | 38,838,131 | <p>Here's the code which finally worked: </p>
<pre><code>fig, axes = plt.subplots(nrows=1, ncols=2)
axes[0].boxplot(mads_dp52)
axes[1].boxplot(mads_dp53)
plt.show()
</code></pre>
| 0 | 2016-08-08T20:39:33Z | [
"python",
"matplotlib",
"boxplot",
"axes"
] |
Slicing strings in a column in pandas | 38,838,015 | <p>I have a CSV that has a column of URLs and I'm trying to slice out some unnecessary characters leading and trailing characters. I'm using the following syntax:</p>
<pre><code>df.['column_name'].str[3:10]
</code></pre>
<p>Unfortunately I get <code>TypeError: 'method' object is not subscriptable</code>.</p>
| 3 | 2016-08-08T20:31:21Z | 38,838,066 | <p>try this</p>
<pre><code>df['new_column'] = df['text_column'].apply(lambda x: x[3:10])
</code></pre>
| 0 | 2016-08-08T20:34:45Z | [
"python",
"csv",
"pandas"
] |
Pandas equivalent rbind operation | 38,838,059 | <p>Basically, I am looping through a bunch of CSV files and in the end would like to <code>append</code> each dataframe into one. Actually, all I need is an <code>rbind</code> type function. So, I did some search and followed the <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">guide</a... | 2 | 2016-08-08T20:34:31Z | 38,838,160 | <p>Try: <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html?highlight=concat#concat" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/10min.html?highlight=concat#concat</a></p>
<p>"pandas provides various facilities for easily combining together Series, DataFrame, and Panel objects with various k... | 0 | 2016-08-08T20:42:00Z | [
"python",
"pandas"
] |
Pandas equivalent rbind operation | 38,838,059 | <p>Basically, I am looping through a bunch of CSV files and in the end would like to <code>append</code> each dataframe into one. Actually, all I need is an <code>rbind</code> type function. So, I did some search and followed the <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">guide</a... | 2 | 2016-08-08T20:34:31Z | 38,838,233 | <pre><code>>>> df1
a b
0 -1.417866 -0.828749
1 0.212349 0.791048
2 -0.451170 0.628584
3 0.612671 -0.995330
4 0.078460 -0.322976
5 1.244803 1.576373
6 1.169629 -1.135926
7 -0.652443 0.506388
8 0.549604 -0.691054
9 -0.512829 -0.959398
>>> df2
a b
0 -0.65216... | 4 | 2016-08-08T20:46:52Z | [
"python",
"pandas"
] |
Consecutive numbers list where each number repeats | 38,838,147 | <p>How can I create a list of consecutive numbers where each number repeats N times, for example:</p>
<pre><code>list = [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5]
</code></pre>
| 2 | 2016-08-08T20:40:54Z | 38,838,231 | <p>My first instinct is to get some functional help from the funcy package. If <code>N</code> is the number of times to repeat each value, and <code>M</code> is the maximum value to repeat, then you can do</p>
<pre><code>import funcy as fp
fp.flatten(fp.repeat(i, N) for i in range(M + 1))
</code></pre>
<p>This will ... | 1 | 2016-08-08T20:46:41Z | [
"python",
"list",
"python-2.7"
] |
Consecutive numbers list where each number repeats | 38,838,147 | <p>How can I create a list of consecutive numbers where each number repeats N times, for example:</p>
<pre><code>list = [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5]
</code></pre>
| 2 | 2016-08-08T20:40:54Z | 38,838,234 | <p><code>sum([[i]*n for i in range(0,x)], [])</code></p>
| 0 | 2016-08-08T20:47:02Z | [
"python",
"list",
"python-2.7"
] |
Consecutive numbers list where each number repeats | 38,838,147 | <p>How can I create a list of consecutive numbers where each number repeats N times, for example:</p>
<pre><code>list = [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5]
</code></pre>
| 2 | 2016-08-08T20:40:54Z | 38,838,292 | <p>Another idea, without any need for other packages or sums:</p>
<pre><code>[x//N for x in range((M+1)*N)]
</code></pre>
<p>Where <code>N</code> is your number of repeats and <code>M</code> is the maximum value to repeat. E.g.</p>
<pre><code>N = 3
M = 5
[x//N for x in range((M+1)*N)]
</code></pre>
<p>yields</p>
<... | 4 | 2016-08-08T20:51:20Z | [
"python",
"list",
"python-2.7"
] |
Consecutive numbers list where each number repeats | 38,838,147 | <p>How can I create a list of consecutive numbers where each number repeats N times, for example:</p>
<pre><code>list = [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5]
</code></pre>
| 2 | 2016-08-08T20:40:54Z | 38,840,594 | <p>The following piece of code is the simplest version I can think of.
Itâs a bit dirty and long, but it gets the job done.</p>
<p>In my opinion, itâs easier to comprehend.</p>
<pre><code>def mklist(s, n):
l = [] # An empty list that will contain the list of elements
# and their duplicates.
... | 0 | 2016-08-09T01:14:17Z | [
"python",
"list",
"python-2.7"
] |
Understanding NumPy's interpretation of string data types | 38,838,218 | <p>Lets say I have a bytes object that represents some data, and I want to convert it to a <code>numpy</code> array via <code>np.genfromtxt</code>. I am having trouble understanding how I should handle strings in this case. Let's start with the following:</p>
<pre><code>from io import BytesIO
import numpy as np
text ... | 0 | 2016-08-08T20:45:55Z | 38,839,263 | <p>In my Python3 session:</p>
<pre><code>In [568]: text = b'test, 5, 1.2'
# I don't need BytesIO since genfromtxt works with a list of
# byte strings, as from text.splitlines()
In [570]: np.genfromtxt([text], delimiter=',', dtype=None)
Out[570]:
array((b'test', 5, 1.2),
dtype=[('f0', 'S4'), ('f1', '<i4'), ... | 0 | 2016-08-08T22:09:37Z | [
"python",
"arrays",
"string",
"numpy"
] |
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0446' in position 32: ordinal not in range(128) | 38,838,274 | <p>I'm trying to debug some code a previous intern wrote and I'm having some difficulties resolving this issue with answers from other unicode error posts. </p>
<p>The error is found in the last line of this function:</p>
<pre><code> def dumpTextPacket(self, header, bugLog, offset, outfile):
bugLog.seek(of... | -1 | 2016-08-08T20:49:59Z | 38,858,501 | <p>When you add together two strings with one of them being Unicode, Python 2 will coerce the result to Unicode too.</p>
<pre><code>>>> 'a' + u'b'
u'ab'
</code></pre>
<p>Since you used <code>data.decode</code>, <code>outString</code> will be Unicode.</p>
<p>When you write to a binary file, you must have a b... | 0 | 2016-08-09T19:00:57Z | [
"python",
"unicode"
] |
Python methods and "switches" | 38,838,298 | <p>I'm trying to use a dictionary as a switch statement as in </p>
<pre><code>def add(first, second):
return first + second
def sub():
...
return something
operations = {
"Add": add,
"Sub": sub
}
ret_val = operations[operation]
</code></pre>
<p>Now how can I pass the arguments to add and sub an... | 0 | 2016-08-08T20:51:38Z | 38,838,347 | <p>To call a function, put the arguments in parentheses after it, just like when you call a function directly by its name.</p>
<pre><code>ret_val = operations[operation](1, 2)
</code></pre>
<p>Note that for this to work properly, all the functions in <code>operations</code> need to take the same number of arguments. ... | 1 | 2016-08-08T20:54:02Z | [
"python"
] |
Python methods and "switches" | 38,838,298 | <p>I'm trying to use a dictionary as a switch statement as in </p>
<pre><code>def add(first, second):
return first + second
def sub():
...
return something
operations = {
"Add": add,
"Sub": sub
}
ret_val = operations[operation]
</code></pre>
<p>Now how can I pass the arguments to add and sub an... | 0 | 2016-08-08T20:51:38Z | 38,838,370 | <p>The dictionary contains callable functions. To call them, just add the arguments in parentheses.</p>
<pre><code>operations[operation](arg1, ...)
</code></pre>
| 0 | 2016-08-08T20:55:30Z | [
"python"
] |
Python methods and "switches" | 38,838,298 | <p>I'm trying to use a dictionary as a switch statement as in </p>
<pre><code>def add(first, second):
return first + second
def sub():
...
return something
operations = {
"Add": add,
"Sub": sub
}
ret_val = operations[operation]
</code></pre>
<p>Now how can I pass the arguments to add and sub an... | 0 | 2016-08-08T20:51:38Z | 38,838,658 | <p>So, the main thing you're missing is executing the function call. The code as provided grabs the function reference properly, but you need parens to execute it.</p>
<p>Once you execute it, you need some way to pass arguments. Because the number of args varies by function, the best way is to pass both a variable n... | 0 | 2016-08-08T21:16:04Z | [
"python"
] |
Get DOT graphviz of nested list elements which can contain duplicated nodes | 38,838,323 | <p>I have a set of nested lists which can be seperated in three groups:</p>
<ul>
<li><p>A (subelements are disjunction, line colors GREEN), e.g.</p>
<pre><code>listA = {
âa1â: ['b1', 'a2'],
âa2â: ['c1', 'c2']
}
</code></pre></li>
<li><p>B (subelements are <strong>ordered</strong> conjunction, line colors ORA... | 0 | 2016-08-08T20:53:03Z | 38,854,894 | <h1>Duplicate nodes problem</h1>
<p>To avoid the duplicate nodes problem you should name each node with a unique name and use a <code>label</code> for the displayed name. For example change:</p>
<pre><code>b2 -> b1 [color="orange"]
b1 -> c4 [color="orange"]
b1 -> c5 [color="orange"]
b1 -> c7 [color="orang... | 1 | 2016-08-09T15:31:41Z | [
"python",
"graphviz",
"decision-tree",
"dot",
"pygraphviz"
] |
How to override event (dropEvent) of a widget in dynamic UI of PyQt? | 38,838,354 | <p><strong>What am I doing/ What I have so far :</strong></p>
<p>I am using Qt-designer to create PyQt .ui file which I am loading in my python script using QUiLoader which gives me access to the widgets/components as :</p>
<pre><code>self.ui.tree_widget_of_items ( which is a QTreeWidget created in Qt-designer)
</cod... | 0 | 2016-08-08T20:54:38Z | 38,843,487 | <p>You have to install an event filter on the tree and implement the <code>QObject.eventFilter</code> method in your class.</p>
<p>Example (install event filter):</p>
<pre><code>self.ui.tree_widget_of_items.installEventFilter(self)
</code></pre>
<p>And implement eventFilter:</p>
<pre><code>def eventFilter(self, o, ... | 1 | 2016-08-09T06:22:51Z | [
"python",
"qt",
"pyqt",
"pyqt4"
] |
How to override event (dropEvent) of a widget in dynamic UI of PyQt? | 38,838,354 | <p><strong>What am I doing/ What I have so far :</strong></p>
<p>I am using Qt-designer to create PyQt .ui file which I am loading in my python script using QUiLoader which gives me access to the widgets/components as :</p>
<pre><code>self.ui.tree_widget_of_items ( which is a QTreeWidget created in Qt-designer)
</cod... | 0 | 2016-08-08T20:54:38Z | 38,860,594 | <p>To implement Events in dynamic UI (which means UI created in Qt-designer and used in python tool using .ui file). You need following things :</p>
<ol>
<li><p>MainWindow class of your tool should inherit QtGui.QMainWindow</p>
<pre><code>class main_window(QtGui.QMainWindow):
</code></pre></li>
<li><p>It should call ... | 0 | 2016-08-09T21:17:38Z | [
"python",
"qt",
"pyqt",
"pyqt4"
] |
How to print a dictionary separated by commas | 38,838,407 | <p>Let's say we have a dictionary</p>
<pre><code>dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
</code></pre>
<p>How would I go about printing the code so it looks like:</p>
<blockquote>
<p>Dollar 12, Half-Coin 4, Quarter 3, Dime 7</p>
</blockquote>
| 0 | 2016-08-08T20:57:44Z | 38,838,516 | <pre><code>dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
out=""
for i in dict:
out += i+" "+str(dict[i])+", "
print out[:-2]
</code></pre>
<p>result:</p>
<pre><code>Half-Coin 4, Quarter 3, Dollar 12, Dime 7
</code></pre>
| -1 | 2016-08-08T21:05:34Z | [
"python",
"dictionary",
"formatting"
] |
How to print a dictionary separated by commas | 38,838,407 | <p>Let's say we have a dictionary</p>
<pre><code>dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
</code></pre>
<p>How would I go about printing the code so it looks like:</p>
<blockquote>
<p>Dollar 12, Half-Coin 4, Quarter 3, Dime 7</p>
</blockquote>
| 0 | 2016-08-08T20:57:44Z | 38,838,532 | <p>Use <code>','.join()</code>, passing in a generator of strings.</p>
<pre><code>d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
print ', '.join('{} {}'.format(k,v) for k,v in d.items())
</code></pre>
<p>Result:</p>
<pre><code>Half-Coin 4, Quarter 3, Dollar 12, Dime 7
</code></pre>
<p>If you want the... | 1 | 2016-08-08T21:06:51Z | [
"python",
"dictionary",
"formatting"
] |
How to print a dictionary separated by commas | 38,838,407 | <p>Let's say we have a dictionary</p>
<pre><code>dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
</code></pre>
<p>How would I go about printing the code so it looks like:</p>
<blockquote>
<p>Dollar 12, Half-Coin 4, Quarter 3, Dime 7</p>
</blockquote>
| 0 | 2016-08-08T20:57:44Z | 38,838,586 | <pre><code>", ".join([x +" "+str(dict[x]) for x in dict.keys()])
</code></pre>
| -1 | 2016-08-08T21:11:04Z | [
"python",
"dictionary",
"formatting"
] |
BeautifulSoup difference between findAll and findChildren | 38,838,460 | <p>What is the difference? Don't they do the same thing - find the inside tags with given properties?</p>
| 2 | 2016-08-08T21:01:29Z | 38,839,074 | <p><em>findChildren</em> returns a <em>resultSet</em> just as <em>find_all</em> does, there is no difference in using either method as <a href="https://github.com/JinnLynn/beautifulsoup/blob/master/bs4/element.py#L1178" rel="nofollow"><em>findChildren</em></a> is actually <em>find_all</em>, if you look at the link to... | 1 | 2016-08-08T21:52:29Z | [
"python",
"beautifulsoup"
] |
PySpark distributing module imports | 38,838,465 | <p>Over the past few days I've been working on trying to understand how Spark executors know how to use a module by a given name upon import. I am working on AWS EMR. Situation:
I initialize pyspark on EMR by typing</p>
<p>pyspark --master yarn</p>
<p>Then, in pyspark,</p>
<pre><code>import numpy as np ## notice the... | 4 | 2016-08-08T21:01:57Z | 38,839,181 | <p>When function is serialized there is a <a href="https://github.com/apache/spark/blob/d48935400ca47275f677b527c636976af09332c8/python/pyspark/cloudpickle.py#L222" rel="nofollow">number of objects is being saved</a>:</p>
<ul>
<li><strong>code</strong></li>
<li><strong>globals</strong></li>
<li>defaults</li>
<li><a hr... | 3 | 2016-08-08T22:01:24Z | [
"python",
"apache-spark",
"pyspark"
] |
Python How to extract specified string within [ ] brackets in pandas dataframe and create a new column with boolean values | 38,838,519 | <p>I'm new to programming and would appreciate any of your insights!</p>
<p>I have a data frame like this. </p>
<p>df;</p>
<pre><code> info Price
0 [100:Sailing] $100
1 [150:Boating, 100:Sailing] $200
2 [200:Surfing] $300
</code></pre>
<p>I would lik... | 2 | 2016-08-08T21:05:42Z | 38,838,796 | <p>I assumed the format of the values in the info column is like a Python list.</p>
<pre><code>df1 = df['info'].str[1:-1].str.replace(' ', '').str.get_dummies(',')
df1.rename(columns=lambda x: x.rsplit(':')[-1], inplace=True)
df2 = pd.concat([df, df1.astype(int)], axis=1)
df2
Out:
info Price... | 5 | 2016-08-08T21:28:44Z | [
"python",
"string",
"python-2.7",
"pandas",
"extraction"
] |
MongoEngine returns empty list | 38,838,676 | <p>I have a database named suvaider. It contains two collection Relation and Reviews. I have filled these two by importing from json files. I have created models for these two collections. But while trying to use these models to get data with mongoengine it returns empty array. I'm a beginner I'm using mongodb for th... | 0 | 2016-08-08T21:17:37Z | 39,005,201 | <p>According to the <a href="http://docs.mongoengine.org/guide/defining-documents.html#document-collections" rel="nofollow">documentation</a> Mongoengine by default converts your Document class name to lowercase and use it as a name of the collection. So in your example it looks for collections named: relation and revi... | 0 | 2016-08-17T19:54:39Z | [
"python",
"mongodb",
"mongoengine",
"flask-mongoengine"
] |
Why is my string recognition algorithm not detecting the correct string? | 38,838,714 | <p>Apparently, my string recognition algorithm is not working properly. It is returning the wrong responses based on the user's input. I know it's probably something simple, but I just can't see what it is right now. I done the research and I haven't found another python issue here where when the user input is entered... | 0 | 2016-08-08T21:21:42Z | 38,838,902 | <p>Test using <code>or</code> seems wrong. Maybe you meant <code>if ('how are you' in userReq) or ('how\'s it goind' in userReq)</code> ? Have a look to Python operators precedence.</p>
| 0 | 2016-08-08T21:36:58Z | [
"python",
"string",
"algorithm"
] |
Best practice to deploy python app to use a specific version of Python with venv | 38,838,715 | <p>I am done with a project and it has been been pushed to git but the client wants VENV. I already got <code>venv</code> to work and created a <code>requirements.txt</code> file.</p>
<p>My question is what is the best practice for a deployment workflow. So far this is what I created as a deploy workflow:</p>
<pre><c... | 2 | 2016-08-08T21:22:03Z | 38,840,083 | <p>I tend to you use the Anaconda package manager rather than venv, one of the nice features is that if you run</p>
<pre><code>conda create -n myenv python=3.5
</code></pre>
<p>it will download and install Python 3.5 even if it's not installed on the system already.</p>
| 1 | 2016-08-08T23:50:11Z | [
"python",
"git",
"python-venv"
] |
Best practice to deploy python app to use a specific version of Python with venv | 38,838,715 | <p>I am done with a project and it has been been pushed to git but the client wants VENV. I already got <code>venv</code> to work and created a <code>requirements.txt</code> file.</p>
<p>My question is what is the best practice for a deployment workflow. So far this is what I created as a deploy workflow:</p>
<pre><c... | 2 | 2016-08-08T21:22:03Z | 39,522,736 | <p>I use the following bash script to install my python applications:
I check for either versions of pip ( 2.x or 3.x ) if they are in PATH:</p>
<pre><code>#!/bin/bash
if [ command -v pip3 >/dev/null 2>&1 ];
then
echo "installing virtual env with pip3"
pip3 install virtualenv
else
echo "install... | 1 | 2016-09-16T01:53:24Z | [
"python",
"git",
"python-venv"
] |
Merging crosstabs in Python | 38,838,764 | <p>I am trying to merge multiple crosstabs into a single one. Note that the data provided is obviously only for test purposes. The actual data is much larger so efficiency is quite important for me.</p>
<p>The crosstabs are generated, listed, and then merged with a lambda function on the <code>word</code> column. Howe... | 4 | 2016-08-08T21:26:19Z | 38,839,103 | <p>I just decided to give you a better way of getting you what you want:</p>
<p>I use <code>df.groupby([col1, col2]).size().unstack()</code> to proxy as my <code>pd.crosstab</code> as a general rule. You were trying to do a crosstab for every group of <code>source</code>. I can fit that in nicely with my existing gr... | 2 | 2016-08-08T21:54:52Z | [
"python",
"pandas",
"merge",
"multi-index"
] |
Encoding error using csv.reader on io file object with non-ascii encoding | 38,838,877 | <p>I am trying to read a csv file with cp1252 encoding like this:</p>
<pre><code>import io
import csv
csvr = csv.reader(io.open('data.csv', encoding='cp1252'))
for row in csvr:
print row
</code></pre>
<p>The relevant content of 'data.csv' is</p>
<pre><code>Curva IV
Fecha: 27-Jul-2016 16:22:40
Muestra: 1
TensiÃ... | 0 | 2016-08-08T21:35:16Z | 38,839,135 | <p>From the docs:</p>
<blockquote>
<p>Note</p>
<p>This version of the csv module doesnât support Unicode input. Also,
there are currently some issues regarding ASCII NUL characters.
Accordingly, all input should be UTF-8 or printable ASCII to be safe;
see the examples in section Examples.</p>
</blockquo... | 0 | 2016-08-08T21:57:24Z | [
"python",
"python-2.7",
"csv",
"encoding"
] |
How to deal with an 'endless' webpage when scraping | 38,838,904 | <p>I'm making a scraper to grab a list of my friends from facebook then scrape a list of mutual friends from them, with goal of constructing a web with the data. I looked at the official facebook api, and it doesn't seem possible to do so I decided to simply scrape from the webpages.</p>
<p>After using mechanize to lo... | -1 | 2016-08-08T21:37:07Z | 38,838,968 | <p>Unless you use <a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium</a> to simulate the actual webpage, you won't be able to simulate "scrolling" (how do you scroll when there is no window, therefore no window height?)</p>
<p>You state that there's nothing in the API which allows you to fetch fr... | 0 | 2016-08-08T21:42:46Z | [
"python",
"facebook",
"mechanize",
"mechanize-python"
] |
Failure to import matplotlib.pyplot in jupyter (but not ipython) | 38,838,914 | <p>Update: <code>ipykeynel 4.4.1</code> patched this issue the morning of Aug 9.</p>
<p>I have a fresh install and I have been trying to get my python dependencies up and running, namely jupyter notebook and matplotlib. I've pip installed everything, and "import matplotlib" works. If I am in a jupyter notebook, and I ... | 5 | 2016-08-08T21:37:56Z | 38,845,174 | <p>I have the same problem, and the problem maybe produced by ipykernel.
after i roll back ipykernel version to 4.3.1. the problem solved. </p>
<p>just like @Igor Raush said, it's look like import circular of matplotlib.pyplot.</p>
| 5 | 2016-08-09T08:00:23Z | [
"python",
"matplotlib",
"jupyter-notebook"
] |
Failure to import matplotlib.pyplot in jupyter (but not ipython) | 38,838,914 | <p>Update: <code>ipykeynel 4.4.1</code> patched this issue the morning of Aug 9.</p>
<p>I have a fresh install and I have been trying to get my python dependencies up and running, namely jupyter notebook and matplotlib. I've pip installed everything, and "import matplotlib" works. If I am in a jupyter notebook, and I ... | 5 | 2016-08-08T21:37:56Z | 38,854,391 | <p><a href="http://stackoverflow.com/a/38851858/3988037">As mentioned here</a>, using the magic line <code>%matplotlib</code> allows me to use the plot-in-new-window backend (Qt4Agg in my case). I did not know you could use <code>%matplotlib</code> by itself, without an argument. Even though an update to <code>ipykerne... | 0 | 2016-08-09T15:07:00Z | [
"python",
"matplotlib",
"jupyter-notebook"
] |
How to decode a pdf encrypted file from python | 38,838,930 | <p>I have got a PDF file and associated password.</p>
<p>I would to convert an encrypted file to a clear version using python only.</p>
<p>I found <a href="http://stackoverflow.com/questions/6413441/python-pdf-library">here</a> some python modules (pyPdf2 , PDFMiner)
to treat PDF file but none of them will work with... | 0 | 2016-08-08T21:39:38Z | 38,857,175 | <p>You'd also need to know the encryption algorithm and key length to be able to advise which tool might work... and depending on the answers, a python library may not be available.</p>
| 0 | 2016-08-09T17:36:38Z | [
"python",
"pdf",
"encryption"
] |
Can I do a dynamic comparison on SQLAlchemy? | 38,838,939 | <p>I have this model:</p>
<pre><code>class PUC(Base):
pucId = Column(Integer, primary_key=True)
asset = Column(TINYINT)
article = Column(TINYINT)
more values ...
more values ...
</code></pre>
<p>And I need to do a query dynamically (This way I tried):</p>
<pre><code>pucs = session.query(PUC).filter(PU... | 1 | 2016-08-08T21:40:21Z | 38,839,386 | <p>Here's an approach that uses <code>filter_by</code> and <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">keyword argument unpacking</a>:</p>
<pre><code>keyword = {unique_by_param : 1}
session.query(PUC).filter_by(**keyword).all()
</code></pre>
| 1 | 2016-08-08T22:22:49Z | [
"python",
"sqlalchemy"
] |
Extend Python list by assigning beyond end (Matlab-style) | 38,838,942 | <p>I want to use Python to create a file that looks like</p>
<pre><code># empty in the first line
this is the second line
this is the third line
</code></pre>
<p>I tried to write this script</p>
<pre><code>myParagraph = []
myParagraph[0] = ''
myParagraph[1] = 'this is the second line'
myParagraph[2] = 'this is the t... | 0 | 2016-08-08T21:40:55Z | 38,838,998 | <pre><code>myParagraph = []
myParagraph.append('')
myParagraph.append('this is the second line')
myParagraph.append('this is the third line')
for i,item in enumerate(myParagraph):
print "i:"+str(i)+": item:"+item
</code></pre>
<p>result:</p>
<pre><code>i:0: item:
i:1: item:this is the second line
i:2: item:this ... | 0 | 2016-08-08T21:46:01Z | [
"python",
"list"
] |
Extend Python list by assigning beyond end (Matlab-style) | 38,838,942 | <p>I want to use Python to create a file that looks like</p>
<pre><code># empty in the first line
this is the second line
this is the third line
</code></pre>
<p>I tried to write this script</p>
<pre><code>myParagraph = []
myParagraph[0] = ''
myParagraph[1] = 'this is the second line'
myParagraph[2] = 'this is the t... | 0 | 2016-08-08T21:40:55Z | 38,839,018 | <p>A list doesn't have an unkown size - len(myParagraph) will give you its length</p>
| 1 | 2016-08-08T21:48:03Z | [
"python",
"list"
] |
Extend Python list by assigning beyond end (Matlab-style) | 38,838,942 | <p>I want to use Python to create a file that looks like</p>
<pre><code># empty in the first line
this is the second line
this is the third line
</code></pre>
<p>I tried to write this script</p>
<pre><code>myParagraph = []
myParagraph[0] = ''
myParagraph[1] = 'this is the second line'
myParagraph[2] = 'this is the t... | 0 | 2016-08-08T21:40:55Z | 38,839,046 | <p><code>append</code> is the easiest way to get around this, but if it makes you more comfortable having those indices then you should consider using <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow"><code>insert</code></a>:</p>
<blockquote>
<p>Insert an item at a given position. The f... | 0 | 2016-08-08T21:50:16Z | [
"python",
"list"
] |
Extend Python list by assigning beyond end (Matlab-style) | 38,838,942 | <p>I want to use Python to create a file that looks like</p>
<pre><code># empty in the first line
this is the second line
this is the third line
</code></pre>
<p>I tried to write this script</p>
<pre><code>myParagraph = []
myParagraph[0] = ''
myParagraph[1] = 'this is the second line'
myParagraph[2] = 'this is the t... | 0 | 2016-08-08T21:40:55Z | 38,839,298 | <p>Since you want to associate an index (whether it exists or not) with an element of data, just use a <code>dict</code> with integer indexes:</p>
<pre><code>>>> myParagraph={}
>>> myParagraph[0] = ''
>>> myParagraph[1] = 'this is the second line'
>>> myParagraph[2] = 'this is the t... | 1 | 2016-08-08T22:13:46Z | [
"python",
"list"
] |
Extend Python list by assigning beyond end (Matlab-style) | 38,838,942 | <p>I want to use Python to create a file that looks like</p>
<pre><code># empty in the first line
this is the second line
this is the third line
</code></pre>
<p>I tried to write this script</p>
<pre><code>myParagraph = []
myParagraph[0] = ''
myParagraph[1] = 'this is the second line'
myParagraph[2] = 'this is the t... | 0 | 2016-08-08T21:40:55Z | 38,839,545 | <p>You can do a limited form of this by assigning to a range of indexes starting at the end of the list, instead of a single index beyond the end of the list:</p>
<pre><code>myParagraph = []
myParagraph[0:] = ['']
myParagraph[1:] = ['this is the second line']
myParagraph[2:] = ['this is the third line']
</code></pre>
... | 1 | 2016-08-08T22:40:01Z | [
"python",
"list"
] |
Convert string of list of dictionary to Python DataFrame | 38,839,100 | <p>I have a .JSON file which is around 3GB. I would like to read this JSON data and load it to pandas data frames. Below is what i did so far..</p>
<p>Step 1: Read JSON file</p>
<pre><code>import pandas as pd
with open('MyFile.json', 'r') as f:
data = f.readlines()
</code></pre>
<p>Step2: just take one component... | 0 | 2016-08-08T21:54:43Z | 38,839,723 | <p>Why haven't you tried <code>pandas.read_json</code>?</p>
<pre><code>import pandas as pd
df = pd.read_json('MyFile.json')
</code></pre>
<p>Works for the example you posted!</p>
<pre><code>In[82]: i = '{"reviewerID": "AO94DHGC771SJ", "asin": "0528881469", "reviewerName": "amazdnu", "helpful": [0, 0], "reviewText": ... | 0 | 2016-08-08T22:59:05Z | [
"python",
"python-3.x"
] |
Python itertools with multiprocessing - huge list vs inefficient CPUs usage with iterator | 38,839,170 | <p>I work on n elements (named "pair" below) variations with repetition used as my function's argument. Obviously everything works fine as long as the "r" list is not big enough to consume all the memory. The issue is I have to make more then 16 repetitions for 6 elements eventually. I use 40 cores system in cloud for ... | 3 | 2016-08-08T22:00:29Z | 38,839,831 | <p>The second code example is slower because you're submitting a single pair to a Pool of 39 works. Only one worker will be processing your request and the other 38 will do nothing! Will be slower because you'll have overhead in piping data from the main thread to the workers processes.</p>
<p>You can "buffer" some pa... | 0 | 2016-08-08T23:16:20Z | [
"python",
"multithreading",
"itertools"
] |
Python itertools with multiprocessing - huge list vs inefficient CPUs usage with iterator | 38,839,170 | <p>I work on n elements (named "pair" below) variations with repetition used as my function's argument. Obviously everything works fine as long as the "r" list is not big enough to consume all the memory. The issue is I have to make more then 16 repetitions for 6 elements eventually. I use 40 cores system in cloud for ... | 3 | 2016-08-08T22:00:29Z | 38,839,904 | <p>Your original code isn't creating a <code>list</code> upfront in your own code (<code>itertools.product</code> returns a generator), but <code>pool.map</code> is realizing the whole generator (because it assumes if you can store all outputs, you can store all inputs too).</p>
<p>Don't use <code>pool.map</code> here... | 3 | 2016-08-08T23:25:54Z | [
"python",
"multithreading",
"itertools"
] |
How can I make np.save work for an ndarray subclass? | 38,839,174 | <p>I want to be able to save my array subclass to a npy file, and recover the result later.</p>
<p>Something like:</p>
<pre><code>>>> class MyArray(np.ndarray): pass
>>> data = MyArray(np.arange(10))
>>> np.save('fname', data)
>>> data2 = np.load('fname')
>>> assert isinst... | 5 | 2016-08-08T22:00:57Z | 38,839,604 | <p>I don't see evidence that <code>np.save</code> handles array subclasses.</p>
<p>I tried to save a <code>np.matrix</code> with it, and got back a <code>ndarray</code>.</p>
<p>I tried to save a <code>np.ma</code> array, and got an error</p>
<pre><code>NotImplementedError: MaskedArray.tofile() not implemented yet.
<... | 2 | 2016-08-08T22:46:33Z | [
"python",
"numpy"
] |
Using label encoder on a dictionary | 38,839,211 | <p>I am using the sklearn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="nofollow">LabelEncoder</a>. I know how to use it for a 1D array, but my use case is as such:</p>
<p>I have multiple arrays of dicts like this (which is effectively the cost of me assigning ... | 0 | 2016-08-08T22:04:38Z | 38,839,549 | <p>It seems that you always have 'a', 'b', 'c', 'd', 'e'. If this is the case why don't you use pandas data frame and forget about the encoder? You kinda need to rewrite the keys of the dictionaries you use, so it's going to be messy anyway!</p>
<pre><code>import pandas as pd
i = [
{u'a': 47502.125, u'b': 1580.5625, u... | 1 | 2016-08-08T22:40:40Z | [
"python",
"dictionary",
"scikit-learn",
"text-classification",
"multilabel-classification"
] |
Using label encoder on a dictionary | 38,839,211 | <p>I am using the sklearn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="nofollow">LabelEncoder</a>. I know how to use it for a 1D array, but my use case is as such:</p>
<p>I have multiple arrays of dicts like this (which is effectively the cost of me assigning ... | 0 | 2016-08-08T22:04:38Z | 38,843,254 | <p>Although it is a good practice to use already implemented functionality, you could easily achieve this with a couple of lines of code. Given your list input:</p>
<pre><code>dico = [
{u'a': 47502.125, u'b': 1580.5625, u'c': 45.3, u'd': 2.3, u'e': 0.45},
{u'b': 121, u'a': 1580.5625, u'c': 12, u'e': 62, u'd': 0.343},
... | 1 | 2016-08-09T06:09:31Z | [
"python",
"dictionary",
"scikit-learn",
"text-classification",
"multilabel-classification"
] |
What is the advantage of running python script using command line? | 38,839,215 | <p>I am beginner to python and programming in general. As I am learning python, I am tying to develop a good habit or follow a good practice. So let me first explain what I am currently doing.</p>
<p>I use Emacs (prelude) to execute python scripts. The keybinding <code>C-c</code> <code>C-c</code> evaluates the buffer ... | 0 | 2016-08-08T22:04:56Z | 38,909,330 | <p>People use different tools for different purposes. </p>
<p>An important question about the interface into any program is who is the user? You, as a programmer, will use the interpreter to test a program and check for errors. Often times, the user doesn't really need to access the variables inside because they are n... | 0 | 2016-08-12T03:18:10Z | [
"python",
"command-line",
"emacs"
] |
json error in loading from file (python) | 38,839,246 | <p>I'm learning how to use json in python and have encountered this problem:
The next two paragraphs are run separately from the same directory: </p>
<pre><code>x=[1,-1,[1]]
import json
f=open('states','w')
f.close()
f=open('states','r+')
json.dump(x,f)
json.dump(x,f)
f.close()
f=open('states','r+')
y=json.load(f... | 0 | 2016-08-08T22:08:14Z | 38,839,494 | <p>The error is that you dump the JSON twice. So when you want to load it again, it is not well formed. Try to dump only once and retry. Or verify that your JSON is correct in the file you saved.</p>
| 2 | 2016-08-08T22:34:41Z | [
"python",
"json"
] |
json error in loading from file (python) | 38,839,246 | <p>I'm learning how to use json in python and have encountered this problem:
The next two paragraphs are run separately from the same directory: </p>
<pre><code>x=[1,-1,[1]]
import json
f=open('states','w')
f.close()
f=open('states','r+')
json.dump(x,f)
json.dump(x,f)
f.close()
f=open('states','r+')
y=json.load(f... | 0 | 2016-08-08T22:08:14Z | 38,839,662 | <blockquote>
<p>I'm learning how to use json in python</p>
</blockquote>
<p>Alright, here's some examples. </p>
<p><strong>Write to a file</strong></p>
<pre><code>import json
x=[1,-1,[1]]
with open('states.txt', 'wb') as f:
json.dump(x, f)
</code></pre>
<p><strong>Read from a file</strong></p>
<pre><code>imp... | 0 | 2016-08-08T22:51:32Z | [
"python",
"json"
] |
What is the best way to send Python generated data to PHP? | 38,839,269 | <p>I have a Raspberry PI collecting data from a break beam sensor I wish to use as part of an already developed Laravel application. I was just wondering what would the best way to transfer the data be.</p>
<p>I was thinking of creating an JSON file uploading it to a directory then running a cron job hourly to pick up... | 1 | 2016-08-08T22:10:07Z | 38,839,396 | <p>Use python to extract data from the serial ports of rasberry pi and json encode it and store it in the web directory of your laravel project files. Later json decode and present the data on the web end via laravel php. This is all good . Beind said that another way is to get data from python and then make a curl Pos... | 1 | 2016-08-08T22:24:07Z | [
"php",
"python",
"json",
"laravel"
] |
What is the best way to send Python generated data to PHP? | 38,839,269 | <p>I have a Raspberry PI collecting data from a break beam sensor I wish to use as part of an already developed Laravel application. I was just wondering what would the best way to transfer the data be.</p>
<p>I was thinking of creating an JSON file uploading it to a directory then running a cron job hourly to pick up... | 1 | 2016-08-08T22:10:07Z | 38,839,403 | <p>Your approach sounds fine - the only caveat would be that you will not have "real time" data. You rely on the schedule of your cron jobs to sync the data around - of course you could do this every minute if you wanted to, which would minimize most of the effect of that delay.</p>
<p>The other option is to expose an... | 2 | 2016-08-08T22:24:57Z | [
"php",
"python",
"json",
"laravel"
] |
Reducing an array of dictionaries based on condition and price | 38,839,334 | <p>I would like to reduce the following list maybe using a lambda function. I know that I could first iterate over the entire list and split it into sublists based on the condition value. Then I would iterate over the sublists to get the minimum price.</p>
<pre><code>price_list = [{'price':10.8,'condition':'new'},{'pr... | 0 | 2016-08-08T22:17:48Z | 38,839,499 | <p>You can do:</p>
<pre><code>li=[]
for c in {e['condition'] for e in price_list}:
di={}
di['price']=min(e['price'] for e in price_list if e['condition']==c)
di['condition']=c
li.append(di)
>>> li
[{'price': 6.9, 'condition': 'new'}, {'price': 1.8, 'condition': 'used'}]
</code></pre>
<hr>
<... | 0 | 2016-08-08T22:34:58Z | [
"python",
"list",
"dictionary",
"lambda",
"python-3.4"
] |
Reducing an array of dictionaries based on condition and price | 38,839,334 | <p>I would like to reduce the following list maybe using a lambda function. I know that I could first iterate over the entire list and split it into sublists based on the condition value. Then I would iterate over the sublists to get the minimum price.</p>
<pre><code>price_list = [{'price':10.8,'condition':'new'},{'pr... | 0 | 2016-08-08T22:17:48Z | 38,839,660 | <p>I will do it like this:</p>
<pre><code>from collections import defaultdict
import sys
d = defaultdict(lambda: float('inf'))
for x in price_list:
d[x['condition']]=min(d[x['condition']],x['price'])
[{ 'price':v, 'condition':k } for k,v in d.items() ]
#output:
[{'price': 1.8, 'condition': 'used'}, {'price': 6.9... | 1 | 2016-08-08T22:51:22Z | [
"python",
"list",
"dictionary",
"lambda",
"python-3.4"
] |
matplotlib.pyplot.errorbar is throwing an error it shouldn't? | 38,839,354 | <p>I'm trying to make an errorbar plot with my data. X is a 9 element ndarray. Y and Yerr are 9x5 ndarrays. When I call:</p>
<pre><code>matplotlib.pyplot.errorbar(X, Y, Yerr)
</code></pre>
<p>I get a ValueError: "yerr must be a scalar, the same dimensions as y, or 2xN."</p>
<p>But <code>Y.shape == Yerr.shape</code> ... | 1 | 2016-08-08T22:19:46Z | 38,860,377 | <p><strong>Hmmm....</strong></p>
<p>By studying lines 2962-2965 of the module that raises the error we find</p>
<pre><code>if len(yerr) > 1 and not ((len(yerr) == len(y) and not (iterable(yerr[0]) and len(yerr[0]) > 1)))
</code></pre>
<p>From the data</p>
<pre><code>1 T len(yerr) > 1
2 T len(yerr) == len(y... | 0 | 2016-08-09T21:03:01Z | [
"python",
"python-3.x",
"matplotlib",
"errorbar"
] |
matplotlib.pyplot.errorbar is throwing an error it shouldn't? | 38,839,354 | <p>I'm trying to make an errorbar plot with my data. X is a 9 element ndarray. Y and Yerr are 9x5 ndarrays. When I call:</p>
<pre><code>matplotlib.pyplot.errorbar(X, Y, Yerr)
</code></pre>
<p>I get a ValueError: "yerr must be a scalar, the same dimensions as y, or 2xN."</p>
<p>But <code>Y.shape == Yerr.shape</code> ... | 1 | 2016-08-08T22:19:46Z | 38,860,687 | <p>Maybe by "dimension of y" the docs actually meant 1xN...</p>
<p>Anyway, this could work:</p>
<pre><code>for y, yerr in zip(Y, Yerr):
matplotlib.pyplot.errorbar(X, y, yerr)
</code></pre>
| 0 | 2016-08-09T21:24:26Z | [
"python",
"python-3.x",
"matplotlib",
"errorbar"
] |
Relationship between two tables, SQLAlchemy | 38,839,365 | <p>I want to make a relationship between AuthorComments and Reply to his comments.</p>
<p>Here is my <strong>models.py</strong>:</p>
<pre><code>class AuthorComments(Base):
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
name = db.Column(db.String... | 0 | 2016-08-08T22:20:24Z | 38,840,512 | <p>Your trouble is that SQLAlchemy doesn't know, for a given row of the child table (<code>Reply</code>), which row of the parent table (<code>AuthorComments</code>) to select! You need to define a <em>foreign-key</em> column in <code>Reply</code> that references a column of its parent <code>AuthorComments</code>.</p>
... | 2 | 2016-08-09T01:01:39Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy",
"rdbms"
] |
Pygame Button getRect Collidepoint not working? | 38,839,401 | <p>I have finished the main code for my game and I have started on making a menu screen. I can display the buttons on the screen just fine but when I click somewhere I get this <a href="http://i.stack.imgur.com/pOjmi.png" rel="nofollow">Error</a>:</p>
<p>How can I go about fixing this? If I didn't make anything clear ... | 2 | 2016-08-08T22:24:30Z | 38,839,463 | <p>You haven't declared any attributes for you class, just local variables. Try doing <code>self.selfrect = image.get_rect()</code> in your initializer and in your <code>wasClicked(event)</code> method do:</p>
<pre><code>def wasClicked(self, event):
if self.selfrect.collidepoint(event.pos):
return True
</... | 2 | 2016-08-08T22:30:37Z | [
"python",
"button",
"menu",
"pygame"
] |
how to use assert_frame_equal in unittest | 38,839,402 | <p>New to unittest package.
I'm trying to verify the DataFrame returned by a function through the following code. Even though I hardcoded the inputs of <code>assert_frame_equal</code> to be equal (<code>pd.DataFrame([0,0,0,0])</code>), the unittest still fails. Anyone would like to explain why it happens?</p>
<pre><c... | 1 | 2016-08-08T22:24:54Z | 38,839,418 | <p><code>assert_frame_equal()</code> is coming from the <code>pandas.util.testing</code> package, not from the <code>unittest.TestCase</code> class. Replace:</p>
<pre><code>self.assert_frame_equal(pd.DataFrame([0,0,0,0]),pd.DataFrame([0,0,0,0]))
</code></pre>
<p>with:</p>
<pre><code>assert_frame_equal(pd.DataFrame([... | 4 | 2016-08-08T22:26:15Z | [
"python",
"unit-testing",
"pandas"
] |
Restrict python script access to os functions | 38,839,407 | <p>I need a fresh idea from you, any help is appreciated.</p>
<p>I am implementing a system where user would be able to upload his own Python scripts and execute them within one of servers.</p>
<p>I do beware about the security issues. I would like to restrict any access to the operating system from this script.</p>
... | 3 | 2016-08-08T22:25:31Z | 38,839,433 | <p><a href="https://pypi.python.org/pypi/RestrictedPython/" rel="nofollow">RestrictedPython</a> is what you need.</p>
| 2 | 2016-08-08T22:27:49Z | [
"python",
"security",
"permissions",
"exec",
"eval"
] |
Markov Switching Model in Python Statsmodels | 38,839,465 | <p>I would like to estimate a Markov Switching Model as done in the following:
<a href="http://www.chadfulton.com/posts/mar_hamilton.html" rel="nofollow">http://www.chadfulton.com/posts/mar_hamilton.html</a></p>
<p>However, when I try to import the function to fit the model, i.e. </p>
<pre><code>from statsmodels.tsa.... | 0 | 2016-08-08T22:31:02Z | 38,843,922 | <p>A new version of Statsmodels including the Markov switching code has not yet (at least as of 8/8/16) been released. If you are using an older version of Statsmodels (e.g. 0.6.1) then the code will not be available for you.</p>
<p>A release candidate (0.8.0rc1) is available on PyPi, or you can download and install t... | 0 | 2016-08-09T06:48:27Z | [
"python",
"python-import",
"statsmodels",
"hidden-markov-models",
"markov-models"
] |
ctypes to int conversion with variable assigned by reference | 38,839,525 | <pre><code>def t(n):
print(n)
t(byref(c_int(5)))
</code></pre>
<p>prints <code><cparam 'P' (0000019607137590)></code></p>
<p>how can I convert above printed line to a python <code>int</code>? so that it would simply print <code>5</code></p>
<p>I tried with <code>c_int(n).value</code>, but didn't cut it.</... | 0 | 2016-08-08T22:37:42Z | 38,839,569 | <p><code>byref</code> is for (fast) passing to C level functions; if you need to use the pointer at the Python layer, use <code>pointer</code> (slow, but accessible in Python); for pointer types, you dereference with indexing (since this is a single value, it's <code>[0]</code>):</p>
<pre><code>def t(n):
print(n[0... | 1 | 2016-08-08T22:43:21Z | [
"python"
] |
list of dictionaries from kwargs of key:set pair | 38,839,541 | <pre><code>def funct ( **kwargs ):
#code goes here
</code></pre>
<p>I have variable number of arguments being passed to this function. the arguments are of the form key1 : {set1}, key2 : {set2}, and so on</p>
<p>Inside the funct I want to have the following data structure some how "synthesized" from the given kwar... | -1 | 2016-08-08T22:39:39Z | 38,839,742 | <p><a href="https://docs.python.org/dev/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> is a convenient way to go about this.</p>
<pre><code>import itertools
def dict_product(**kwargs):
"""
Cartesian product of kwargs as dicts with the same keys.
>>> ... | 1 | 2016-08-08T23:01:36Z | [
"python"
] |
<function at > Python Curses | 38,839,590 | <p>I have a program. </p>
<p>I have made this</p>
<pre><code>scoreboard = '\n'.join([
'ââââââââââââââ',
'â Player â',
'â â',
'â 4 â',
'â â',
'â â',
... | -1 | 2016-08-08T22:45:25Z | 38,845,025 | <p>That's because your redefine two times the variable scoreboard (Function / List).
Try changing the name of the function.</p>
| 0 | 2016-08-09T07:50:39Z | [
"python",
"windows",
"function",
"python-3.x",
"curses"
] |
How do I set a name_scope in a graph to be removed from main graph in python | 38,839,675 | <p>I'm trying to organize my TensorBoard graph such that a certain component is automatically placed on the side when I first initiate TensorBoard.</p>
<p><a href="http://i.stack.imgur.com/xoA39.png" rel="nofollow"><img src="http://i.stack.imgur.com/xoA39.png" alt="enter image description here"></a></p>
<p>I want the... | 2 | 2016-08-08T22:53:03Z | 38,857,814 | <p>This isn't currently possible, although we are planning to do this as part of a broader push to improve the graph visualizer in the next few months.
If you want, you can file a GitHub issue for tracking (but we will do this either way). </p>
| 1 | 2016-08-09T18:18:01Z | [
"python",
"tensorflow",
"tensorboard"
] |
Remove duplicate items by value from a dictionary | 38,839,765 | <p>I've got the following dictionary:</p>
<pre><code>potential_duplicates = {
432L: (u'one two three', u'one two three'),
433L: (u'one two three', u'one two three'),
434L: (u'whole foods', u'whole foods'),
435L: (u'whole foods', u'whole foods'),
437L: (u'this is a dupe', u'this is a dupe'),
438L: (u'thi... | 0 | 2016-08-08T23:04:28Z | 38,839,846 | <p>You can do this with two nested dictionary comprehensions. The inner one consolidates the duplicates by reversing the key and value, and the outer one rebuilds it in the original form.</p>
<pre><code>>>> {k:v for v,k in {v:k for k,v in potential_duplicates.items()}.items()}
{433L: (u'one two three', u'one ... | 0 | 2016-08-08T23:18:34Z | [
"python",
"dictionary",
"list-comprehension"
] |
Exporting data to a CSV file, error can't encode character '\xe8' | 38,839,816 | <p>I have a large set of data and I am going to export them into a CSV file using the following code. </p>
<pre><code> with open ('/Users/mz/Dropbox/dis/Programming/zoloft.csv',
'w', newline = '') as zolo:
zolo = csv.writer(zolo, delimiter =',', quotechar='|')
rows = zip(all_rating, all_... | 0 | 2016-08-08T23:14:25Z | 38,839,857 | <p>The <a href="https://docs.python.org/2/library/csv.html" rel="nofollow"><code>csv</code> module, at present, doesn't have Unicode support</a>, but your dataset clearly contains Unicode characters. So what you can do is something similar to the answer to <a href="http://stackoverflow.com/questions/816285/where-is-pyt... | 2 | 2016-08-08T23:20:29Z | [
"python",
"csv"
] |
Why is my logging filter being applied to the wrong handler? | 38,839,817 | <p>Here's a simple Python filter that does nothing but put "TEST - " in front of a log message. (The real filter will do more helpful processing later):</p>
<pre><code>class TimeStamp_Filter(logging.Filter):
def filter(self, record):
record.msg = "TEST - " + str(record.msg)
return True
</code></pr... | 0 | 2016-08-08T23:14:26Z | 38,839,889 | <p>You are changing the message of the log record from a filter. That is causing the issue. </p>
<p>Python will apply that filter to your console output alright but when it does, it changes the original log message. So when the log message is passed to the file handler, the message has changed already and contains th... | 0 | 2016-08-08T23:23:20Z | [
"python",
"logging",
"filter"
] |
SWIG: How to return a struct using %apply? 'No typemaps defined' warning | 38,839,828 | <p>I currently have a function that uses a struct as a buffer to return some information, like so:</p>
<pre><code>int example_reader(int code, void* return_struct);
</code></pre>
<p>My goal is to make it so that when I wrap this function using SWIG so that it can be used in Python, I will return the struct along with... | 1 | 2016-08-08T23:16:07Z | 38,910,594 | <p>I have given here a full C example, where an interface is used for returning a struct to the target language together with a return value. In this way you can make a proper interface, where no implementation is given in the header. That is no default implementation of a virtual destructor. If you don't want to use a... | 1 | 2016-08-12T05:30:22Z | [
"python",
"c++",
"c",
"swig"
] |
Python sorting str price with two decimal points | 38,839,892 | <p>My goal: Sort a <code>list</code> of Products (<code>dict</code>) first by Price, then by Name.
My problem: <code>Str</code> values with numbers in them aren't sorted properly (AKA "Human sorting" or "Natural Sorting").</p>
<p>I found this function from a similar question:
<a href="http://stackoverflow.com/question... | 0 | 2016-08-08T23:23:49Z | 38,839,941 | <p>I think your best bet is to parse the prices as floats (so you can sort them):</p>
<pre><code>float("1.00")
# output: 1.0
</code></pre>
<p>Then output them with two decimal places:</p>
<pre><code>"{:.2f}".format(1.0)
# output: "1.00"
</code></pre>
| 2 | 2016-08-08T23:31:08Z | [
"python",
"sorted"
] |
Python sorting str price with two decimal points | 38,839,892 | <p>My goal: Sort a <code>list</code> of Products (<code>dict</code>) first by Price, then by Name.
My problem: <code>Str</code> values with numbers in them aren't sorted properly (AKA "Human sorting" or "Natural Sorting").</p>
<p>I found this function from a similar question:
<a href="http://stackoverflow.com/question... | 0 | 2016-08-08T23:23:49Z | 38,839,947 | <p>Try typecasting them to floats in the question and when you need to print 2 decimal places, you can easily format the output like so:</p>
<pre><code>float_num = float("110.10")
print "{0:.2f}".format(float_num) # prints 110.10
</code></pre>
| 1 | 2016-08-08T23:31:27Z | [
"python",
"sorted"
] |
Python sorting str price with two decimal points | 38,839,892 | <p>My goal: Sort a <code>list</code> of Products (<code>dict</code>) first by Price, then by Name.
My problem: <code>Str</code> values with numbers in them aren't sorted properly (AKA "Human sorting" or "Natural Sorting").</p>
<p>I found this function from a similar question:
<a href="http://stackoverflow.com/question... | 0 | 2016-08-08T23:23:49Z | 38,839,958 | <p>Your sort function is overkill. Try this simple approach:</p>
<pre><code>from pprint import pprint
products = [
{'name': 'Product 200', 'price': '3000.00'},
{'name': 'Product 4', 'price': '100.10'},
{'name': 'Product 15', 'price': '20.00'},
{'name': 'Product 1', 'price': '5.05'},
{'name': 'Prod... | 3 | 2016-08-08T23:32:29Z | [
"python",
"sorted"
] |
Python sorting str price with two decimal points | 38,839,892 | <p>My goal: Sort a <code>list</code> of Products (<code>dict</code>) first by Price, then by Name.
My problem: <code>Str</code> values with numbers in them aren't sorted properly (AKA "Human sorting" or "Natural Sorting").</p>
<p>I found this function from a similar question:
<a href="http://stackoverflow.com/question... | 0 | 2016-08-08T23:23:49Z | 38,840,275 | <p>To break ties should there be any sorting the strings using the integer value from the product, you can return a tuple:</p>
<pre><code>products = [
{'name': 'Product 200', 'price': '2.99'},
{'name': 'Product 4', 'price': '4.99'},
{'name': 'Product 15', 'price': '4.99'},
{'name': 'Product 1', 'price'... | 0 | 2016-08-09T00:17:57Z | [
"python",
"sorted"
] |
elegant way to check file directory path valid in Python 2.7 | 38,839,902 | <p>I am trying to read content of all files under a specific directory. I find it is a bit tricky if path name is not ends with <code>/</code>, then my code below will not work (will have I/O exception since <code>pathName+f</code> is not valid -- missing <code>/</code> in the middle). Here is a code example to show wh... | 2 | 2016-08-08T23:25:19Z | 38,839,996 | <p>You would just use join again:</p>
<pre><code>pathName = '/Users/foo/Downloads/test' # not working, since not ends with/
onlyfiles = [f for f in listdir(pathName) if isfile(join(pathName, f))]
for f in onlyfiles:
with open(join(pathName, f), 'r') as content_file:
content = content_file.read()
pr... | 3 | 2016-08-08T23:36:54Z | [
"python",
"python-2.7"
] |
Generate Integer Random Numbers in Python Array | 38,839,912 | <p>I'm trying to make an array with 30 integer elements between 0 and 2 randomly chosen. When some number is chosen 10 times, i can't append it anymore. In the end, I need an array with 30 elements with 10 numbers 0, 10 numbers 1 and 10 numbers 2. Here's what i'm trying:</p>
<pre><code>import random
array_size = 30
nu... | 0 | 2016-08-08T23:27:08Z | 38,839,970 | <pre><code>import math
import random
number = 3
size = 30
steps = math.ceil(size / number)
solution = []
for x in range(steps):
for n in range(number):
solution.append(n)
random.shuffle(solution)
print(solution)
</code></pre>
| 1 | 2016-08-08T23:33:35Z | [
"python",
"arrays",
"random"
] |
Generate Integer Random Numbers in Python Array | 38,839,912 | <p>I'm trying to make an array with 30 integer elements between 0 and 2 randomly chosen. When some number is chosen 10 times, i can't append it anymore. In the end, I need an array with 30 elements with 10 numbers 0, 10 numbers 1 and 10 numbers 2. Here's what i'm trying:</p>
<pre><code>import random
array_size = 30
nu... | 0 | 2016-08-08T23:27:08Z | 38,840,029 | <p>Just change </p>
<pre><code>while number[counter] > 10:
</code></pre>
<p>to</p>
<pre><code>while number[counter] >= 10:
</code></pre>
<p>Originally your code would only stop appending a certain number only if there were more than 10 instances of it within your array. By changing it to a >=, the program wil... | 0 | 2016-08-08T23:40:58Z | [
"python",
"arrays",
"random"
] |
How to combine n-grams into one vocabulary in Spark? | 38,839,924 | <p>Wondering if there is a built-in Spark feature to combine 1-, 2-, n-gram features into a single vocabulary. Setting <code>n=2</code> in <code>NGram</code> followed by invocation of <code>CountVectorizer</code> results in a dictionary containing only 2-grams. What I really want is to combine all frequent 1-grams, 2-g... | 3 | 2016-08-08T23:29:18Z | 39,801,829 | <p>You can train separate <code>NGram</code> and <code>CountVectorizer</code> models and merge using <code>VectorAssembler</code>. </p>
<pre><code>from pyspark.ml.feature import NGram, CountVectorizer, VectorAssembler
from pyspark.ml import Pipeline
def build_ngrams(inputCol="tokens", n=3):
ngrams = [
N... | 2 | 2016-10-01T00:32:07Z | [
"python",
"apache-spark",
"nlp",
"pyspark",
"apache-spark-ml"
] |
Comparing Excel dates to current date in Python | 38,840,012 | <p>Python newbie here! :)</p>
<p>Basically, I am trying to scan an excel file's column A (which contains all dates) and if the date in the cell is 7 days in the future...do something. Since I am learning, I am just looking at one cell before I progress and start looping through the data.</p>
<p>Here is my current cod... | 0 | 2016-08-08T23:38:46Z | 38,840,045 | <p>Your <code>cell</code> variable seems to be <code>datetime.datetime</code> object. So you can compare it like this: </p>
<pre><code>from datetime import timedelta
if cell.date() == (datetime.now().date() + timedelta(days=7)):
print("ok")
</code></pre>
| 1 | 2016-08-08T23:44:00Z | [
"python",
"excel",
"date",
"xlrd"
] |
Given an odd length list of values in Python, how can I swap all values other than the final value in the list? | 38,840,017 | <p>In regards to Python 2.7.12 (<em>disclaimer: I understand Python2 is being phased out to Python3, but the course I'm taking started us here, perhaps to understand older code bases</em>):</p>
<p>I have a list of integers whom I'd like to swap each with their neighboring value. So far, this works great for lists that... | 3 | 2016-08-08T23:39:20Z | 38,840,040 | <p>This is easier to do <em>without</em> <code>enumerate</code>. Note that it never, ever makes decisions based on the <em>contents</em> of <code>arr</code>; that is what makes it work on anything, not just a pre-sorted list of integers starting from 1.</p>
<pre><code>for i in range(len(arr)//2):
a = 2*i
b = ... | 4 | 2016-08-08T23:42:45Z | [
"python",
"list"
] |
Given an odd length list of values in Python, how can I swap all values other than the final value in the list? | 38,840,017 | <p>In regards to Python 2.7.12 (<em>disclaimer: I understand Python2 is being phased out to Python3, but the course I'm taking started us here, perhaps to understand older code bases</em>):</p>
<p>I have a list of integers whom I'd like to swap each with their neighboring value. So far, this works great for lists that... | 3 | 2016-08-08T23:39:20Z | 38,840,090 | <p>Here's a shorter, probably faster way based on slice assignment:</p>
<pre><code>def swap_adjacent_elements(l):
end = len(l) - len(l) % 2
l[:end:2], l[1:end:2] = l[1:end:2], l[:end:2]
</code></pre>
<p>The slice assignment selects the elements of <code>l</code> at all even indices (<code>l[:end:2]</code>) or... | 6 | 2016-08-08T23:51:24Z | [
"python",
"list"
] |
Given an odd length list of values in Python, how can I swap all values other than the final value in the list? | 38,840,017 | <p>In regards to Python 2.7.12 (<em>disclaimer: I understand Python2 is being phased out to Python3, but the course I'm taking started us here, perhaps to understand older code bases</em>):</p>
<p>I have a list of integers whom I'd like to swap each with their neighboring value. So far, this works great for lists that... | 3 | 2016-08-08T23:39:20Z | 38,840,129 | <p>You could iterate through the length of the list with a step of two and try to swap values (and except index errors).</p>
<pre><code>def swap_list_pairs(arr):
for index in range(0, len(arr), 2):
try:
arr[index], arr[index+1] = arr[index+1], arr[index]
except IndexError:
p... | 4 | 2016-08-08T23:57:18Z | [
"python",
"list"
] |
Given an odd length list of values in Python, how can I swap all values other than the final value in the list? | 38,840,017 | <p>In regards to Python 2.7.12 (<em>disclaimer: I understand Python2 is being phased out to Python3, but the course I'm taking started us here, perhaps to understand older code bases</em>):</p>
<p>I have a list of integers whom I'd like to swap each with their neighboring value. So far, this works great for lists that... | 3 | 2016-08-08T23:39:20Z | 38,846,870 | <p>Similar to @user2357112 but I prefer it this way:</p>
<pre><code>arr[1::2], arr[:-1:2] = arr[:-1:2], arr[1::2]
</code></pre>
<p>Demo:</p>
<pre><code>>>> arr = [1, 2, 3, 4, 5]
>>> arr[1::2], arr[:-1:2] = arr[:-1:2], arr[1::2]
>>> arr
[2, 1, 4, 3, 5]
>>> arr = [1, 2, 3, 4, 5, 6]... | 1 | 2016-08-09T09:26:03Z | [
"python",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.