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 |
|---|---|---|---|---|---|---|---|---|---|
LDAP modify password | 37,660,371 | <p>I have a Windows 2012 R2 server and a LDAP server on it. I wrote a python script to modify the password of user (the user, who isn't admin, want to modify is own password. I have an other function which modify the password when you're admin, but I don't want to set a password, but modify it). This is a sample of my ... | 0 | 2016-06-06T14:44:55Z | 37,675,040 | <p>I achieved to change the password, their is the code :</p>
<pre><code>#!/usr/bin/env python
#coding:utf-8
import ldap
import ldap.modlist as modlist
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
ld = ldap.initialize('ldaps://XXX:636')
ld.simple_bind_s('XXX@ad2012.local', XXX')
newpassword = ... | 0 | 2016-06-07T09:08:19Z | [
"python",
"passwords",
"ldap"
] |
Node.js receiving data from a python script | 37,660,388 | <p>So I have node calling a python scrip but I want to get an object back from python.</p>
<p>I'm currently using Python-shell (<a href="https://www.npmjs.com/package/python-shell" rel="nofollow">https://www.npmjs.com/package/python-shell</a>) but the problem is its listening so I can't actually send the data I get fr... | 0 | 2016-06-06T14:46:05Z | 37,660,853 | <p>If you want to return the results of a script to the client, just wrap this call: PythonShell.run in in a router endpoint:</p>
<pre><code>app.get('/somepath', (req, res)=>{
PythonShell.run('my_script.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of m... | 0 | 2016-06-06T15:08:58Z | [
"python",
"node.js"
] |
Using Python to communicate with web socket using JSON | 37,660,600 | <p>In order to better understand how websockets are used beyond the basic hello-world, I set myself the task of getting some data from a page using websockets and JSON (because the source code of gitxiv is readily available, I chose to look at <a href="http://gitxiv.com/day/2015/12/31" rel="nofollow">http://gitxiv.com/... | 4 | 2016-06-06T14:55:54Z | 37,661,778 | <p>If you look closely at what what's sent through the browser, notice that it's:</p>
<pre><code>["{\"msg\":\"connect\"}"]
</code></pre>
<p>This looks an awful lot like an array of JSON strings. Indeed, if you try to replicate it:</p>
<pre><code>ws.send(json.dumps([json.dumps({'msg': 'connect', 'version': '1', 'supp... | 5 | 2016-06-06T15:53:03Z | [
"python",
"json",
"websocket",
"telescope"
] |
only show a certain serializer field in a sub-level (newbie) | 37,660,603 | <p>I'm slowly learning how to work with rest framework and I'm stuck in one part I don't really understand(my english isn't great either). I have this api point: building for which I show some data on api/building/ but I want a certain field to appear only on api/building/1 (1=pk number) and I cannot figure this out ho... | 1 | 2016-06-06T14:55:58Z | 37,664,805 | <p>Here is a great answer demonstrating what you should do:</p>
<p><a href="http://stackoverflow.com/a/22755648/2402929">http://stackoverflow.com/a/22755648/2402929</a></p>
<p>In summary, you should create a serializer that will contain all your methods and fields you want in the list route (/api/building/), then ext... | 0 | 2016-06-06T18:49:43Z | [
"python",
"serialization",
"django-rest-framework"
] |
Changing strings to float variables in a 2d array | 37,660,626 | <p>I have a 2D array of strings called c. It has 3 columns. I want to make every 2nd column in each row a float type value. This is what I have so far</p>
<pre><code>for row in range(len(c)):
cNew = float(c[i][1])
</code></pre>
| 0 | 2016-06-06T14:57:21Z | 37,661,059 | <p>EDIT: I misread you question. Here's one solution:</p>
<pre><code>array = [['string', '2.0', 'string'],
['string', '3.0', 'string']]
y = [ [float(x) if i%2 == 1 else x for i,x in enumerate(row)] for row in array]
print(y)
</code></pre>
| 0 | 2016-06-06T15:18:34Z | [
"python",
"arrays",
"casting",
"2d"
] |
Python - too many values to unpack at line 10 | 37,660,653 | <p>In the below code, I'm trying to filter the fruits that cost more than 1.00..</p>
<pre><code>fruits = [
( 'apple', 0.99 ),
( 'orange', 1.25 ),
( 'pear', 1.49 ),
( 'banana', 0.75 ),
]
def preferred(fruit):
pfruit = [ (x, y) for (x, y) in fruit if y > 1 ]
return pfruit
favorites = filter(p... | -1 | 2016-06-06T14:58:46Z | 37,660,817 | <p>Option 1: Simply call the method without the <code>filter</code></p>
<pre><code>>>> preferred(fruits)
# [('orange', 1.25), ('pear', 1.49)]
</code></pre>
<p>Option 2: Use <code>filter</code> in some way with a callable</p>
<pre><code>fruits = [
( 'apple', 0.99 ),
( 'orange', 1.25 ),
( 'pear',... | 0 | 2016-06-06T15:07:03Z | [
"python",
"list",
"filter",
"tuples"
] |
Add columns from different dataframes to target dataframe in PySpark | 37,660,680 | <p>I have a few dataframes like this:</p>
<pre><code> rdd_1 = sc.parallelize([(0,10,"A",2), (1,20,"B",1), (2,30,"A",2)])
rdd_2 = sc.parallelize([(0,10,223,"201601"), (0,10,83,"2016032"),(1,20,3213,"201602"),(1,20,3003,"201601"), (1,20,9872,"201603"), (2,40, 2321,"201601"), (2,30, 10,"201602"),(2,61, 2321,"201601")])
... | 1 | 2016-06-06T15:00:09Z | 37,661,264 | <p>I would suggest to use pivot functions as following :</p>
<pre><code>from pyspark.sql.functions import *
rdd_1 = sc.parallelize([(0,10,"A",2), (1,20,"B",1), (2,30,"A",2)])
rdd_2 = sc.parallelize([(0,10,223,"201601"), (0,10,83,"2016032"),(1,20,3213,"201602"),(1,20,3003,"201601"), (1,20,9872,"201603"), (2,40, 2321,"... | 3 | 2016-06-06T15:28:13Z | [
"python",
"apache-spark",
"pyspark"
] |
Append value to object using list comprehension | 37,660,682 | <p>I am still not python programmer by any means so please bare with me in case this question is very obvious .</p>
<p>I am using django and due to some limitations of Django framework had to use list comprehension to filter values in my model.</p>
<p>My current statement is following </p>
<pre><code> po_list = [n... | 0 | 2016-06-06T15:00:11Z | 37,660,812 | <p>You shouldn't try to do this with a list comprehension. What your looking for is database aggregation. Django supports this to some extent. Some more information can be found in the docs: <a href="https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#values" rel="nofollow">https://docs.djangoproject.com/en/1.... | 0 | 2016-06-06T15:06:41Z | [
"python",
"django"
] |
How to get Tensorflow seq2seq embedding output | 37,660,685 | <p>I am attempting to train a sequence to sequence model using tensorflow and have been looking at their example code. </p>
<p>I want to be able to access the vector embeddings created by the encoder as they seem to have some interesting properties.</p>
<p>However, it really isn't clear to me how this can be.</p>
<p... | 3 | 2016-06-06T15:00:21Z | 37,662,288 | <p>I suggest you read this tutorial on <a href="https://www.tensorflow.org/versions/r0.8/tutorials/word2vec/index.html#vector-representations-of-words" rel="nofollow">Vector representation of words</a> which tackles exactly what you want (getting meaningful word vectors).</p>
| -1 | 2016-06-06T16:18:33Z | [
"python",
"tensorflow"
] |
How to get Tensorflow seq2seq embedding output | 37,660,685 | <p>I am attempting to train a sequence to sequence model using tensorflow and have been looking at their example code. </p>
<p>I want to be able to access the vector embeddings created by the encoder as they seem to have some interesting properties.</p>
<p>However, it really isn't clear to me how this can be.</p>
<p... | 3 | 2016-06-06T15:00:21Z | 38,528,247 | <p>As with all Tensorflow operations, most variables are dynamically created. There are different ways to access these variables ( and their values ). Here, the variable you are interested in is part of the set of trained variables. To access these, we can thus use the <code>tf.trainable_variables()</code> function:</p... | 3 | 2016-07-22T13:53:38Z | [
"python",
"tensorflow"
] |
How to get Tensorflow seq2seq embedding output | 37,660,685 | <p>I am attempting to train a sequence to sequence model using tensorflow and have been looking at their example code. </p>
<p>I want to be able to access the vector embeddings created by the encoder as they seem to have some interesting properties.</p>
<p>However, it really isn't clear to me how this can be.</p>
<p... | 3 | 2016-06-06T15:00:21Z | 39,979,437 | <p>There is a related <a href="http://stackoverflow.com/questions/35143046/tensorflow-seq2seq-get-sequence-hidden-state">post</a>, but it is based on tensorflow-0.6 which is quite out of date. So I update his answer in tensorflow-0.8 which is also similar to that in the newest version.</p>
<p>(*represent where to modi... | 0 | 2016-10-11T14:20:51Z | [
"python",
"tensorflow"
] |
Using variable name as name of dictionary | 37,660,718 | <p>I want to accomplish the following:</p>
<pre><code>vname = [ 'name1', 'name2']
for i in len(vname):
vname[i] = {}
vname[i]['key1'] = 4*i
</code></pre>
<p>I expect to create two dictionaries name1 and name2 such that</p>
<pre><code>name1['key1'] = 0
name2['key1'] = 4
</code></pre>
| 0 | 2016-06-06T15:01:47Z | 37,660,793 | <p>I'd use a <em>nested dictionary</em> instead, generating values with the help of <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a>:</p>
<pre><code>>>> {key: {'key1': index * 4} for index, key in enumerate(vname)}
{'name2': {'key1': 4}, 'name1':... | 1 | 2016-06-06T15:05:44Z | [
"python",
"dictionary"
] |
Using variable name as name of dictionary | 37,660,718 | <p>I want to accomplish the following:</p>
<pre><code>vname = [ 'name1', 'name2']
for i in len(vname):
vname[i] = {}
vname[i]['key1'] = 4*i
</code></pre>
<p>I expect to create two dictionaries name1 and name2 such that</p>
<pre><code>name1['key1'] = 0
name2['key1'] = 4
</code></pre>
| 0 | 2016-06-06T15:01:47Z | 37,660,959 | <p>In order to dynamically create variables of a certain name, you could add them to the global namespace:</p>
<pre><code>>>> vname = [ 'name1', 'name2']
>>> for i in range(len(vname)):
... globals()[vname[i]] = {}
... globals()[vname[i]]['key1'] = 4*i
...
>>> name1
{'key1': 0}
>... | 0 | 2016-06-06T15:14:15Z | [
"python",
"dictionary"
] |
Use list of indices to manipulate a nested dictionary | 37,660,736 | <p>I'm trying to perform operations on a nested dictionary (data retrieved from a yaml file):</p>
<pre><code>data = {'services': {'web': {'name': 'x'}}, 'networks': {'prod': 'value'}}
</code></pre>
<p>I'm trying to modify the above using the inputs like:</p>
<pre><code>{'services.web.name': 'new'}
</code></pre>
<p>... | 0 | 2016-06-06T15:02:20Z | 37,660,925 | <p>You may iterate over the keys while moving a reference:</p>
<pre><code>data = {'networks': {'prod': 'value'}, 'services': {'web': {'name': 'x'}}}
modification = {'services.web.name': 'new'}
for key, value in modification.items():
keyparts = key.split('.')
to_modify = data
for keypart in keyparts[:-1]:
... | 0 | 2016-06-06T15:12:03Z | [
"python",
"list",
"dictionary",
"nested"
] |
How to create a Python List of TensorFlow Variables | 37,660,758 | <p>This seems like it should be such an easy thing but I'm having a little trouble figuring out the syntax behind it. Basically, I have this code:</p>
<pre><code>Weights = []
Weights.append(tf.Variable(tf.random_normal( n_input, Population[sample][0]), 0, 1))
</code></pre>
<p>It returns the error that an 'int' objec... | 0 | 2016-06-06T15:03:27Z | 37,661,337 | <p>The issue in your code comes from <code>tf.random_normal(shape)</code>. Here <code>shape</code> should be a list like <code>[n_input, 3]</code>.</p>
<p>The error raised is <code>'int' object is not iterable</code> because Python tries to read <code>n_input</code> as a list, and it is an int.</p>
<hr>
<p>Your code... | 1 | 2016-06-06T15:31:41Z | [
"python",
"list",
"tensorflow"
] |
Caching a function containing some constants, in Django | 37,660,799 | <p>In a Django website I maintain (v 1.7), I divide every 24-hr day into various time-windows, and then depending on which time window a user logged in at, I process some stuff for the said user. It doesn't matter what date it is, only the time-window matters. </p>
<p>Currently, the time-windows and their related proc... | 2 | 2016-06-06T15:06:06Z | 37,661,145 | <p>If the declarations are static you can put them out of the function. Thus they don't get executed each time the function runs:</p>
<pre><code>from datetime import time as time_object
window1_least = time_object(hour=0, minute=0)
window1_most = time_object(hour=3, minute=0)
window2_least = time_object(hour=3, min... | 0 | 2016-06-06T15:23:03Z | [
"python",
"django",
"performance",
"caching"
] |
Caching a function containing some constants, in Django | 37,660,799 | <p>In a Django website I maintain (v 1.7), I divide every 24-hr day into various time-windows, and then depending on which time window a user logged in at, I process some stuff for the said user. It doesn't matter what date it is, only the time-window matters. </p>
<p>Currently, the time-windows and their related proc... | 2 | 2016-06-06T15:06:06Z | 37,662,115 | <p>If you really need to improve performance you should consider reorganizing the windows, since they are checked from midnight, (which probably is not the time when you have the most of the traffic).</p>
<p>Just to give a second approach, you could do something like this:</p>
<pre><code>from datetime import datetime... | 1 | 2016-06-06T16:09:41Z | [
"python",
"django",
"performance",
"caching"
] |
Python find index of items in list b from list a | 37,660,876 | <p>I have two lists such as:</p>
<pre><code>aa=[int(1000*random.random()) for i in xrange(10000)]
bb=[int(1000*random.random()) for i in xrange(10000)]
</code></pre>
<p>and i would another list that tells me where in list bb is the item aa; if it doesn't exist then I would like it to return -1.</p>
<p>The lists are ... | 3 | 2016-06-06T15:10:06Z | 37,661,113 | <p>Works slightly better for me, returns exactly the same output and you don't need to define a function</p>
<pre><code>ls = [bb.index(i) for i in aa]
</code></pre>
<p>EDIT:
Inspired by Valéry's answer (the output wasn't correct)!</p>
<pre><code>dict_index = [bb.index(i) for i in set(aa) if i in bb]
ls = [dict_inde... | -1 | 2016-06-06T15:21:31Z | [
"python",
"algorithm",
"performance",
"list",
"numpy"
] |
Python find index of items in list b from list a | 37,660,876 | <p>I have two lists such as:</p>
<pre><code>aa=[int(1000*random.random()) for i in xrange(10000)]
bb=[int(1000*random.random()) for i in xrange(10000)]
</code></pre>
<p>and i would another list that tells me where in list bb is the item aa; if it doesn't exist then I would like it to return -1.</p>
<p>The lists are ... | 3 | 2016-06-06T15:10:06Z | 37,661,269 | <p>You can create a <code>dict</code>, or <code>defaultdict(list)</code>, mapping each element to the index (or indices) it appears at. This way, you need some more space (somewhat more than the original list, but still in the same ballpark), but once the dict is created, each index lookup will be O(1).</p>
<pre><code... | 0 | 2016-06-06T15:28:21Z | [
"python",
"algorithm",
"performance",
"list",
"numpy"
] |
Python find index of items in list b from list a | 37,660,876 | <p>I have two lists such as:</p>
<pre><code>aa=[int(1000*random.random()) for i in xrange(10000)]
bb=[int(1000*random.random()) for i in xrange(10000)]
</code></pre>
<p>and i would another list that tells me where in list bb is the item aa; if it doesn't exist then I would like it to return -1.</p>
<p>The lists are ... | 3 | 2016-06-06T15:10:06Z | 37,662,054 | <p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package can be used to solve this problem in a fully vectorized manner (disclaimer: I am its author). Note that you would do well to replace the rest of your code with numpy as well, since otherwise that is bound ... | 1 | 2016-06-06T16:06:41Z | [
"python",
"algorithm",
"performance",
"list",
"numpy"
] |
Python find index of items in list b from list a | 37,660,876 | <p>I have two lists such as:</p>
<pre><code>aa=[int(1000*random.random()) for i in xrange(10000)]
bb=[int(1000*random.random()) for i in xrange(10000)]
</code></pre>
<p>and i would another list that tells me where in list bb is the item aa; if it doesn't exist then I would like it to return -1.</p>
<p>The lists are ... | 3 | 2016-06-06T15:10:06Z | 37,663,950 | <p>Here's an approach based on <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> and inspired by <a href="http://stackoverflow.com/a/34945323/3293881"><code>this other post</code></a> -</p>
<pre><code>sidx = np.argsort(bb)
L = n... | 1 | 2016-06-06T17:59:06Z | [
"python",
"algorithm",
"performance",
"list",
"numpy"
] |
Python Simple HTTP Server in Virtual Directory | 37,660,909 | <p>I like the ease of use of Python's SimpleHTTPServer but...</p>
<p>I'd like to launch it from what I'm calling a "fake directory" - that is, a directory that only exists from the server's point of view (does not actually persist on the computer), and ceases to exist when the python process running the server stops. ... | 1 | 2016-06-06T15:11:29Z | 37,661,219 | <p>I would do this by using an in-memory sqlite database. You get all of the benefits of a sql database (relations, searchability, etc), but it only exists for the life of the process.</p>
<p>You can use the package <a href="https://github.com/guardianproject/libsqlfs" rel="nofollow">libsqlfs</a> which emulates a comp... | 1 | 2016-06-06T15:26:40Z | [
"python",
"server",
"simplehttpserver"
] |
Python Simple HTTP Server in Virtual Directory | 37,660,909 | <p>I like the ease of use of Python's SimpleHTTPServer but...</p>
<p>I'd like to launch it from what I'm calling a "fake directory" - that is, a directory that only exists from the server's point of view (does not actually persist on the computer), and ceases to exist when the python process running the server stops. ... | 1 | 2016-06-06T15:11:29Z | 37,661,324 | <p>You could use <a href="https://docs.python.org/3.5/library/tempfile.html#tempfile.TemporaryDirectory" rel="nofollow">TemporaryDirectory</a> or <a href="https://docs.python.org/3.5/library/tempfile.html#tempfile.mkdtemp" rel="nofollow">mkdtemp</a> and make the server serve from that directory. With the first approach... | 1 | 2016-06-06T15:31:00Z | [
"python",
"server",
"simplehttpserver"
] |
Python Simple HTTP Server in Virtual Directory | 37,660,909 | <p>I like the ease of use of Python's SimpleHTTPServer but...</p>
<p>I'd like to launch it from what I'm calling a "fake directory" - that is, a directory that only exists from the server's point of view (does not actually persist on the computer), and ceases to exist when the python process running the server stops. ... | 1 | 2016-06-06T15:11:29Z | 37,661,501 | <p>Here is a snippet of what you could achieve using <code>mkdtemp</code>. It does not remove files if the python process gets killed. Maybe a signal handler could do the job.</p>
<pre><code>import SimpleHTTPServer
import tempfile
import os
import shutil
class CustomHTTPServer():
pass
if __name__ == '__main__':
... | 1 | 2016-06-06T15:39:10Z | [
"python",
"server",
"simplehttpserver"
] |
Python Simple HTTP Server in Virtual Directory | 37,660,909 | <p>I like the ease of use of Python's SimpleHTTPServer but...</p>
<p>I'd like to launch it from what I'm calling a "fake directory" - that is, a directory that only exists from the server's point of view (does not actually persist on the computer), and ceases to exist when the python process running the server stops. ... | 1 | 2016-06-06T15:11:29Z | 37,662,538 | <p>You could inherit from SimpleHTTPServer and override the method <strong>list_directory</strong> and <strong>translate_path</strong>, but if you really don't mind dumping it to disc, you could make yourself a temporary directory context manager that handles directory deletion with shutil:</p>
<pre><code>from tempfil... | 0 | 2016-06-06T16:31:45Z | [
"python",
"server",
"simplehttpserver"
] |
Removing and replacing values in List of lists in Python | 37,660,934 | <p>I have List something like below: </p>
<pre><code>[[{
'canBeAdded' : True,
'categories' : ['Diving', 'Sports'],
'relevanceRank' : 1,
'rankSource' : 'NONE',
'value' : 1.0,
'canBeRemoved' : True,
'displayStartDate' : '2013-02-10T05:00:00Z',
'filterTags' ... | -1 | 2016-06-06T15:12:28Z | 37,694,094 | <p>Start reading:
<a href="https://people.duke.edu/~ccc14/sta-663/IntroductionToPythonSolutions.html" rel="nofollow">https://people.duke.edu/~ccc14/sta-663/IntroductionToPythonSolutions.html</a></p>
<p>Try this: </p>
<pre><code>LL = [[{
'canBeAdded' : True,
'categories' : ['Diving', 'Sports'],
... | 0 | 2016-06-08T05:42:07Z | [
"python",
"python-3.x"
] |
Renaming files in a smart way | 37,660,974 | <p>I have a collection of files that I would like to re-organize in a smart way, using python.
The files are state-county-year specific and saved in a folder structure of this form: \state\year\county\image.jpg with many images per county.
I have the following code that copies and renames all files as state_year_count... | 0 | 2016-06-06T15:14:54Z | 37,662,846 | <p>os.walk could be what you're looking for.
Also, I'd recommend not moving your images <strong>inside</strong> of your search directory, as that'll lead to confusion on re-processing.</p>
<p>Something like this:</p>
<pre><code>import os
import shutil
SRCDIR = r'C:\Users\me\originals'
DESTDIR = r'C:\Users\me\copies'... | 0 | 2016-06-06T16:48:53Z | [
"python",
"naming"
] |
Python OpenCV: Play UDP video streaming while sending keep alive messages | 37,660,982 | <p>I have a program which connects with a camera via socket. This camera starts to livestream video when I send a message throught this socket, and continues while I send keep alive messages. The video is transmitted via UDP as mpeg-ts packets. I'm trying to play the video with OpenCV but I'm having </p>
<pre><code>[u... | 2 | 2016-06-06T15:15:17Z | 38,668,020 | <p>Maybe u work the same project likes me :]. I have view one pages u post before this. It said u want to try gst 1.0 instead of gst 0.10. I still worked with it, and almost gave up. Now I only could work with gst 0.10.And now, I had edited some command line for gst pipeline. It works well. Hope it will help u, and rep... | 0 | 2016-07-29T21:54:14Z | [
"python",
"sockets",
"opencv",
"udp"
] |
Pandas compare 2 dataframes by specific rows in all columns | 37,661,073 | <p>I have the following Pandas dataframe of some raw numbers:</p>
<pre><code>import numpy as np
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 10000)
col_raw_headers = ['07_08_19 #1','07_08_19 #2','07_08_19 #2.1','11_31_19 #1','11_31... | 1 | 2016-06-06T15:19:53Z | 37,663,451 | <p>I came up with this using loops. It is very disappointing:</p>
<pre><code>holder = []
for randm,pp in enumerate(list(df_processed)):
list1 = df_processed[pp].tolist()
for car,rr in enumerate(list(df_raw)):
list2 = df_raw.loc[7:,rr].tolist()
if list1==list2:
holder.append([rr,pp])... | 0 | 2016-06-06T17:26:03Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Pandas compare 2 dataframes by specific rows in all columns | 37,661,073 | <p>I have the following Pandas dataframe of some raw numbers:</p>
<pre><code>import numpy as np
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 10000)
col_raw_headers = ['07_08_19 #1','07_08_19 #2','07_08_19 #2.1','11_31_19 #1','11_31... | 1 | 2016-06-06T15:19:53Z | 37,664,234 | <p>Does this look like the output you're looking for?</p>
<p>Raw dataframe <code>df</code>:</p>
<pre><code> Tr_id 07_08_19 07_08_19.1 07_08_19.2 11_31_19 11_31_19.1
0 Quantity1 1 1 2 1 2
1 Quantity2 75 11 0.9 ... | 1 | 2016-06-06T18:17:52Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Pandas compare 2 dataframes by specific rows in all columns | 37,661,073 | <p>I have the following Pandas dataframe of some raw numbers:</p>
<pre><code>import numpy as np
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 10000)
col_raw_headers = ['07_08_19 #1','07_08_19 #2','07_08_19 #2.1','11_31_19 #1','11_31... | 1 | 2016-06-06T15:19:53Z | 39,077,982 | <p>alternative solution, using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow">DataFrame.isin()</a> method:</p>
<pre><code>In [171]: df1
Out[171]:
a b c
0 1 1 3
1 0 2 4
2 4 2 2
3 0 3 3
4 0 4 4
In [172]: df2
Out[172]:
a b c
0 0 3 3
1... | 1 | 2016-08-22T11:07:42Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Segmentation fault when loading a GeoJson | 37,661,081 | <p>I have a problem while loading a JSON document with geopandas but when calling <code>data = geopandas.GeoDataFrame.from_file(json_data)</code>, I get a <code>segmentation fault</code>.</p>
<p>My JSON seems to be valid and I don't know how to do it without using geopandas.</p>
<p>Here is my GeoJSON : <a href="http:... | 0 | 2016-06-06T15:20:15Z | 37,661,282 | <blockquote>
<p>My JSON seems to be valid and I don't know how to do it without using geopandas.</p>
</blockquote>
<p>There is a site to test that: <a href="http://geojsonlint.com/" rel="nofollow">geojsonlint.com</a>. According to this validator the document is invalid.</p>
<pre><code>Line 5: GeoJSON features must ... | 1 | 2016-06-06T15:29:04Z | [
"python",
"json",
"geojson",
"geopandas"
] |
python mpl_toolkits installation issue | 37,661,119 | <p>After command <code>pip install mpl_toolkits</code> I receive next error
<code>Could not find a version that satisfies the requirement mpl_toolkits (from versions: )
No matching distribution found for mpl_toolkits</code>
I tried to google, but nothing helps. How can I solve this?</p>
| 0 | 2016-06-06T15:21:52Z | 37,661,312 | <p><em>It is not on PyPI and you should not be installing it via <code>pip</code></em>. If you have <code>matplotlib</code> installed, you should be able to import <code>mpl_toolkits</code> directly:</p>
<pre><code>$ pip install --upgrade matplotlib
...
$ python
>>> import mpl_toolkits
>>>
</code><... | 1 | 2016-06-06T15:30:33Z | [
"python",
"python-3.x",
"pip"
] |
Why can my Python MySQLdb script see, but not make live changes to, my database? | 37,661,176 | <p>I am working with a customized Django installation, although the issue I am dealing with is from a command line tool intended to update the database. The tool reads the database as intended and functions comparably to typing SELECTs in MySQL's command line. However, it seems never to <em>change</em> the database. I ... | 0 | 2016-06-06T15:24:43Z | 37,661,275 | <p>You need to commit data</p>
<pre><code> cursor.execute('UPDATE auth_user SET foo = ' + str(foo) + " WHERE username = '" + username.replace("'", "\\'") + "'")
connection.commit()
</code></pre>
<p>Take a look at <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction... | 2 | 2016-06-06T15:28:42Z | [
"python",
"mysql",
"mysql-python"
] |
Add text annotation to matplotlib plot from a pandas dataframe | 37,661,437 | <p>How to add text annotation and mark plotted points and the numeric values to a matplotlib plot of a pandas dataframe? The columns of the dataframe is not fixed size, it varies for different files.</p>
<pre><code>dataframe = pd.read_csv('file1.csv')
plt.figure(figsize=(50,25))
dataframe.plot()
plt.xticks(rotation=4... | 2 | 2016-06-06T15:36:42Z | 37,662,428 | <pre><code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({'x':range(0, 100, 20),
'y':np.random.randint(0,100,5)})
rows, cols = df.shape
fig, ax = plt.subplots(figsize=(50/10,25/10))
df.plot(ax=ax)
for col in range(cols):
for i in range(rows):
... | 3 | 2016-06-06T16:26:04Z | [
"python",
"pandas",
"matplotlib"
] |
how to add a jar to python notebook on bluemix spark? | 37,661,456 | <p>I would like to use spark jdbc with python. First step was to add a jar:</p>
<pre><code>%AddJar http://central.maven.org/maven2/org/apache/hive/hive-jdbc/2.0.0/hive-jdbc-2.0.0.jar -f
</code></pre>
<p>However, the response:</p>
<pre><code>ERROR: Line magic function `%AddJar` not found.
</code></pre>
<p>How can ... | 2 | 2016-06-06T15:37:47Z | 37,665,384 | <p>I don't think this is possible in Notebook's Python Kernel as %Addjar is scala kernel magic function in notebook.</p>
<p>You would need to rely on the service provider to add this jar to python kernel.</p>
<p>Another thing you could try is sc.addjar() but not sure how would it work.</p>
<p><a href="http://stackov... | 2 | 2016-06-06T19:27:08Z | [
"python",
"apache-spark",
"ipython",
"ibm-bluemix",
"jupyter-notebook"
] |
how to add a jar to python notebook on bluemix spark? | 37,661,456 | <p>I would like to use spark jdbc with python. First step was to add a jar:</p>
<pre><code>%AddJar http://central.maven.org/maven2/org/apache/hive/hive-jdbc/2.0.0/hive-jdbc-2.0.0.jar -f
</code></pre>
<p>However, the response:</p>
<pre><code>ERROR: Line magic function `%AddJar` not found.
</code></pre>
<p>How can ... | 2 | 2016-06-06T15:37:47Z | 37,665,930 | <p>Presently, this is not possible only from a python notebook; but it is understood as an important requirement. What you can do until this is supported, is from the same spark service instance of your python notebook, create a scala notebook and <code>%AddJar</code> from there. Then all python notebooks of that same ... | 2 | 2016-06-06T20:03:23Z | [
"python",
"apache-spark",
"ipython",
"ibm-bluemix",
"jupyter-notebook"
] |
How to read some data in python, saving that after manipulation | 37,661,488 | <p>Suppose I read a file a csv file as a nested list in python.
data in python looks like this:</p>
<pre><code>my_data=[[1,4,6,2],
[1,6,5,2],
[1,2,1,6]]
</code></pre>
<p>and so on. </p>
<p>Suppose I have to do some cleaning with data in python( for several purpose). Data continues to look as a neste... | -1 | 2016-06-06T15:38:48Z | 37,663,485 | <pre><code>import csv
_list = [[1, 4, 6, 2], [1, 6, 5, 2], [1, 2, 1, 6]]
filename = 'test.csv'
with open(filename, 'wb') as csvfile:
a = csv.writer(csvfile)
a.writerows(_list)
with open(filename, 'rb') as fn:
read = csv.reader(fn, delimiter='\t')
for row in read:
print row[0]
</code></pre>
<... | 0 | 2016-06-06T17:28:07Z | [
"python"
] |
How to click a link from a hover menu using Selenium Webdriver and Python? | 37,661,489 | <p><a href="http://www.nike.com/us/en_us/c/nikeid" rel="nofollow">http://www.nike.com/us/en_us/c/nikeid</a></p>
<p>I want to click on the 'Customize' nav link up in the top nav bar (so the one on the top, not the left) and then select Men's in the hover menu.</p>
<p>I can click on 'Customize', the hover menu than ope... | 1 | 2016-06-06T15:38:48Z | 37,661,791 | <p>Just <em>fix your selector</em> to match the <code>Men</code> link:</p>
<pre><code>wait.until(EC.visibility_of_element_located(
(By.CSS_SELECTOR, "li[data-nav-tracking=customize] [data-nav-tracking=men] a"))).click()
</code></pre>
| 2 | 2016-06-06T15:53:41Z | [
"python",
"selenium"
] |
Python building object instance: object() takes no parameters | 37,661,532 | <p>I'm writing a tensorflow program similar to their MNIST LSTM example code. I'm building my data file, and I am unable to build an object instance.</p>
<p>Essentially the process goes: define an empyty instance <code>data_sets = DataSet()</code> and then build the object <code>data_sets.train = DataSet(arg1, arg2...... | 0 | 2016-06-06T15:41:06Z | 37,661,624 | <p>You overwrite <code>ScrollData</code> within you <code>read_data</code> function with a class which doesn't take constructor arguments. </p>
<p>leave this redefinition out and either add arguments to the first call or define standard values in the constructor</p>
| 2 | 2016-06-06T15:45:31Z | [
"python",
"class",
"object",
"constructor",
"arguments"
] |
Hide Labels of Radio Buttons in Django Template | 37,661,551 | <p>I have the following code in models.py:</p>
<pre><code>MATRIX_COLUMN_CHOICES = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]
class DeathCertificateReviewForm(forms.ModelForm):
matrix_row_one_column_value = forms.ChoiceField(widget = forms.RadioSelect, choices = MATRIX_COLUMN_CHOICES)
</code></pre>
<p>And i... | 0 | 2016-06-06T15:41:54Z | 37,679,037 | <p>This is defined in the radio-select Widget <a href="https://docs.djangoproject.com/en/dev/ref/forms/widgets/#radioselect" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/forms/widgets/#radioselect</a> , so Creating a custom widget should do the trick.
Also, it seems that your <code><li></li></c... | 0 | 2016-06-07T12:11:43Z | [
"python",
"django",
"templates",
"button",
"radio"
] |
`scipy.optimize.root` faster root finding | 37,661,586 | <p>I use <code>scipy.optimize.root</code> with the <code>hybr</code> method (best one ?) to find the root of a numeric function </p>
<p>I print the residual at each iteration</p>
<p><code>
delta d 117.960112417
delta d 117.960112417
delta d 117.960112417
delta d 117.960048733
delta d 117.960112427
delta d 117.96011... | 1 | 2016-06-06T15:43:36Z | 37,662,723 | <p>First, I think you are confusing iterations with calls to your function, which are not quite exactly the same. Because you have not provided the solver with a Jacobean function, it must estimate the Jacobean (or perhaps just some part of it) itself. The Jacobean is basically the multidimensional equivalent of the de... | 5 | 2016-06-06T16:41:54Z | [
"python",
"performance",
"scipy",
"mathematical-optimization",
"accelerate"
] |
Copy content from one YAML to another YAML after comparison of keys | 37,661,712 | <p>I have a use case where I need to pick key:value pairs from a new YAML file. Check whether that key exists in old YAML file and if it does copy the value and set it in new YAML file.<br>
Also if that key does not exist in old file then ask the user.</p>
<p>Code: </p>
<pre><code>copyfile('all.isv', '/home/ubuntu/tm... | 0 | 2016-06-06T15:49:43Z | 37,668,010 | <p>That is invalid Python, your <code>try</code> doesn't have a matching <code>except</code>. Apart from that it is not necessary to open the second file in the context of the with statement that you use for reading in the "old" file. Therefore start with:</p>
<pre><code>import ruamel.yaml
copyfile('all.isv', '/home/... | 1 | 2016-06-06T22:52:13Z | [
"python",
"yaml",
"pyyaml"
] |
Why does Pylint error on metaclass-defined attribute usage? | 37,661,772 | <p>I am using a metaclass in my code, and the code works. (Using a metaclass, it sets the attribute <code>test_attr</code> to <code>"Success!"</code> on object creation.) When I run <code>pylint</code> on this code, however, it displays errors in <code>Test.test</code>, saying that <code>test_attr</code> is not defined... | 0 | 2016-06-06T15:52:47Z | 37,695,672 | <p>I'm guessing pylint simply doesn't understand this kind of "magic" - why are you doing it in the first place?</p>
<p>You could set <code>generated-members</code> or <code>ignored-classes</code> (see <a href="https://docs.pylint.org/features.html?highlight=generated#id28" rel="nofollow">docs</a>) to tell pylint abou... | 1 | 2016-06-08T07:16:51Z | [
"python",
"python-3.x",
"attributes",
"metaclass",
"pylint"
] |
Copy multiple files from sub folder into one folder | 37,661,798 | <p>I have folder that has subfolders each with many different files.
I'd like to copy all of the files (not subdirectories) into one folder</p>
<pre><code>import os
import shutil
src = r'C:\TEMP\dir'
dest = r'C:\TEMP\new'
src_files = os.listdir(src)
for file_name in src_files:
full_file_name = os.path.join(src, ... | 0 | 2016-06-06T15:53:56Z | 37,665,246 | <p>You can try this</p>
<pre><code>import os
import shutil
src = r'C:\TEMP\dir'
dest = r'C:\TEMP\new'
for path, subdirs, files in os.walk(src):
for name in files:
filename = os.path.join(path, name)
shutil.copy2(filename, dest)
</code></pre>
| 0 | 2016-06-06T19:18:09Z | [
"python",
"copy",
"shutil"
] |
Python LXML: Modify CDATA | 37,661,822 | <p>When I'm manipulating XML parsed with the Python LXML module (specifically <code>lxml.objectify</code>, but I don't think it makes a difference), how can I preserve CDATA?</p>
<p>Given the following results:</p>
<pre><code>>>> from lxml import objectify, etree
>>> xml = '''
<Root>
<... | 0 | 2016-06-06T15:54:55Z | 37,662,213 | <pre><code>>>> from lxml import etree
>>> parser = etree.XMLParser(strip_cdata=False)
>>> parsed = etree.XML('''
... <Root>
... <Child>
... <![CDATA[abcd]]>
... </Child>
... </Root>
... ''', parser)
>>> print etree.tostring(parsed)
<Root... | 0 | 2016-06-06T16:15:12Z | [
"python",
"lxml",
"cdata",
"lxml.objectify"
] |
How can one configure flask to be accessible via public IP interface? | 37,661,843 | <p>I am unable to resolve any methods externally via their url once I set the SERVER_NAME or host property in flask. The following is my app init config:</p>
<pre><code>flask_sqlalchemy import SQLAlchemy
from flask.ext.cors import CORS
__authors__ = 'DarkStar1'
from flask import Flask
app = Flask(__name__)
app.confi... | 1 | 2016-06-06T15:55:33Z | 37,662,122 | <p>run flask using </p>
<pre><code>app.run(host="0.0.0.0:PORT#")
</code></pre>
<p>look for your IPv4 Address using ipconfig in your command prompt, and in your browser you can access your app using your ipaddress:port#</p>
<p>You might have to configure your router (port forwarding) to make it publicly available, ot... | 2 | 2016-06-06T16:10:04Z | [
"python",
"flask",
"configuration",
"devserver"
] |
serialize class instance for comparison | 37,661,851 | <p>I have an application which is working with projects. These projects are currently stored as pickles, generated with</p>
<pre><code>cPickle.dump(project, open(filename, 'wb'), HIGHEST_PROTOCOL)
</code></pre>
<p>These project files need to be diffable because they are used in a version control environment.
The prob... | 0 | 2016-06-06T15:56:07Z | 37,743,422 | <p>I found the solution, I'm gonna post it here in case anyone has the same question in the future.</p>
<p>The solution is to do a deepcopy of the object directly before it's pickled.
That way the reference count which apparently causes the differences gets reset and the files turn out the same when using HIGHEST_PROT... | 0 | 2016-06-10T08:25:50Z | [
"python",
"serialization",
"version-control",
"pickle"
] |
Convert a list to json objects | 37,661,863 | <p>I have a huge text file.</p>
<pre><code>line 1
line 2
line 3
...
</code></pre>
<p>I have converted it into an array of lists:</p>
<pre><code>[['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
['String 6'],['String 7'],['String 8'],['String 9'],['String 9'],
['String 10'], ...]
</code></pre>
<p>I ... | -1 | 2016-06-06T15:56:25Z | 37,661,975 | <p>To solve this, you need to <em>split the input list into chunks</em>, by 7 in your case. For this, let's use <a href="http://stackoverflow.com/a/312464/771848">this approach</a>. Then, use a <em>list comprehension</em> producing a list of dictionaries:</p>
<pre><code>>>> from pprint import pprint
>>&... | 1 | 2016-06-06T16:02:17Z | [
"python",
"arrays",
"json"
] |
Convert a list to json objects | 37,661,863 | <p>I have a huge text file.</p>
<pre><code>line 1
line 2
line 3
...
</code></pre>
<p>I have converted it into an array of lists:</p>
<pre><code>[['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
['String 6'],['String 7'],['String 8'],['String 9'],['String 9'],
['String 10'], ...]
</code></pre>
<p>I ... | -1 | 2016-06-06T15:56:25Z | 37,662,298 | <p>Just adding onto alexce's response, you can easily convert the restructured data into JSON:</p>
<pre><code>import json
json.dumps(result)
</code></pre>
<p>There are some potential <a href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx/" rel="nofollow">security concerns</a> with top-level arrays. I'm no... | 0 | 2016-06-06T16:18:59Z | [
"python",
"arrays",
"json"
] |
Convert a list to json objects | 37,661,863 | <p>I have a huge text file.</p>
<pre><code>line 1
line 2
line 3
...
</code></pre>
<p>I have converted it into an array of lists:</p>
<pre><code>[['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
['String 6'],['String 7'],['String 8'],['String 9'],['String 9'],
['String 10'], ...]
</code></pre>
<p>I ... | -1 | 2016-06-06T15:56:25Z | 37,662,751 | <p>As @alecxe pointed out, you need to divide the array of lists you got from the file into groups of values with 7 or fewer elements. You can then take a list of any 7 titles you want and use them as keys to create the dictionary of each json object in the final list.</p>
<pre><code>try:
from itertools import izi... | 1 | 2016-06-06T16:43:48Z | [
"python",
"arrays",
"json"
] |
Python best way to document imported module version in scripts | 37,661,876 | <p>What is the best way or PEP convention to document the versions of <strong>imported modules</strong> in single python scripts? Sometimes I have to use older scripts that does not run because of module incompatibility (for example the script was written using pandas 0.15.0 and matplotlib 1.3.0, and now I use pandas 0... | 0 | 2016-06-06T15:57:23Z | 37,661,976 | <p><a href="https://www.python.org/dev/peps/pep-0518/" rel="nofollow" title="PEP 518 -- Specifying Minimum Build System Requirements for Python Projects">PEP 518</a> has been accepted recently regarding your question.</p>
<p>Dependencies has to be stored in a specific file <em><code>pyproject.toml</code></em></p>
<pr... | 1 | 2016-06-06T16:02:19Z | [
"python",
"module",
"documentation",
"pep"
] |
Python best way to document imported module version in scripts | 37,661,876 | <p>What is the best way or PEP convention to document the versions of <strong>imported modules</strong> in single python scripts? Sometimes I have to use older scripts that does not run because of module incompatibility (for example the script was written using pandas 0.15.0 and matplotlib 1.3.0, and now I use pandas 0... | 0 | 2016-06-06T15:57:23Z | 37,662,354 | <p>The best way to add information on your script is whit metadata, for example:</p>
<pre><code>__version__="1.0.2"
__appname__="name script"
__author__="author"
__description__="short description"
__long_description__="long description for your script"
__author_email__="author@gmail.com"
</code></pre>
| 0 | 2016-06-06T16:22:09Z | [
"python",
"module",
"documentation",
"pep"
] |
Running a perl script in python and storing the output in a file | 37,661,984 | <p>I'm trying to run </p>
<pre><code>script.pl < input > output
</code></pre>
<p>In python. I tried this:</p>
<pre><code>subprocess.check_call(["script.pl","<","input",">","output"])
</code></pre>
<p>Which I guess is not the proper way to do it.
Any help would be much appreciated!</p>
| 1 | 2016-06-06T16:02:32Z | 37,662,323 | <p>You want to execute the shell command</p>
<pre><code>script.pl < input > output # 0 args, redirects stdin and stdout
</code></pre>
<p>but you are executing the shell command</p>
<pre><code>script.pl "<" input ">" output # 4 args, and no redirections
</code></pre>
<p>If you want to... | 3 | 2016-06-06T16:20:37Z | [
"python"
] |
Running a perl script in python and storing the output in a file | 37,661,984 | <p>I'm trying to run </p>
<pre><code>script.pl < input > output
</code></pre>
<p>In python. I tried this:</p>
<pre><code>subprocess.check_call(["script.pl","<","input",">","output"])
</code></pre>
<p>Which I guess is not the proper way to do it.
Any help would be much appreciated!</p>
| 1 | 2016-06-06T16:02:32Z | 37,669,120 | <p>Keep it simple,</p>
<pre><code>import os
os.system("script.pl < input > output")
</code></pre>
| 0 | 2016-06-07T01:24:46Z | [
"python"
] |
Android Appium Python - element.get_attribute('text') returns no text | 37,661,988 | <p>I try to get the text attribute of an element in hybrid app.</p>
<pre><code>def test_example(driver):
el = driver.find_element_by_id('com.access_company.twine.android.dmc:id/btnVideos')
print el.get_attribute("text")
</code></pre>
<p>so there is a button with video icon and a text "Videos". Unfortunately th... | 0 | 2016-06-06T16:02:49Z | 37,664,992 | <p>For the text of the stated element try the following code : </p>
<pre><code>el = driver.find_element_by_id('com.access_company.twine.android.dmc:id/btnVideos')
print el.text
</code></pre>
<p>Also <code>el.get_attribute("resourceId")</code> shall ideally return <em>"btnVideos"</em></p>
| 0 | 2016-06-06T19:02:21Z | [
"android",
"python",
"testing",
"automation",
"appium"
] |
Android Appium Python - element.get_attribute('text') returns no text | 37,661,988 | <p>I try to get the text attribute of an element in hybrid app.</p>
<pre><code>def test_example(driver):
el = driver.find_element_by_id('com.access_company.twine.android.dmc:id/btnVideos')
print el.get_attribute("text")
</code></pre>
<p>so there is a button with video icon and a text "Videos". Unfortunately th... | 0 | 2016-06-06T16:02:49Z | 37,674,334 | <p>Ok. After investigating more time I found the solution and i feel so dumb now. There was a button, but this is not clickable so the id i was taking was not actually the button with the text, but the parent which is a relative layout without text. duh.. By the way resourceId doesn't return only "btnVideos" but the fu... | 0 | 2016-06-07T08:33:34Z | [
"android",
"python",
"testing",
"automation",
"appium"
] |
Which pip is with which python? | 37,662,012 | <p>This is driving me crazy. I have tried to remove all the packages of python installed on <code>mac os x</code> <code>el capitan</code> and re-installed <code>brew install python</code> and <code>pip</code>. Here I have :</p>
<pre><code>which pip
/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2... | 0 | 2016-06-06T16:04:02Z | 37,666,909 | <p>You can run <code>pip</code> with a specific version of Python by running it as a module. Command line arguments work just as if running directly from the command line. For example, try:</p>
<pre><code>python -m pip list
</code></pre>
<p>If that still lists <code>numpy</code> it probably means there is something w... | 2 | 2016-06-06T21:06:24Z | [
"python",
"numpy",
"matplotlib",
"homebrew"
] |
Hide lines on tree view - openerp 7 | 37,662,048 | <p>I want to hide all lines (not only there cointaner) in sequence tree view (the default view).
I must hide all lines if code != 'foo' but the attrs atribute don't work on tree views, so how can i filter/hide this?</p>
<p>I don't have any code already, because i'm newbie in openerp and i dont know what to change.</p>... | -1 | 2016-06-06T16:06:22Z | 37,670,777 | <blockquote>
<p>Attrs is to be used to hide columns / fields conditionally but not the
record, to hide records domain must be used.</p>
</blockquote>
<p>If there is default tree view and you want to hide records from there then you must pass domain with action. And suppose there is one2many field and into that you... | 3 | 2016-06-07T04:55:34Z | [
"python",
"openerp",
"openerp-7"
] |
Is there a simple way to do all pairwise statistical comparisons of distributions from a pandas dataframe? | 37,662,052 | <p>I have a pandas dataframe with 5 distributions in it. I am able to slice it up and run pairwise comparisons using ranksums or equivalent, like this:</p>
<pre><code>case_1 = df[df['Symmetric Division Rate']=='1' and df['test']=='sackin']['value']
case_2 = df[df['Symmetric Division Rate']=='0.8' and df['test']=='sack... | 1 | 2016-06-06T16:06:28Z | 37,663,346 | <p>You could do something along these lines:</p>
<pre><code>from itertools import combinations
from scipy.stats import ranksums
</code></pre>
<p>Create your selectors:</p>
<pre><code>df.SymmetricDivisionRate = df.SymmetricDivisionRate.astype(str)
selectors = df.SymmetricDivisionRate.unique()
</code></pre>
<p>Create... | 2 | 2016-06-06T17:19:35Z | [
"python",
"python-3.x",
"pandas",
"scipy",
"statistics"
] |
Mutithreading in django when interactiong with database, what i need to know and pay attention to? | 37,662,074 | <p>My site will need to parse large amounts of data from multiple web pages in regular intervals. I'm thinking about using celery or python threads to speed that up. </p>
<p>I'm afraid of hard to debug errors when interacting with database.
For example is it possible/ what will happen when 2 threads will call <code>Sa... | -1 | 2016-06-06T16:07:22Z | 37,663,149 | <p>Bad things can certainly happen if you have enough requests per second. </p>
<p>What will happen if two threads call <code>SampleModel.object.get_or_create(name="same string")</code> simultaneously? What about if there are two processes instead? What if it is called by two worker nodes?</p>
<p>In cases like this, ... | 1 | 2016-06-06T17:07:43Z | [
"python",
"django",
"database",
"multithreading",
"django-celery"
] |
Add string to h5 file | 37,662,092 | <p>I have the following code:</p>
<pre><code>import tables
import numpy as np
filename = "file.h5"
x = np.random.random(150)
z = np.random.random(150)
mystr = " " * 160
f = tables.open_file(filename, mode="w")
hds = f.create_carray(f.root, "x", obj=x,
filters=tables.Filters(complevel=5, compl... | 0 | 2016-06-06T16:08:23Z | 37,665,039 | <p>With <code>h5py</code> you can store numpy arrays containing strings (or just one) as a dataset. Or you can store a string as an attribute of either a group or a dataset.</p>
<pre><code> http://docs.h5py.org/en/latest/strings.html
</code></pre>
<p>It can be as simple as:</p>
<pre><code>dset.attrs["title"] = "Hel... | 1 | 2016-06-06T19:04:50Z | [
"python",
"string",
"numpy",
"pytables"
] |
error: is not JSON serializable | 37,662,116 | <p>i have this in my python code: </p>
<pre><code>my_list=json.dumps(data_list)
payload = {'data_list' : my_list}
requests.get("http://127.0.0.1:8000/myhorizon/resource_usage/index",
json=payload)
</code></pre>
<p>and i use ajax to draw a curve with the information of my_list:</p>
<pre><code> <script>
fun... | 0 | 2016-06-06T16:09:43Z | 37,705,508 | <p>You're converting <code>data_list</code> to JSON format, but then you're storing it inside a regular Python dictionary, which is <em>not</em> JSON.</p>
<p>You need to first create the dictionary and <em>then</em> convert the entire thing to JSON.</p>
<p>Try this:</p>
<pre><code>my_list = {'data_list' : data_list}... | 0 | 2016-06-08T14:33:37Z | [
"python",
"html",
"json",
"ajax"
] |
interpolate missing values 2d python | 37,662,180 | <p>I have a 2d array(or matrix if you prefer) with some missing values represented as
<code>NaN</code>. The missing values are typically in a strip along one axis, eg:</p>
<pre><code>1 2 3 NaN 5
2 3 4 Nan 6
3 4 Nan Nan 7
4 5 Nan Nan 8
5 6 7 8 9
</code></pre>
<p>where I would like to repla... | 2 | 2016-06-06T16:12:46Z | 37,662,256 | <p>I'd actually manually go through this matrix row by row, and whenever you start encountering a list of Nans, keep track of the number immediately before the Nans and immediately after, and the number of Nans you saw before going back to ordinary numbers. Once those numbers are found, it would be possible to overwri... | 0 | 2016-06-06T16:16:54Z | [
"python",
"numpy",
"interpolation"
] |
interpolate missing values 2d python | 37,662,180 | <p>I have a 2d array(or matrix if you prefer) with some missing values represented as
<code>NaN</code>. The missing values are typically in a strip along one axis, eg:</p>
<pre><code>1 2 3 NaN 5
2 3 4 Nan 6
3 4 Nan Nan 7
4 5 Nan Nan 8
5 6 7 8 9
</code></pre>
<p>where I would like to repla... | 2 | 2016-06-06T16:12:46Z | 39,596,856 | <p>Yes you can use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html" rel="nofollow"><code>scipy.interpolate.griddata</code></a> and masked array and you can choose the type of interpolation that you prefer using the argument <code>method</code> usually <code>'cubic'</c... | 1 | 2016-09-20T14:31:38Z | [
"python",
"numpy",
"interpolation"
] |
Python: averaging across repeat dates | 37,662,254 | <p>I have a numpy array with <code>datetime</code> stored in array <code>A</code> of size 100 as:</p>
<pre><code>>>>A[0]
datetime.datetime(2011, 1, 1, 0, 0)
</code></pre>
<p>The other 99 elements are <code>datetime.datetime</code> objects also but few of them repeat e.g.</p>
<pre><code>A[55]
datetime.datet... | -1 | 2016-06-06T16:16:53Z | 37,665,644 | <p>I do actually concurr with @someone else, this could be achieved without digging into pandas. <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code></a> is really nice for this. Written for Python 3.5+(because of <code>statistics</code>:</p>
<pre><code>from itertools import... | 1 | 2016-06-06T19:45:02Z | [
"python",
"pandas",
"dataframe"
] |
how to add column on panda based on another column partial string | 37,662,273 | <p>I´m quite new with python and pandas. I´m trying to add a new column to a data frame (group column) with values based on a partial string in another column (user column). Users are coded like this: AA1, AA2, BB1, BB2 and so on. What I want is the group column to have a 'AA' value for all the AA users. After lookin... | 1 | 2016-06-06T16:18:00Z | 37,662,425 | <p>I think you can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.startswith.html" rel="nofollow"><code>str.startswith</code></a> or <a href="http:... | 0 | 2016-06-06T16:26:00Z | [
"python",
"pandas"
] |
how to add column on panda based on another column partial string | 37,662,273 | <p>I´m quite new with python and pandas. I´m trying to add a new column to a data frame (group column) with values based on a partial string in another column (user column). Users are coded like this: AA1, AA2, BB1, BB2 and so on. What I want is the group column to have a 'AA' value for all the AA users. After lookin... | 1 | 2016-06-06T16:18:00Z | 37,662,569 | <pre><code>df['group'] = ['AA' if x.startswith('AA') else 'other' for x in df['user']]
</code></pre>
<p>you just have an extra <code>x</code> before <code>x.startswith('AA')</code></p>
| 0 | 2016-06-06T16:33:13Z | [
"python",
"pandas"
] |
Django TypeError | 37,662,284 | <p>I get an error with model like this:</p>
<pre><code>class Project(models.Model): # Should Rename to Project Name
project_name = models.CharField(max_length=50)
frequency = models.PositiveIntegerField(blank=True)
related_tests = models.ManyToManyField(TestType)
creation_date = models.DateField()
... | 0 | 2016-06-06T16:18:18Z | 37,662,375 | <p>You don't need to pass <code>self</code> to <code>__init__</code> with <code>super</code>:</p>
<pre><code>super().__init__(*args, **kwargs)
</code></pre>
<p>Or in python 2, you should do:</p>
<pre><code>super(Project, self).__init__(*args, **kwargs)
</code></pre>
| 3 | 2016-06-06T16:23:27Z | [
"python",
"django"
] |
I have a list of 100K items to process. How to process this in concurrent manner using threads? | 37,662,414 | <p>I have list of 100000 items that needs to be posted to a URL end point.
If I were to process this sequentially, performance wise, this would be a long wait. Would this be solved via parallel process or concurrent future? Obviously each element in the list can only be posted once. Do I need to track the threads?</p>
| 0 | 2016-06-06T16:25:28Z | 37,663,123 | <p>Your problem looks IO bound, not CPU bound, so you may get nice performances by using <a href="http://aiohttp.readthedocs.io/en/stable/" rel="nofollow">aiohttp</a>, and use <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.wait" rel="nofollow">asyncio.wait</a> to wait them all to complete.</p>
| 1 | 2016-06-06T17:06:23Z | [
"python",
"multithreading",
"concurrency",
"parallel-processing",
"multiprocessing"
] |
Rename files using sub folder names | 37,662,505 | <p>My folder structure is as follows</p>
<pre><code>Folder A(Parent folder)
Folder B(Sub folder)
1.jpg
2.jpg
3.jpg
4.jpg
Folder B1(Sub folder)
1.jpg
2.jpg
3.jpg
4.jpg
.....
Folder Bn(Sub folder)
1.jpg
2.jpg
...jpg
</code></pre>
<p>How can I rename .jpeg filenames with s... | 0 | 2016-06-06T16:30:29Z | 37,662,662 | <p>Take <code>os.walk('pathToRootDir')</code>, in order to get sub folders recursively.</p>
<p>In the next step try to debug using print statements like </p>
<pre><code>print fname.split('.')
</code></pre>
<p>You'll find the error yourself, maybe take a deeper look into the split function and try something like:</p>... | 0 | 2016-06-06T16:38:16Z | [
"python",
"file",
"rename"
] |
Rename files using sub folder names | 37,662,505 | <p>My folder structure is as follows</p>
<pre><code>Folder A(Parent folder)
Folder B(Sub folder)
1.jpg
2.jpg
3.jpg
4.jpg
Folder B1(Sub folder)
1.jpg
2.jpg
3.jpg
4.jpg
.....
Folder Bn(Sub folder)
1.jpg
2.jpg
...jpg
</code></pre>
<p>How can I rename .jpeg filenames with s... | 0 | 2016-06-06T16:30:29Z | 37,663,129 | <p>Completing rocksteady answer, you could use os.walk and os.path.</p>
<pre><code>ROOT_DIR=os.getcwd()
for root, dirs, files in os.path.walk(ROOT_DIR):
dname = os.path.split(root)[-1]
for file in files:
os.rename(os.path.join(root, file),
os.path.join(root, "{}-{}".format(dname, fil... | 0 | 2016-06-06T17:06:37Z | [
"python",
"file",
"rename"
] |
How do I click the first link in a list using Selenium Webdriver | 37,662,506 | <p><a href="http://store.nike.com/us/en_us/pw/mens-nikeid-shoes/7puZoolZoi3" rel="nofollow">http://store.nike.com/us/en_us/pw/mens-nikeid-shoes/7puZoolZoi3</a></p>
<p>I am trying to click the first shoe listed in the store. I need to know how to reliably click the first shoe, as the store inventory changes daily, so ... | 1 | 2016-06-06T16:30:30Z | 37,662,546 | <p>The following CSS selector would match all products (shoes) on the page:</p>
<pre><code>.grid-item.nikeid
</code></pre>
<p>And if you use <code>driver.find_element_by_css_selector(".grid-item.nikeid").click()</code> - you would click the first shoe on the page.</p>
| 1 | 2016-06-06T16:32:04Z | [
"python",
"selenium-webdriver"
] |
How do I click the first link in a list using Selenium Webdriver | 37,662,506 | <p><a href="http://store.nike.com/us/en_us/pw/mens-nikeid-shoes/7puZoolZoi3" rel="nofollow">http://store.nike.com/us/en_us/pw/mens-nikeid-shoes/7puZoolZoi3</a></p>
<p>I am trying to click the first shoe listed in the store. I need to know how to reliably click the first shoe, as the store inventory changes daily, so ... | 1 | 2016-06-06T16:30:30Z | 37,678,078 | <p>You can also use below XPath to find the first link in the grid</p>
<pre><code>//*[contains(@class,'grid-item')]/a)[1]
</code></pre>
| 0 | 2016-06-07T11:25:33Z | [
"python",
"selenium-webdriver"
] |
Is there a way to get the username of the currently authenticated user in python Bottle using basic_auth? | 37,662,617 | <p>I would like to display the currently authorized user in a python Bottle session, where I am using basic_auth for the authorization framework. Is there a way to do that?</p>
| 0 | 2016-06-06T16:35:38Z | 37,688,292 | <p>You have two options:</p>
<pre><code>user = request.auth[0]
</code></pre>
<p>or</p>
<pre><code>user = request.environ.get('REMOTE_USER')
</code></pre>
| 0 | 2016-06-07T20:02:07Z | [
"python",
"basic-authentication",
"bottle"
] |
Extracting subsets of sequences with XPath | 37,662,732 | <p>I'm looking for an XPATH to extract 'sets' as separate sequences. It has to be interpreted by python <code>lxml</code> (which is a wrapper around <code>libxml2</code>).</p>
<p>For example, given the following:</p>
<pre><code><root>
<sub1>
<sub2>
<Container>
... | 1 | 2016-06-06T16:42:31Z | 37,663,243 | <pre><code>from lxml import etree
doc=etree.parse("data.xml");
v = doc.findall('sub1/sub2/Container')
finalResult = list()
for vv in v:
sequence = list()
for item in vv.findall('item'):
sequence.append(item.text)
finalResult.append(sequence)
print finalResult
</code></pre>
<p>And this is the resul... | 0 | 2016-06-06T17:13:42Z | [
"python",
"xml",
"xpath"
] |
Extracting subsets of sequences with XPath | 37,662,732 | <p>I'm looking for an XPATH to extract 'sets' as separate sequences. It has to be interpreted by python <code>lxml</code> (which is a wrapper around <code>libxml2</code>).</p>
<p>For example, given the following:</p>
<pre><code><root>
<sub1>
<sub2>
<Container>
... | 1 | 2016-06-06T16:42:31Z | 37,670,016 | <ol>
<li><p>Evaluate this XPath expression:</p>
<p><code>count(/*/*/*)</code></p></li>
</ol>
<p>This finds the number of <code><sub2></code> elements (equivalent and more readable, but longer, is:</p>
<pre><code>count(/*/sub1/sub2))
</code></pre>
<ol start="2">
<li><p>For each <code>$n</code> in 1 to <code>co... | 1 | 2016-06-07T03:30:17Z | [
"python",
"xml",
"xpath"
] |
Why DataFrame.sort_index retuns None? | 37,662,816 | <p>I have tried to sort data frame by index and have None as result. Why it happens?
This is my data frame <a href="http://screencast.com/t/zOEuR6Uu" rel="nofollow">http://screencast.com/t/zOEuR6Uu</a>
And I call:</p>
<pre><code>levelData.sort_index(inplace = True)
</code></pre>
<p>None (((</p>
<pre><code> levelData... | -3 | 2016-06-06T16:47:24Z | 37,662,919 | <p><code>DataFrame.sort_index</code> is following the <a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation" rel="nofollow">Command-Query separation principle</a> which says that a function should either be a command or a query but not both. </p>
<ul>
<li>Commands do something such as modify the call... | 2 | 2016-06-06T16:53:46Z | [
"python",
"sorting",
"pandas",
"dataframe"
] |
creating heatmap with matplotlib | 37,662,897 | <p>I have a numpy matrix <code>fooarray</code> of size 138 x 138. Each entry in row and column is a word. The following code is used to generate heatmap of the same matrix. But I am not able to show all the words in the plot.</p>
<p>It seems the values shown are also wrong in the color scale. While the values in matri... | 1 | 2016-06-06T16:52:09Z | 37,668,590 | <p>I have not clear why you are adding [' | '] and ['|'] in front of the labels, so I removed it from the code. The color scale works for me (see code), I believe there is something wrong with your data.</p>
<p>The code below control ticks positions with <code>set_xticks</code> and labels with <code>ax.set_xticklabels... | 3 | 2016-06-07T00:03:26Z | [
"python",
"numpy",
"matplotlib"
] |
Common elements of list of lists of lists | 37,662,954 | <p>I have a list of lists of lists. Is there any way that I can get the intersection of these. For eg.:</p>
<pre><code>a=[[[1, 2], [2, 3]], [[1, 2], [3, 4]], [[1, 2], [1, 4], [2, 4]]]
</code></pre>
<p>From this how can I get <code>[1,2]</code> as the result, which is the common element of those 3 lists of lists ?</p>... | 0 | 2016-06-06T16:55:31Z | 37,662,988 | <p>I might do it something like this:</p>
<pre><code>>>> sets = [set(tuple(lst) for lst in sublist) for sublist in a]
>>> sets
[set([(1, 2), (2, 3)]), set([(1, 2), (3, 4)]), set([(1, 2), (2, 4), (1, 4)])]
>>> sets[0].intersection(*sets[1:])
set([(1, 2)])
</code></pre>
<p>The first step is t... | 2 | 2016-06-06T16:57:59Z | [
"python",
"list",
"intersection"
] |
When using Bag.to_textfiles with dask, I get the error "AttributeError: 'dict' object has no attribute 'endswith'" | 37,663,006 | <p>Title says most of it
but the object in question is:</p>
<pre><code>>>> import dask.bag as db
>>> b = db.from_sequence([{'name': 'Alice', 'balance': 100},
... {'name': 'Bob', 'balance': 200},
... {'name': 'Charlie', 'balance': 300}],
... ... | 2 | 2016-06-06T16:59:06Z | 37,663,599 | <p>The <code>to_textfiles</code> function assumes that the elements of the bag are strings. I recommend mapping <code>str</code> on your bag first</p>
<pre><code>b.map(str).to_textfiles('*.json')
</code></pre>
<p>Or better yet, given that your output files are json, dump your data to json format explicitly</p>
<pre... | 1 | 2016-06-06T17:35:52Z | [
"python",
"dask"
] |
Saving Pandas dataframe indices to file | 37,663,085 | <p>I am trying to save just the indices of a dataframe to a file. Here is what I've tried:</p>
<p>A)</p>
<pre><code>np.savetxt("file_name", df.index.values)
</code></pre>
<p>returns:</p>
<pre><code>TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')
</code></pre>
<p>B)</p>
<pre><code... | 0 | 2016-06-06T17:04:00Z | 37,663,417 | <p>The error in A) is likely because you have strings or someother type of <code>object</code> in your index. The default format specifier in <code>np.savetxt</code> appears to assume the data is <code>float</code>-like. I got around this by setting <code>fmt='%s'</code>, though it likely isn't a reliable solution.</p... | 3 | 2016-06-06T17:23:32Z | [
"python",
"numpy",
"pandas"
] |
Heroku: Failed to git push | 37,663,095 | <p>Hi I am attempting to git push my python app, but constantly obtain error messages. This is the best that I can do so far. Errors below:</p>
<pre><code>remote: gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/... | 1 | 2016-06-06T17:04:46Z | 37,663,341 | <p>Did you follow all the steps in the heroku tutorial (all of them) ?</p>
| 0 | 2016-06-06T17:19:17Z | [
"python",
"git",
"heroku",
"deployment"
] |
Heroku: Failed to git push | 37,663,095 | <p>Hi I am attempting to git push my python app, but constantly obtain error messages. This is the best that I can do so far. Errors below:</p>
<pre><code>remote: gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/... | 1 | 2016-06-06T17:04:46Z | 37,663,673 | <p>I think I did, in my best knowledge. But did you see what would I have missed? I have a huge list of requirements.txt ( ~40 dependencies). Most of them are not used in my app. They are there because I pip freeze > requirements.txt
Would this huge list cause the problem?</p>
<p>Thank you.</p>
| 0 | 2016-06-06T17:40:24Z | [
"python",
"git",
"heroku",
"deployment"
] |
Can not install Paramiko in Cent OS | 37,663,119 | <p>Recently I am trying to learn python and write some scripts during work. However I found my python is not update to date. So I upgrade from 2.6 to 2.7.6 following some guide from network. After that the python, pip and easy_install seems all okay.
Then I tried to install Paramiko using pip. The error show the libff... | 1 | 2016-06-06T17:06:14Z | 37,664,054 | <p>I've finally found the solution for this. Thanks NepCoder!
I manually download the libffi-devel from page <a href="https://pkgs.org/centos-6/centos-x86_64/libffi-devel-3.0.5-3.2.el6.x86_64.rpm.html" rel="nofollow">https://pkgs.org/centos-6/centos-x86_64/libffi-devel-3.0.5-3.2.el6.x86_64.rpm.html</a>. Then using 'rpm... | 0 | 2016-06-06T18:05:57Z | [
"python",
"pip",
"paramiko",
"libffi"
] |
Django - how to bulk delete | 37,663,145 | <p>I'm working in a CRUD and one of the features of the list is bulk delete. The user chooses (checkbox) the lines he wants to delete and press the "Delete selected" button.</p>
<p>I'm using generic views in my CRUD. My single delete, for example is like this:</p>
<pre><code>class ContentDeleteView(NextRedirectMixin,... | 1 | 2016-06-06T17:07:09Z | 37,663,469 | <p>You should resort to rolling out your own kind of delete view, here is a basic example:</p>
<pre><code>class BulkDeleteView(View):
model = None
def post(self, request, *args, **kwargs):
delete_ids = request.POST['delete_ids'].split(',') # should validate
self.model.objects.filter(pk__in=de... | 1 | 2016-06-06T17:26:57Z | [
"python",
"django"
] |
How to iterate through nodes in scrapy using python | 37,663,181 | <p>I am trying to scrape a website and the content of the html looks something like this</p>
<pre><code><div class="panel-heading" role="tab" id="heading727654">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse72765... | 1 | 2016-06-06T17:09:40Z | 37,663,971 | <p>You need to <em>prepend dots</em> to your inner XPath expressions to make them work in the context of <code>node</code>. Otherwise the search starts from the root of the tree:</p>
<pre><code>def parse(self, response):
filename = response.url.split("/")[-2] + '.html'
with open(filename, 'wb') as f:
f... | 1 | 2016-06-06T17:59:45Z | [
"python",
"web-scraping",
"scrapy"
] |
python: call a function with parameter from input | 37,663,208 | <p>I have a list of tuples consisting of name, phone number and address, and a function called "all" which just shows a list of all the tuples (like in a phonebook). The function is called via input from a user.</p>
<p>I want another function, called "entry" which shows a specific entry of my list. This function shoul... | 0 | 2016-06-06T17:11:22Z | 37,663,339 | <p>I'm sorry if misunderstood your question, but it seems like you need function arguments. For example: if your `entry' program just prints out what the user put in, your code would look like this:</p>
<pre><code>def entry(user_input): # the variable in the parentheses is your argument--is a local variable ONLY used ... | 0 | 2016-06-06T17:19:13Z | [
"python",
"function"
] |
python: call a function with parameter from input | 37,663,208 | <p>I have a list of tuples consisting of name, phone number and address, and a function called "all" which just shows a list of all the tuples (like in a phonebook). The function is called via input from a user.</p>
<p>I want another function, called "entry" which shows a specific entry of my list. This function shoul... | 0 | 2016-06-06T17:11:22Z | 37,663,355 | <p>Have you looked into argparse?</p>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='your description')
parser.add_argument('-entry', dest="entry")
args = parser.parse_args()
print (args.entry)
</code></pre>
<p>You can then call this with <code>python yourfile.py -entry="this is the entry"</... | 0 | 2016-06-06T17:20:03Z | [
"python",
"function"
] |
Importing through folders | 37,663,219 | <p>I just want to make it clear that I'm not nooby at Python, and I am fully aware on how to import files, and use 'from' to import through folders.</p>
<p>However I want to import through two folders, if that makes sense. Say I have a folder called 'First Folder', and inside that folder I have another called 'Second ... | -1 | 2016-06-06T17:12:13Z | 37,663,308 | <p>You can do something like this.</p>
<pre><code>from first.second import abc
</code></pre>
<p>But file hierarchy should be like this.</p>
<pre><code>.
|-- first
|-- __init__.py
`-- second
|-- abc.py
|-- __init__.py
</code></pre>
| 1 | 2016-06-06T17:17:18Z | [
"python"
] |
How do I identify the user type of an IP address? Using python and requests/bs4/flask | 37,663,240 | <p>I'm using python with requests/bs4/flask and I'd like to identify the user type of an incoming IP request to my flask app.</p>
<p><a href="http://ipleak.net" rel="nofollow">http://ipleak.net</a> identifies the type as residential, college, cafe, corporate, ect but they only check your IP.</p>
<p><a href="https://w... | 0 | 2016-06-06T17:13:27Z | 37,664,492 | <p>I monitored the network traffic and found the call to check the type of IP. I wrote this function to check any IP that I pass to the function.</p>
<pre><code> import requests
from bs4 import BeautifulSoup
# check type of IP address
def ip_check(ip):
result = requests.get('https://ipleak.net/?mode=aj... | 0 | 2016-06-06T18:31:49Z | [
"python",
"ip",
"python-requests",
"ip-address"
] |
Reversing names in pandas | 37,663,258 | <p>I have a dataframe with a Name column like this:</p>
<p><img src="http://i.stack.imgur.com/sJED1.png" alt="Names col in DF"></p>
<p>How can I use pandas to reverse the names in the format "xxx, xxx" efficiently? Also if you have other string cleaning tips for munging names like these I would appreciate it!</p>
| 0 | 2016-06-06T17:14:26Z | 37,663,656 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/text.html" rel="nofollow"><code>Series.str.replace</code></a> to perform regex string substitutions:</p>
<pre><code>df['Name'] = df['Name'].str.replace(r'(.+),\s+(.+)', r'\2 \1')
</code></pre>
<p>The regex pattern <code>(.+), (.+)</code> means </p>
<pre><co... | 0 | 2016-06-06T17:39:35Z | [
"python",
"pandas"
] |
Reversing names in pandas | 37,663,258 | <p>I have a dataframe with a Name column like this:</p>
<p><img src="http://i.stack.imgur.com/sJED1.png" alt="Names col in DF"></p>
<p>How can I use pandas to reverse the names in the format "xxx, xxx" efficiently? Also if you have other string cleaning tips for munging names like these I would appreciate it!</p>
| 0 | 2016-06-06T17:14:26Z | 37,663,830 | <p>Maybe you can try something like this with <code>reverse</code> function:</p>
<pre><code>d = {'name':['Bran Stark','Jon Snow','Rhaegar Targaryen']}
df = pd.DataFrame(data=d)
df['new name'] = df['name'].apply(lambda x : ', '.join(reversed(x.split(' '))))
print(df['new name'])
0 Stark, Bran
1 S... | 0 | 2016-06-06T17:51:03Z | [
"python",
"pandas"
] |
Getting error when sending a char array to a DLL call "Don't know how to convert parameter" | 37,663,347 | <p>I am trying to recreate a DLL function call in Python. The code uses a DLL file to set the laser parameters for various material setting. Here is the original C# code:</p>
<pre><code>public bool ApplyLasFile(string strLasFile)
{
if (!File.Exists(strLasFile))
{
//MessageBox.Show("File not found", "Er... | 0 | 2016-06-06T17:19:35Z | 37,667,467 | <p>So this is weird. The function call requires a Char array, but putting the string strait into the function call within python seems to be getting the job done for some reason. I am new to python, so hopefully someday this will make sense to me.</p>
| 0 | 2016-06-06T21:56:18Z | [
"python",
"dllimport"
] |
Getting error when sending a char array to a DLL call "Don't know how to convert parameter" | 37,663,347 | <p>I am trying to recreate a DLL function call in Python. The code uses a DLL file to set the laser parameters for various material setting. Here is the original C# code:</p>
<pre><code>public bool ApplyLasFile(string strLasFile)
{
if (!File.Exists(strLasFile))
{
//MessageBox.Show("File not found", "Er... | 0 | 2016-06-06T17:19:35Z | 37,687,783 | <p>I suspect the reason that your code works unexpectedly is that the C function you are calling in the DLL takes a <code>char *</code> for its first parameter. I'm guessing its declaration looks something like:</p>
<pre><code>bool ApplyLAS(char *filename, int length);
</code></pre>
<p>I'm guessing the return type h... | 0 | 2016-06-07T19:30:42Z | [
"python",
"dllimport"
] |
how to create a three-point arc in pygame | 37,663,381 | <p>I need to draw an arc in pygame, through three points, however pygame's arc function doesn't seem to support this. I have researched three point arcs, both in and out of pygame, however cannot find anything that I understand and is useful.</p>
<p>I would ideally like a full code however any hints will be useful</p>... | 1 | 2016-06-06T17:21:24Z | 37,679,550 | <p>Here are some hints, which will require a little mathematics to finish. If you need more help, show more of your work and ask.</p>
<p>Let's say you want to draw a circular arc from point <code>a=(ax, ay)</code> through point <code>b=(bx, by)</code> to point <code>c=(cx, cy)</code>. You want to use the function</p>
... | 2 | 2016-06-07T12:34:36Z | [
"python",
"geometry",
"pygame"
] |
How to serialize dict in Django? | 37,663,418 | <p>I can't figure out how to serialize <code>cleaned_data</code> of some form. The problem probably is, that this <code>cleaned_data</code> contains <code>model objects</code>. I didn't find anything touching this problem so I'm asking here. </p>
<blockquote>
<p>Exception Value:<br>
'dict' object has no attribute ... | 0 | 2016-06-06T17:23:34Z | 37,668,774 | <p>The <code>Django</code> way to do this is to use <code>model_to_dict</code>. This will serialize the model instance as a dictionary. Call this on each model instance respectively in you <code>cleanded_data</code></p>
<pre><code>from django.forms.models import model_to_dict
model_to_dict(model_instance)
</code></p... | 0 | 2016-06-07T00:29:54Z | [
"python",
"django",
"serialization"
] |
websocket.recv() never returns inside another event loop | 37,663,560 | <p>I am currently developing a <strong>server</strong> program in Python that uses the websockets and asyncio packages.</p>
<p>I got a basic script handling websockets working (Exhibit A). This script locks when waiting for input, which is not what I want.</p>
<p>The solution for this that I imagine is I can start tw... | 2 | 2016-06-06T17:33:07Z | 37,665,147 | <p>Maybe the module websocket (unlike websockets) can help you.</p>
<p>The use of WebsocketApp is very simple:</p>
<pre><code>from websocket import WebSocketApp
class ExampleClass(object):
def __init__(self):
websocket.enableTrace(True)
self.ws = websocket.WebSocketApp("ws://echo.websocket.or... | -1 | 2016-06-06T19:12:02Z | [
"python",
"asynchronous",
"websocket",
"async-await"
] |
Python - cross array multiplication | 37,663,646 | <p>I'm developing a model based on neural network principals.
I have an entry layer, weights and an output layer:</p>
<pre><code>[1,2] -- [ [1,1] , [1,1] ] --> [3,3]
</code></pre>
<p><a href="http://i.stack.imgur.com/O52XW.png" rel="nofollow"><img src="http://i.stack.imgur.com/O52XW.png" alt="Simple Neural Network... | 0 | 2016-06-06T17:38:36Z | 37,663,795 | <p>You can implement this with <code>numpy.dot</code> </p>
<pre><code>In [1]: import numpy as np
In [2]: a
Out[2]: array([1, 2])
In [3]: b
Out[3]:
array([[1, 1],
[1, 1]])
In [4]: np.dot(a,b)
Out[4]: array([3, 3])
</code></pre>
<p>Here is more <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated... | 2 | 2016-06-06T17:49:03Z | [
"python",
"numpy",
"neural-network"
] |
HTML WebPy multilpe forms | 37,663,787 | <p>I have a rather silly question.</p>
<p>I am trying an app and have two forms on it:</p>
<p>Enter a zip code (submit button)<br>
or<br>
Login if you already have a user id. (submit button)</p>
<p>Now in my code (python using <code>web.py</code> framework) i have two <code>def POST(self)</code> but which one will t... | 0 | 2016-06-06T17:48:34Z | 37,664,558 | <p>you may have as many forms on the page as you want, the only issue is how you will handle them.</p>
<p>there are 2 options:</p>
<ol>
<li>two separate backends e.g. <code>/login</code> and <code>/zip</code> to handle POSTs from forms - in the form tag you will need to add <code>action</code> attribute to direct POS... | 0 | 2016-06-06T18:35:56Z | [
"python",
"forms",
"web.py"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.