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
"Backlog" of a loop through a list in Python
39,785,543
<p>I have a weird Python beginner's question,.. playing around in my virtual env in the interpreter (python 3.5):</p> <p>I have a list with mixed types: </p> <pre><code>lissi = ["foo", "bar". "boo", "baz", 4, 7] </code></pre> <p>And then "accidentally" try to print out all elements in a <strong>for loop</strong> concatenated to a string:</p> <pre><code>for x in lissi: print("Hallo " + x) </code></pre> <p>This, of course, is not possible bcs. we cannot conc. integers to a String - so the first elements are printed and then there is a TypeError. </p> <p>Then I typed just <code>"x" and enter</code> to see if there is still data stored and yes it is: <strong>x is 4</strong>. </p> <p><code>type(x)</code> is <code>int</code> (tried that to figure out if 7 is also still there).</p> <p>So my question is: What happens "under the hood" in Python in the for loop: Seems as if every successfully processed element is removed, but there is a backlog stored in x which is the first element the TypeError was thrown for? And is there a way to "clear" this data from memory in case of errors? </p> <p>thx</p>
0
2016-09-30T07:00:56Z
39,785,691
<p>It's not a backlog and nothing like "every successfully processed element is removed".<br> Basically on every iteration <code>for</code> loop assigns to variable <code>x</code> the value of next element of list <code>lissi</code> (doesn't have to be a list, can be any iterable).<br> Whenever the loop breaks, due to exception or <code>break</code> statement, variable <code>x</code> is left intact, so it contains the last value assigned by the <code>for</code> loop.<br> This is ok, since loops don't have any isolated scope in Python and actually makes it convenient to search iterable for interesting element, breaking the loop when it's found and not being forced to store it in another variable before leaving the loop. </p>
1
2016-09-30T07:09:57Z
[ "python", "python-3.x", "for-loop", "memory" ]
Python button functions oddly not doing the same
39,785,577
<p>I currently have 2 buttons hooked up to my Raspberry Pi (these are the ones with ring LED's in them) and I'm trying to perform this code</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(17, GPIO.OUT) #green LED GPIO.setup(18, GPIO.OUT) #red LED GPIO.setup(4, GPIO.IN, GPIO.PUD_UP) #green button GPIO.setup(27, GPIO.IN, GPIO.PUD_UP) #red button def remove_events(): GPIO.remove_event_detect(4) GPIO.remove_event_detect(27) def add_events(): GPIO.add_event_detect(4, GPIO.FALLING, callback=green, bouncetime=800) GPIO.add_event_detect(27, GPIO.FALLING, callback=red, bouncetime=800) def red(pin): remove_events() GPIO.output(17, GPIO.LOW) print "red pushed" time.sleep(2) GPIO.output(17, GPIO.HIGH) add_events() def green(pin): remove_events() GPIO.output(18, GPIO.LOW) print "green pushed" time.sleep(2) GPIO.output(18, GPIO.HIGH) add_events() def main(): while True: print "waiting" time.sleep(0.5) GPIO.output(17, GPIO.HIGH) GPIO.output(18, GPIO.HIGH) GPIO.add_event_detect(4, GPIO.FALLING, callback=green, bouncetime=800) GPIO.add_event_detect(27, GPIO.FALLING, callback=red, bouncetime=800) if __name__ == "__main__": main() </code></pre> <p>On the surface it looks like a fairly easy script. When a button press is detected:</p> <ol> <li>remove the events</li> <li>print the message </li> <li>wait 2 seconds before adding the events and turning the LED's back on </li> </ol> <p>Which normally works out great when I press the green button. I tried it several times in succession and it works without fail. With the red, however, it works well the first time, and the second time, but after it has completed it second red(pin) cycle the script just stops.</p> <p>Considering both events are fairly similar, I can't explain why it fails on the end of the 2nd red button.</p> <p><strong>EDIT: I have changed the pins from red and green respectively (either to different pin's completely or swap them). Either way, it's always the red button code (actually now green button) causes an error. So it seems its' not a physical red button problem, nor a pin problem, this just leaves the code to be at fault...</strong></p>
12
2016-09-30T07:03:15Z
39,886,705
<p>I was able to reproduce your problem on my Raspberry Pi 1, Model B by running your script and connecting a jumper cable between ground and GPIO27 to simulate red button presses. (Those are pins 25 and 13 on my particular Pi model.) </p> <p>The python interpreter is crashing with a Segmentation Fault in the thread dedicated to polling GPIO events after <code>red</code> returns from handling a button press. After looking at the implementation of the Python <code>GPIO</code> module, it is clear to me that it is unsafe to call <code>remove_event_detect</code> from within an event handler callback, and this is causing the crash. In particular, removing an event handler while that event handler is currently running can lead to memory corruption, which will result in crashes (as you have seen) or other strange behaviors. </p> <p>I suspect you are removing and re-adding the event handlers because you are concerned about getting a callback during the time when you are handing a button press. There is no need to do this. The GPIO module spins up a single polling thread to monitor GPIO events, and will wait for one callback to return before calling another, regardless of the number of GPIO events you are watching.</p> <p>I suggest you simply make your calls to <code>add_event_detect</code> as your script starts, and never remove the callbacks. Simply removing <code>add_events</code> and <code>remove_events</code> (and their invocations) from your script will correct the problem.</p> <p>If you are interested in the details of the problem in the <code>GPIO</code> module, you can take a look at the <a href="https://pypi.python.org/packages/c1/a8/de92cf6d04376f541ce250de420f4fe7cbb2b32a7128929a600bc89aede5/RPi.GPIO-0.6.2.tar.gz">C source code for that module</a>. Take a look at <code>run_callbacks</code> and <code>remove_callbacks</code> in the file <code>RPi.GPIO-0.6.2/source/event_gpio.c</code>. Notice that both of these functions use a global chain of <code>struct callback</code> nodes. <code>run_callbacks</code> walks the callback chain by grabbing one node, invoking the callback, and then following that node's link to the next callback in the chain. <code>remove_callbacks</code> will walk the same callback chain, and free the memory associated with the callbacks on a particular GPIO pin. If <code>remove_callbacks</code> is called in the middle of <code>run_callbacks</code>, the node currently held by <code>run_callbacks</code> can be freed (and have its memory potentially reused and overwritten) before the pointer to the next node is followed.</p> <p>The reason you see this problem only for the red button is likely due to the order of calls to <code>add_event_detect</code> and <code>remove_event_detect</code> causes the memory previously used by the callback node for the red button to be reclaimed for some other purpose and overwritten earlier than the memory used from the green button callback node is similarly reclaimed. However, be assured that the problem exists for both buttons -- it is just luck that that the memory associated with the green button callback isn't changed before the pointer to the next callback node is followed.</p> <p>More generally, there is a concerning lack of thread synchronization around the callback chain use in the GPIO module in general, and I suspect similar problems could occur if <code>remove_event_detect</code> or <code>add_event_detect</code> are called while an event handler is running, even if events are removed from another thread! I would suggest that the author of the <code>RPi.GPIO</code> module should use some synchronization to ensure that the callback chain can't be modified while callbacks are being made. (Perhaps, in addition to checking whether the chain is being modified on the polling thread itself, <code>pthread_mutex_lock</code> and <code>pthread_mutex_unlock</code> could be used to prevent other threads from modifying the callback chain while it is in use by the polling thread.)</p> <p>Unfortunately, that is not currently the case, and for this reason I suggest you avoid calling <code>remove_event_detect</code> entirely if you can avoid it.</p>
9
2016-10-06T02:45:36Z
[ "python", "raspberry-pi", "gpio" ]
ValueError: Filter must not be larger than the input
39,785,661
<p>I am pretty new to machine learning so I am playing around with examples and such. The image size specified in the code is (28,28) But for some reason I keep getting the same ValueError I cant figure out why this is happening.</p> <p>Here's the code:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(1337) # for reproducibility from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.utils import np_utils # input image dimensions img_rows, img_cols = 28, 28 batch_size = 128 # Number of images used in each optimization step nb_classes = 10 # One class per digit nb_epoch = 35 # Number of times the whole data is used to learn # Read the train and test datasets train = pd.read_csv("../input/train.csv").values test = pd.read_csv("../input/test.csv").values # Reshape the data to be used by a Theano CNN. Shape is # (nb_of_samples, nb_of_color_channels, img_width, img_heigh) X_train = train[:, 1:].reshape(train.shape[0], 1, img_rows, img_cols) X_test = test.reshape(test.shape[0], 1, img_rows, img_cols) y_train = train[:, 0] # First data is label (already removed from X_train) # Make the value floats in [0;1] instead of int in [0;255] X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 # convert class vectors to binary class matrices (ie one-hot vectors) Y_train = np_utils.to_categorical(y_train, nb_classes) #Display the shapes to check if everything's ok print('X_train shape:', X_train.shape) print('Y_train shape:', Y_train.shape) print('X_test shape:', X_test.shape) model = Sequential() # For an explanation on conv layers see http://cs231n.github.io/convolutional-networks/#conv # By default the stride/subsample is 1 # border_mode "valid" means no zero-padding. # If you want zero-padding add a ZeroPadding layer or, if stride is 1 use border_mode="same" model.add(Convolution2D(12, 5, 5, border_mode='valid',input_shape=(1,img_rows, img_cols))) model.add(Activation('relu')) # For an explanation on pooling layers see http://cs231n.github.io/convolutional-networks/#pool model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.15)) model.add(Convolution2D(24, 5, 5)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.15)) # Flatten the 3D output to 1D tensor for a fully connected layer to accept the input model.add(Flatten()) model.add(Dense(180)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(100)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) #Last layer with one output per class model.add(Activation('softmax')) #We want a score simlar to a probability for each class # The function to optimize is the cross entropy between the true label and the output (softmax) of the model # We will use adadelta to do the gradient descent see http://cs231n.github.io/neural-networks-3/#ada model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=["accuracy"]) # Make the model learn model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1) # Predict the label for X_test yPred = model.predict_classes(X_test) # Save prediction in file for Kaggle submission np.savetxt('mnist-pred.csv', np.c_[range(1,len(yPred)+1),yPred], delimiter=',', header = 'ImageId,Label', comments = '', fmt='%d') </code></pre>
-1
2016-09-30T07:08:19Z
39,805,029
<p>So the problem is with the convolution sizes used. Convolution operations usually <strong>reduce</strong> dimension of the image. Similarly - each pooling operation reduces the size. You have very small images yet applied model architecture which has been designed for a bigger ones, thus at some point, after one of the convolutions/poolings you actually have a smaller outputed image than a following filter size, and this is an ill-defined operation. </p> <p>To temporarly fix the problem - remove second convolution and maxpooling layers, since these operations (with parameters provided) cannot be performed on such small data. In general you should first understand how convolution works, and not apply someone elses model, since the parameters are crucial for good performance - if you apply transformations which reduce resolution to much - you will be unable to learn anything. Thus once you have some intuition how convolution works you can go back and try different architectures, but there is no one, "magical" equation to figure out the architecture, thus I cannot provide you with parameters that will "just work" - start with removing this additional convolution and pooling, and than go back and try other possibilities once you have better understanding of your data and model.</p>
0
2016-10-01T09:31:37Z
[ "python", "pandas", "machine-learning", "keras" ]
I have tried to correct this Django Object set error but it has failed
39,785,662
<pre><code>from django.db import models class Gallery(models.Model): Title = models.CharField(max_length=250) Category = models.CharField(max_length=250) Gallery_logo = models.CharField(max_length=1000) def __str__(self): return self.Title + '_' + self.Gallery_logo class Picture (models.Model): Gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) Title = models.CharField(max_length=250) Artist = models.CharField(max_length=250) Price = models.CharField(max_length=20) def __str__(self): return self.Title </code></pre> <p>I keep getting this error:</p> <pre><code>Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'Gallery' object has no attribute 'pic_set' </code></pre> <p>I am using Pycharm 2016 and I just began self learning Django yesterday.</p>
1
2016-09-30T07:08:22Z
39,785,861
<p>Since you have just started to learn django , let me point out that field names should begin with a lower case letter. (It's not an error to use upper case but it's confusing and not the standard)</p> <pre><code>class Gallery(models.Model): title = models.CharField(max_length=250) category = models.CharField(max_length=250) gallery_logo = models.CharField(max_length=1000) def __str__(self): return self.Title + '_' + self.Gallery_logo class Picture (models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) title = models.CharField(max_length=250) artist = models.CharField(max_length=250) price = models.CharField(max_length=20) </code></pre> <p>Now when you define the foreign key relationship as above. Each Gallery instead has a <code>picture_set</code> that name come from the model name you have chosen which in this case is <code>Picture</code></p>
1
2016-09-30T07:20:23Z
[ "python", "django" ]
interacting with objects in execfile/subprocess.call on python file with arguments
39,785,663
<p>Python novice here.</p> <p>I am trying to interact with the variables/objects in a python file that requires arguments for its data. <strong>Let's say I can only get this data from arguments</strong>, rather than make a script that includes arguments that would be passed (which means I must use execfile or subprocess.call).</p> <p>Let's say this was my python file, foo.py:</p> <pre><code>bar = 123 print("ran foo.py, bar = %d" % bar) </code></pre> <p>Of course, there would be more to the file to parse arguments, but that is irrelevant.</p> <p>Now, in a python shell (either python or ipython in a terminal):</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.call("python foo.py 'args'", shell=True) ran foo.py, bar = 123 0 &gt;&gt;&gt; bar Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'bar' is not defined </code></pre> <p>As the example output above shows, bar is not defined after stdout from foo.py.</p> <p>Is there any way to interact with variables or data objects in a python file called by execfile or subprocess.call? Normally I would eval in a REPL or run in an IDE so I can test out values and objects after execution, but I cannot figure out how to do this with a python file that builds data from parsed arguments.</p> <p>Does anyone know how I can do this? Thanks for your consideration, at any rate.</p>
0
2016-09-30T07:08:24Z
39,785,921
<p>Is foo.py under your control? If yes, simply change it, such that it can be run by being imported as module and interacted with. If no, you may need to catch the output as string and newly build your variable <code>bar</code> from it. How you capture the output of a subprocess is answered here for example: <a href="http://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output">Running shell command from Python and capturing the output</a></p>
0
2016-09-30T07:24:16Z
[ "python", "ipython" ]
Azure python create empty vhd blob
39,785,735
<p>I am using Azure python API to create page blob create_blob and updating the header using the link provided <a href="http://blog.stevenedouard.com/create-a-blank-azure-vm-disk-vhd-without-attaching-it/" rel="nofollow">http://blog.stevenedouard.com/create-a-blank-azure-vm-disk-vhd-without-attaching-it/</a> and updating my actual image data using update_page but when i am trying to boot the VHD i am getting provision error in Azure. "Could not provision the virtual machine" can any one please suggest.</p>
0
2016-09-30T07:12:15Z
39,788,280
<p>I think there may be something wrong with your vhd image. I would suggest you have a look at <a href="https://blogs.msdn.microsoft.com/narahari/2013/01/14/windows-azure-virtual-machines-gotchas/" rel="nofollow">this article</a>.</p> <p>Here is a snippet of that article:</p> <p>Please make sure of the following when uploading a VHD for use with Azure VMs:</p> <ul> <li>A VM must be generalized to use as an image from which you will create other VMs. For Windows, you generalize with the sysprep tool. For Linux you generalize with the Windows Azure Linux Agent (waagent). Provisioning will fail if you upload a VHD as an image that has not been generalized.</li> <li>A VM must not be generalized to use as a disk to only use as a single VM (and not base other VMs from it). Provisioning will fail if you upload a VHD as a disk that has generalized.</li> <li>When using third-party storage tools for the upload make sure to upload the VHD a page blob (provisioning will fail if the VHD was uploaded as a block blob). Add-AzureVHD and Csupload will handle this for you. It is only with third-party tools that you could inadvertantly upload as a block blob instead of a page blob.</li> <li><p>Upload only fixed VHDs (not dynamic, and not VHDX). Windows Azure Virtual Machines do not support dynamic disks or the VHDX format.<br> <strong>Note:</strong> Using CSUPLOAD or Add-AzureVHD to upload VHDs automatically converts the dynamic VHDs to fixed VHDs.</p></li> <li><p>Maximum size of VHD can be up to 127 GB. While data disks can be up to 1 TB, OS disks must be 127 GB or less.</p></li> <li>The VM must be configured for DHCP and not assigned a static IP address. Windows Azure Virtual Machines do not support static IP addresses.</li> </ul>
0
2016-09-30T09:34:45Z
[ "python", "azure" ]
Azure python create empty vhd blob
39,785,735
<p>I am using Azure python API to create page blob create_blob and updating the header using the link provided <a href="http://blog.stevenedouard.com/create-a-blank-azure-vm-disk-vhd-without-attaching-it/" rel="nofollow">http://blog.stevenedouard.com/create-a-blank-azure-vm-disk-vhd-without-attaching-it/</a> and updating my actual image data using update_page but when i am trying to boot the VHD i am getting provision error in Azure. "Could not provision the virtual machine" can any one please suggest.</p>
0
2016-09-30T07:12:15Z
39,788,981
<p>I think that there are two points that you could focus on.</p> <p>1.The VHD file should be a .vhd file. So ,your code should be 'blob_name='a-new-vhd.vhd''</p> <p>2.The storage account and the VM which you created should be in the same location.</p> <p>Hope it helps. Any concerns, please feel free to let me know.</p>
0
2016-09-30T10:08:34Z
[ "python", "azure" ]
Python compute a specific inner product on vectors
39,785,820
<p>Assume having two vectors with m x 6, n x 6</p> <pre><code>import numpy as np a = np.random.random(m,6) b = np.random.random(n,6) </code></pre> <p>using np.inner works as expected and yields</p> <pre><code>np.inner(a,b).shape (m,n) </code></pre> <p>with every element being the scalar product of each combination. I now want to compute a special inner product (namely Plucker). Right now im using</p> <pre><code>def pluckerSide(a,b): a0,a1,a2,a3,a4,a5 = a b0,b1,b2,b3,b4,b5 = b return a0*b4+a1*b5+a2*b3+a4*b0+a5*b1+a3*b2 </code></pre> <p>with a,b sliced by a for loop. Which is way too slow. Any plans on vectorizing fail. Mostly broadcast errors due to wrong shapes. Cant get np.vectorize to work either. Maybe someone can help here?</p>
1
2016-09-30T07:17:26Z
39,786,194
<p>There seems to be an indexing based on some random indices for pairwise multiplication and summing on those two input arrays with function <code>pluckerSide</code>. So, I would list out those indices, index into the arrays with those and finally use <code>matrix-multiplication</code> with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow"><code>np.dot</code></a> to perform the sum-reduction.</p> <p>Thus, one approach would be like this -</p> <pre><code>a_idx = np.array([0,1,2,4,5,3]) b_idx = np.array([4,5,3,0,1,2]) out = a[a_idx].dot(b[b_idx]) </code></pre> <p>If you are doing this in a loop across all rows of <code>a</code> and <code>b</code> and thus generating an output array of shape <code>(m,n)</code>, we can vectorize that, like so -</p> <pre><code>out_all = a[:,a_idx].dot(b[:,b_idx].T) </code></pre> <p>To make things a bit easier, we can re-arrange <code>a_idx</code> such that it becomes <code>range(6)</code> and re-arrange <code>b_idx</code> with that pattern. So, we would have :</p> <pre><code>a_idx = np.array([0,1,2,3,4,5]) b_idx = np.array([4,5,3,2,0,1]) </code></pre> <p>Thus, we can skip indexing into <code>a</code> and the solution would be simply -</p> <pre><code>a.dot(b[:,b_idx].T) </code></pre>
3
2016-09-30T07:41:04Z
[ "python", "numpy", "vector", "vectorization" ]
multiprocessing pool.map() got "TypeError: list indices must be integers, not str"
39,785,873
<p>I do a multiprocessing with python's <code>multiprocessing.Pool</code> module, but got <code>TypeError: list indices must be integers, not str</code> Error:</p> <p>Here is my code:</p> <pre><code> def getData(qid): r = requests.get("http://api.xxx.com/api?qid=" + qid) if r.status == 200: DBC.save(json.loads(r.text)) def getAnotherData(qid): r = requests.get("http://api.xxxx.com/anotherapi?qid=" + qid) if r.status == 200: DBC.save(json.loads(r.text)) def getAllData(qid): print qid getData(str(qid)) getAnotherData(str(qid)) if __name__ == "__main__": pool = Pool(processes=200) pool.map(getAllData, range(10000, 700000)) </code></pre> <p>After running the code for some time (not instantly), a Exception will be thrown out </p> <pre><code>pool.map(getAllData, range(10000, 700000)) File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get raise self._value TypeError: list indices must be integers, not str </code></pre> <p>What could be wrong? Is it a bug of the <code>Pool</code> module?</p>
0
2016-09-30T07:20:58Z
39,786,016
<p>When a worker task raises an exception, <code>Pool</code> catches it, sends it back to the parent process, and reraises the exception, but this doesn't preserve the original traceback (so you just see where it was reraised in the parent process, which isn't very helpful). At a guess, something in <code>DBC.save</code> expects a value loaded from the JSON to be an <code>int</code>, and it's actually a <code>str</code>.</p> <p>If you want to see the real traceback, <code>import traceback</code> at top level, and change the top level of your worker function to:</p> <pre><code>def getAllData(qid): try: print qid getData(str(qid)) getAnotherData(str(qid)) except: traceback.print_exc() raise </code></pre> <p>so you can see the real traceback in the worker, not just the neutered, mostly useless traceback in the parent.</p>
1
2016-09-30T07:29:55Z
[ "python", "multiprocessing" ]
unable to install JQ via PIP
39,785,890
<p>I am trying to install JQ via PIP in python.</p> <pre><code>pip install jq </code></pre> <p>I am getting following error.</p> <p><strong>Failed building wheel for jq</strong></p> <p><a href="http://i.stack.imgur.com/ywWcL.png" rel="nofollow"><img src="http://i.stack.imgur.com/ywWcL.png" alt="enter image description here"></a></p> <p>I am facing same issue while install pyjq.</p> <pre><code>pip install pyjq </code></pre> <p><strong>Failed building wheel for pyjq</strong></p> <p><a href="http://i.stack.imgur.com/2EoxV.png" rel="nofollow"><img src="http://i.stack.imgur.com/2EoxV.png" alt="enter image description here"></a></p>
2
2016-09-30T07:22:24Z
39,786,170
<p>It doesn't appear that jq supports Windows; it says it requires gcc &amp; libtool, which generally means a Unix-like environment.</p>
1
2016-09-30T07:40:02Z
[ "python", "python-2.7", "jq" ]
unable to install JQ via PIP
39,785,890
<p>I am trying to install JQ via PIP in python.</p> <pre><code>pip install jq </code></pre> <p>I am getting following error.</p> <p><strong>Failed building wheel for jq</strong></p> <p><a href="http://i.stack.imgur.com/ywWcL.png" rel="nofollow"><img src="http://i.stack.imgur.com/ywWcL.png" alt="enter image description here"></a></p> <p>I am facing same issue while install pyjq.</p> <pre><code>pip install pyjq </code></pre> <p><strong>Failed building wheel for pyjq</strong></p> <p><a href="http://i.stack.imgur.com/2EoxV.png" rel="nofollow"><img src="http://i.stack.imgur.com/2EoxV.png" alt="enter image description here"></a></p>
2
2016-09-30T07:22:24Z
39,839,370
<p>Like you I had a difficult time installing jq </p> <p>In my attempts I had many various errors including the failed building wheel that you are getting. I assume that the problem was on my end and not that the host was temporarily down. My setup: python 2 &amp; 3, Jupyter, brew in addition to pip. The problem was likely due to some lack of consistency in package links, brew doctor helped me identify which links were broken then brew link/unlink/overwrite. </p> <p>At anyrate I was only successful after brew uninstall jq, fixing all links, then updating brew and rebooting my system (perhaps some dependency was occupied?). </p> <p>Then and only then did finally <code>pip install jq</code> work</p>
0
2016-10-03T19:53:23Z
[ "python", "python-2.7", "jq" ]
How to get logged in username in views.py in django
39,785,934
<p>Actually i'am very new to django and python. In /templates/home.html, added <strong>{{ user.username }}</strong> it's showing currently logged in username</p> <pre><code>&lt;p&gt;Welcome {{ user.username }} !!!&lt;/p&gt; </code></pre> <p>I want to get currently logged in username in <strong>views.py</strong> file. How to get username?</p> <p>i tried different way but i am not get the result</p> <ol> <li><code>user = User.objects.get(username=request.user.username)</code></li> <li><code>username = request.GET['username']</code></li> <li><p><code>def sample_view(request): current_user = request.user print(current_user)</code></p></li> </ol> <p>Please tell me, How to achieve my result.</p> <p>my views.py look like this. is there any problem on my views.py</p> <pre><code> #!python #log/views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.template import Context from contextlib import contextmanager # Create your views here. # this login required decorator is to not allow to any # view without authenticating @login_required(login_url="login/") def home(request): return render(request,"home.html") #dummy_user = {{ username }} #user = User.objects.get(username=request.user.username) #username = request.GET['username'] #print(usernam #user = request.user #print(user) def sample_view(request): current_user = {} #current_user['loggeduser'] = request.user #or current_user['loggeduser'] = request.user.username return render(request,"home.html",current_user) # print(current_user.id) </code></pre>
0
2016-09-30T07:25:05Z
39,785,992
<p>Provided that you have enabled the <a href="https://docs.djangoproject.com/en/1.10/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware" rel="nofollow">authentication middleware</a>, you don't need to do any of this. The fact that the username shows up in your template indicates that you have enabled it. Each view has access to a <code>request.user</code> that is an instance of a <code>User</code> model. So the following is very much redundant</p> <pre><code>user = User.objects.get(username=request.user.username) </code></pre> <p>Because you already have <code>request.user.username</code>!! if you wanted to find the user's email, you do <code>request.user.email</code> Or just do</p> <pre><code>user = request.user </code></pre> <p>and use the newly created variable (eg user.username)</p> <p>Reference: <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.user" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.user</a></p> <blockquote> <p>From the AuthenticationMiddleware: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in, user will be set to an instance of AnonymousUser. You can tell them apart with is_authenticated, like so:</p> </blockquote>
1
2016-09-30T07:28:34Z
[ "python", "html", "django", "authentication", "oauth" ]
Speckle ( Lee Filter) in Python
39,785,970
<p>I am trying to do speckle noise removal in satellite SAR image.I am not getting any package which does speckle noise removal in SAR image. I have tried pyradar but it works with python 2.7 and I am working on Anaconda with python 3.5 on windows. Also Rsgislib is available but it is on Linux. Joseph meiring has also given a Lee filter code on github but it fails to work. : <a href="https://github.com/reptillicus/LeeFilter" rel="nofollow">https://github.com/reptillicus/LeeFilter</a></p> <p>Kindly, can anyone share the python script for Speckle Filter or how to proceed for speckle filter design in python.</p>
2
2016-09-30T07:27:01Z
39,786,527
<p>This is a fun little problem. Rather than try to find a library for it, why not write it from the definition?</p> <pre><code>from scipy.ndimage.filters import uniform_filter from scipy.ndimage.measurements import variance def lee_filter(img, size): img_mean = uniform_filter(img, (size, size)) img_sqr_mean = uniform_filter(img**2, (size, size)) img_variance = img_sqr_mean - img_mean**2 overall_variance = variance(img) img_weights = img_variance**2 / (img_variance**2 + overall_variance**2) img_output = img_mean + img_weights * (img - img_mean) return img_output </code></pre> <p>If you don't want the window to be a square of size x size, just replace uniform_filter with something else (convolution with a disk, etc)</p> <p>This seems rather old-fashioned as a filter, it won't behave well at edges. You may want to look into modern edge-aware denoisers, like guided filter or bilateral filter.</p>
0
2016-09-30T08:01:15Z
[ "python", "python-3.x", "image-processing", "imagefilter", "sar" ]
custom decorator for class viewsets
39,785,980
<p>I have a view set like this </p> <pre><code>class NeProjectsViewSet(viewsets.ViewSet): def list(self, request,org_unique_id): ''' something ''' def create(self, request,org_unique_id): ''' something ''' def retrieve(self): ''' something ''' def update(self, request, pk): ''' something ''' def partial_update(self, request): ''' something ''' def destroy(self, request): ''' something ''' </code></pre> <p>and i've a method like this</p> <pre><code>def check_session(self,request): current_datetime = datetime.now() if ('last_login' in request.session): last = (current_datetime - datetime.strptime(request.session['last_login'], "%Y-%m-%d %H:%M:%S.%f")).seconds if last &gt; base.SESSION_IDLE_TIMEOUT: del request.session['token'] raise ValueError('Session Expired') else: request.session['last_login'] = str(current_datetime) return (request.session['token'] == request.META['HTTP_AUTHORIZATION']) </code></pre> <p>to validate session for every request, for that i need to call this method before every method in the viewset. I read somewhere writing custom decorator is better way, so how to implement custom decorator for my view set to check session for request</p>
0
2016-09-30T07:27:42Z
39,787,007
<p><em>Assuming you are using DRF.</em></p> <p>I think you are going in wrong direction. If this is part of your permission layer you should just add custom permission class to your viewset</p> <p><a href="http://www.django-rest-framework.org/api-guide/permissions/" rel="nofollow">http://www.django-rest-framework.org/api-guide/permissions/</a></p> <pre><code>from rest_framework import permissions class ValidateSession(permissions.BasePermission): """ Validate session expiration """ def has_permission(self, request, view): current_datetime = datetime.now() if ('last_login' in request.session): last = (current_datetime - datetime.strptime(request.session['last_login'], "%Y-%m-%d %H:%M:%S.%f")).seconds if last &gt; base.SESSION_IDLE_TIMEOUT: del request.session['token'] return False else: request.session['last_login'] = str(current_datetime) return (request.session['token'] == request.META['HTTP_AUTHORIZATION']) </code></pre> <p>And then add it like this</p> <pre><code>class NeProjectsViewSet(viewsets.ViewSet): permission_classes = (ValidateSession,) ... </code></pre> <p><em>Assuming you're using plain django</em></p> <pre><code>from django.contrib.auth.mixins import AccessMixin class ValidateSessionMixin(AccessMixin): """ Validate session """ def has_permission(self): current_datetime = datetime.now() request = self.request if ('last_login' in request.session): last = (current_datetime - datetime.strptime(request.session['last_login'], "%Y-%m-%d %H:%M:%S.%f")).seconds if last &gt; base.SESSION_IDLE_TIMEOUT: del request.session['token'] return True else: request.session['last_login'] = str(current_datetime) return (request.session['token'] == request.META['HTTP_AUTHORIZATION']) def dispatch(self, request, *args, **kwargs): if not self.has_permission(): return self.handle_no_permission() return super(ValidateSessionMixin, self).dispatch(request, *args, **kwargs) </code></pre> <p>And apply this mixin like this</p> <pre><code>class NeProjectsViewSet(ValidateSessionMixin, viewsets.ViewSet): ... </code></pre>
0
2016-09-30T08:30:07Z
[ "python", "django", "python-decorators" ]
How to create a formula that checks who won a tic-tac-toe game without lots of if statements?
39,786,013
<p>I have the following code and feel it could be more efficient. Meaning this is 3x3 board and could be done manually but what if it were a 30x30 board or bigger?</p> <pre><code>x = [[1, 2, 0],[2, 1, 0],[2, 1, 0]] for y in range (3): if ((x[0][0] == x[1][0] == x[2][0] == y) or (x[0][1] == x[1][1] == x[2][1] == y) or (x[0][2] == x[1][2] == x[2][2] == y) or (x[0][0] == x[0][1] == x[0][2] == y) or (x[1][0] == x[1][1] == x[1][2] == y) or (x[2][0] == x[2][1] == x[2][2] == y) or (x[0][0] == x[1][1] == x[2][2] == y) or (x[0][2] == x[1][1] == x[2][0] == y)): if y==1: print('Player 1 won!!!') if y==2: print('Player 2 won!!!') if y==0: print('Nobody won') </code></pre> <p>Is there a way to make the condition part better?</p>
2
2016-09-30T07:29:47Z
39,786,384
<p>If you don't mind about importing numpy, this would work for any square grid and any number of player:</p> <pre><code>import numpy as np def check(arr): def check_one_dim(arr): for player in np.arange(Nplayer)+1: # instead of Nplayer you could write arr.max() arrtest = arr == player s = arrtest.astype(int).prod(axis=0) t = arrtest.diagonal().astype(int).prod() if (s == 1).any() or t == 1: return player else: return 0 return max(check_one_dim(arr), check_one_dim(arr[::-1].T)) Nplayer = 2 x = np.array([[1, 2, 0],[2, 1, 0],[2, 1, 0]]) winner = check(x) if winner &gt; 0: print("Player {}").format(winner) else: print("No winner") </code></pre> <p>I am not sure it is faster, but there is less "ifs" :)</p>
0
2016-09-30T07:52:37Z
[ "python" ]
How to create a formula that checks who won a tic-tac-toe game without lots of if statements?
39,786,013
<p>I have the following code and feel it could be more efficient. Meaning this is 3x3 board and could be done manually but what if it were a 30x30 board or bigger?</p> <pre><code>x = [[1, 2, 0],[2, 1, 0],[2, 1, 0]] for y in range (3): if ((x[0][0] == x[1][0] == x[2][0] == y) or (x[0][1] == x[1][1] == x[2][1] == y) or (x[0][2] == x[1][2] == x[2][2] == y) or (x[0][0] == x[0][1] == x[0][2] == y) or (x[1][0] == x[1][1] == x[1][2] == y) or (x[2][0] == x[2][1] == x[2][2] == y) or (x[0][0] == x[1][1] == x[2][2] == y) or (x[0][2] == x[1][1] == x[2][0] == y)): if y==1: print('Player 1 won!!!') if y==2: print('Player 2 won!!!') if y==0: print('Nobody won') </code></pre> <p>Is there a way to make the condition part better?</p>
2
2016-09-30T07:29:47Z
39,788,018
<p>You could use a function generator like this:</p> <pre><code>def cell_owner(player): """returns a function which can check if a cell belongs to provided player""" def wrapped(cell): return player == cell return wrapped </code></pre> <p>So you can call <code>cell_owner(1)</code> to get a function which accept a value and checks if it is 1. This seems useless, but with such a function you can use <a href="https://docs.python.org/3.5/library/functions.html?highlight=all#all" rel="nofollow">all</a> and <a href="https://docs.python.org/3.5/library/functions.html?highlight=all#map" rel="nofollow">map</a> to check a whole cells group in one line:</p> <pre><code># will return True if each cell in &lt;cells_group&gt; belong to &lt;player&gt; all(map(cell_owner(&lt;player&gt;), &lt;cells_group&gt;) </code></pre> <p>Before, doing this, you can prepare a list of cells groups which are winnable and then iterate on the list applying the all/map functions to each group to determine is a player won.</p> <p>Below is a complete example with some extra-functions for test pupose:</p> <pre><code>import random def gen_random_grid(size): """just for test purpose: generate a randomly filled grid""" return [[random.randint(0, 2) for col in range(size)] for row in range(size)] def print_grid(grid): """just for test purpose: prints the grid""" size = len(grid) row_sep = "+{}+".format("+".join(["---"] * size)) row_fmt = "|{}|".format("|".join([" {} "] * size)) print(row_sep) for row in grid: print(row_fmt.format(*row)) print(row_sep) def cell_owner(player): """returns a function which can check is a cell belongs to provided player""" def wrapped(cell): return player == cell return wrapped def get_winner(grid): """determines if there is a winner""" size = len(grid) # prepare list of potentially winning cells groups cells_groups_to_check = grid[:] # rows cells_groups_to_check += [[grid[row][col] for row in range(size)] for col in range(size)] #cols cells_groups_to_check.append( [grid[index][index] for index in range(size)]) # diag 1 cells_groups_to_check.append( [grid[index][size - 1 - index] for index in range(size)]) # diag 2 winner = 0 for y in range(1, 3): # 0 is not a player, no need to test it # for each player... for group in cells_groups_to_check: # ... check if a cells group is complete if (all(map(cell_owner(y), group))): winner = y break if winner: break return winner # generate some random grids of different sizes TEST_GRIDS = [gen_random_grid(3) for _ in range(3)] TEST_GRIDS += [gen_random_grid(2) for _ in range(3)] TEST_GRIDS += [gen_random_grid(4) for _ in range(3)] # demonstration for grid in TEST_GRIDS: print_grid(grid) print("Winner is {}".format(get_winner(grid))) </code></pre> <p>Note this code should work for any size of <strong>square</strong> grid.</p>
0
2016-09-30T09:20:31Z
[ "python" ]
How to create a formula that checks who won a tic-tac-toe game without lots of if statements?
39,786,013
<p>I have the following code and feel it could be more efficient. Meaning this is 3x3 board and could be done manually but what if it were a 30x30 board or bigger?</p> <pre><code>x = [[1, 2, 0],[2, 1, 0],[2, 1, 0]] for y in range (3): if ((x[0][0] == x[1][0] == x[2][0] == y) or (x[0][1] == x[1][1] == x[2][1] == y) or (x[0][2] == x[1][2] == x[2][2] == y) or (x[0][0] == x[0][1] == x[0][2] == y) or (x[1][0] == x[1][1] == x[1][2] == y) or (x[2][0] == x[2][1] == x[2][2] == y) or (x[0][0] == x[1][1] == x[2][2] == y) or (x[0][2] == x[1][1] == x[2][0] == y)): if y==1: print('Player 1 won!!!') if y==2: print('Player 2 won!!!') if y==0: print('Nobody won') </code></pre> <p>Is there a way to make the condition part better?</p>
2
2016-09-30T07:29:47Z
39,815,136
<p>Your solution doesn't work, so efficiency is a secondary issue. Try:</p> <pre><code>x = [[0, 2, 1],[0, 2, 1],[0, 2, 0]] </code></pre> <p>You'll get two answers:</p> <pre><code>Nobody won Player 2 won!!! </code></pre> <p>When checking for no winners, you can't assume all zero in a row or a column means nobody won. (Though that does work for diagonals.)</p> <p>Here's an approach that should evaluate any N x N square:</p> <pre><code>x = [[1, 2, 0], [2, 1, 0], [2, 1, 0]] def winner(board): length = len(board) if all(x == board[0][0] for x in (x[dim][dim] for dim in range(1, length))): return board[0][0] if all(x == board[0][length - 1] for x in (x[dim][length - dim - 1] for dim in range(1, length))): return board[0][length - 1] for row in range(length): if board[row][0]: if all(x == board[row][0] for x in board[row][1:]): return board[row][0] for col in range(length): if board[0][col] and all(x == board[0][col] for x in (x[row][col] for row in range(1, length))): return board[0][col] return 0 y = winner(x) if y == 1: print('Player 1 won!!!') elif y == 2: print('Player 2 won!!!') elif y == 0: print('Nobody won') </code></pre> <p>Though you'll clearly need to fully test it before relying on it!</p>
-1
2016-10-02T08:17:24Z
[ "python" ]
Python join data lines together
39,786,091
<p>Hello i have dataset a few thousand lines which is split in even and odd number lines and i can't find a way to join them together again in the same line. Reading the file and overwriting it is fine or making a new file.</p> <p>I have found this <a href="http://stackoverflow.com/questions/17908317/python-even-numbered-lines-in-text-file">example</a> to print the seperate lines but can't get it to write it to file.</p> <p>I would like it to look like this:</p> <pre><code>Time = 1 Temperature1 = 24.75 Temperature2 = 22.69 Temperature3 = 20.19 RPM = -60.00 Time = 2 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00 etc... </code></pre> <p>Example of dataset:</p> <pre><code>Time = 1 Temperature1 = 24.75 Temperature2 = 22.69 Temperature3 = 20.19 RPM = -60.00 Time = 2 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00 Time = 3 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00 Time = 4 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.25 RPM = -60.00 Time = 5 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.19 RPM = -60.00 Time = 6 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.19 RPM = -60.00 Time = 7 Temperature1 = 24.81 Temperature2 = 22.81 Temperature3 = 20.25 RPM = -60.00 Time = 8 Temperature1 = 24.81 Temperature2 = 22.87 Temperature3 = 20.25 RPM = -60.00 Time = 9 Temperature1 = 24.87 Temperature2 = 22.87 Temperature3 = 20.25 RPM = -60.00 Time = 10 Temperature1 = 24.87 Temperature2 = 22.87 Temperature3 = 20.25 RPM = -60.00 </code></pre>
-1
2016-09-30T07:34:28Z
39,786,294
<p>You can use <code>%</code> (modulus) to determine if the line is odd or even. If it's even, then join together the last line and the current line.</p> <pre><code># Using your dataset as a string data_split = data.split("\n") for i in range(len(data_split)): if i % 2: lines = [data_split[i-1], data_split[i]] print " ".join(lines) </code></pre> <blockquote> <p>Output: </p> <p>Time = 1 Temperature1 = 24.75 Temperature2 = 22.69 Temperature3 = 20.19 RPM = -60.00</p> <p>Time = 2 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00</p> <p>Time = 3 Temperature1 = 24.75 Temperature2 = 22.75 Temperature3 = 20.19 RPM = -60.00</p> <p>...</p> </blockquote>
0
2016-09-30T07:47:25Z
[ "python", "python-2.7", "dataset" ]
Python: Function to return index starting from the end for a string
39,786,203
<p>Is there a function to return the end index instead of the start index of a substring. For example, for</p> <pre><code>string = 'the rain in spain stays mainly in the plain' </code></pre> <p><code>string.foo('mainly ')</code> returns 31, instead of having to use <code>string.index('mainly ')+len('mainly ')</code>? </p>
0
2016-09-30T07:41:44Z
39,786,341
<p>It can be easily implemented in two lines:</p> <pre><code>def get_sub_end(s, sub): f = s.find(sub) return f if f == -1 else f + len(sub) </code></pre> <p>Usage:</p> <pre><code>test_str = 'the rain in spain stays mainly in the plain' if __name__ == '__main__': print get_sub_end(test_str, "mainly ") # &gt;&gt;&gt; 31 print get_sub_end(test_str, "undefined ") # &gt;&gt;&gt; -1 </code></pre>
0
2016-09-30T07:50:20Z
[ "python", "string", "indexing", "slice" ]
candlestick function not displaying results
39,786,253
<p>When i execute this piece of code the program produces <code>[None, None, None,...]</code></p> <p>I am expecting candlestick diagram</p> <pre><code>import matplotlib.finance as mpf import matplotlib.pyplot as plt start =(2014,5,1) end = (2014,6,30) quotes = mpf.quotes_historical_yahoo_ochl('^GDAXI',start, end) fig, ax=plt.subplots(figsize=(8,5)) fig.subplots_adjust(bottom=0.2) mpf.candlestick_ochl(ax,quotes,width=0.6,colorup='b',colordown='r') plt.grid(True) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(),rotation=30) </code></pre>
0
2016-09-30T07:45:09Z
39,786,469
<p>You didn't actually <a href="http://stackoverflow.com/questions/8575062/how-to-show-matplotlib-plots-in-python">show</a> your plot on screen. When I copy your code and add</p> <pre><code>plt.show() </code></pre> <p>at the end of it, it runs just fine.</p>
0
2016-09-30T07:57:43Z
[ "python", "matplotlib" ]
Neural Network Inception v3 doesn't create labels
39,786,320
<p>I am facing an error with testing the Neural Network Inception v3 and Tensorflow.</p> <p>I avtivated and trained the model this way with Python:</p> <pre><code>source tf_files/tensorflow/bin/activate python tf_files/tensorflow/examples/image_retraining/retrain.py --bottleneck_dir=tf_files/bottlenecks --how_many_training_steps 500 --model_dir=tf_files/inception --output_graph=tf_files/retrained_graph.pb --output_labels=tf_files/retrained_labels.txt --image_dir tf_files/data </code></pre> <p>Which gave me the following error:</p> <blockquote> <p>CRITICAL:tensorflow:Label kiwi has no images in the category testing.</p> </blockquote> <p><code>Kiwi</code> is a folder which contains images. The other folder called <code>Apples</code> gave me no error. But maybe it occurs because it contains less than 20 images. And it doesn't create a file called <code>retrained_labels.txt</code>.</p> <p>So when executing following following command it gives me an error saying it couldn't find the file, which is mentioned above.</p> <pre><code>python image_label.py apple.jpg </code></pre> <p>Everything is in it's folders and the content of <code>image_label.py</code> is:</p> <pre><code>import tensorflow as tf import sys # change this as you see fit image_path = sys.argv[1] # Read in the image_data image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile("tf_files/retrained_labels.txt")] # Unpersists graph from file with tf.gfile.FastGFile("tf_files/retrained_graph.pb", 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') with tf.Session() as sess: # Feed the image_data as input to the graph and get first prediction softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') predictions = sess.run(softmax_tensor, \ {'DecodeJpeg/contents:0': image_data}) # Sort to show labels of first prediction in order of confidence top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] for node_id in top_k: human_string = label_lines[node_id] score = predictions[0][node_id] print('%s (score = %.5f)' % (human_string, score)) </code></pre>
0
2016-09-30T07:49:12Z
39,789,136
<p>I solved it. The error occured <strong>because the folder hadn't got enough images to train with</strong>. So after increasing the number of the images from 14 to 38 it gives me the predictions!</p>
0
2016-09-30T10:16:00Z
[ "python", "neural-network", "tensorflow" ]
How to match multiple columns in pandas DataFrame for an "interval"?
39,786,406
<p>I have the following pandas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame('filename.csv') print(df) order start end value 1 1342 1357 category1 1 1459 1489 category7 1 1572 1601 category23 1 1587 1599 category2 1 1591 1639 category1 .... 15 792 813 category13 15 892 913 category5 .... </code></pre> <p>So, there is an <code>order</code> column encompasses many rows each, and then a range/interval from <code>start</code> to <code>end</code> for each row. Each row then is labeled by a certain <code>value</code> (e.g. category1, category2, etc.)</p> <p>Now I have another dataframe called <code>key_df</code>. It is basically the exact same format:</p> <pre><code>import pandas as pd key_df = pd.DataFrame(...) print(key_df) order start end value 1 1284 1299 category4 1 1297 1309 category9 1 1312 1369 category3 1 1345 1392 category29 1 1371 1383 category31 .... 1 1471 1501 category31 ... </code></pre> <p>My goal is to take the <code>key_df</code> dataframe and check whether the intervals <code>start:end</code> match any of the rows in the original dataframe <code>df</code>. If it does, this row in <code>df</code> should be labeled with the <code>key_df</code> dataframe's <code>value</code> value. </p> <p>In our example above, the dataframe <code>df</code> would end up like this:</p> <pre><code>order start end value key_value 1 1342 1357 category1 category29 1 1459 1489 category7 category31 .... </code></pre> <p>This is because if you look at <code>key_df</code>, the row</p> <pre><code>1 1345 1392 category29 </code></pre> <p>with interval <code>1::1345-1392</code> falls in the interval <code>1::1342-1357</code> in the original <code>df</code>. Likewise, the <code>key_df</code> row:</p> <pre><code>1 1471 1501 category31 </code></pre> <p>corresponds to the second row in <code>df</code>:</p> <pre><code>1 1459 1489 category7 category31 </code></pre> <p>I'm not entirely sure</p> <p>(1) how to accomplish this task in pandas </p> <p>(2) how to scale this efficiently in pandas</p> <p>One could begin with an if statement, e.g. </p> <pre><code>if df.order == key_df.order: # now check intervals...somehow </code></pre> <p>but this doesn't take advantage of the dataframe structure. One then must check by interval, i.e. something like <code>(df.start =&lt; key_df.start) &amp;&amp; (df.end =&gt; key_df.end)</code></p> <p>I'm stuck. What is the most efficient way to match multiple columns in an "interval" in pandas? (Creating a new column if this condition is met is then straightforward)</p>
2
2016-09-30T07:54:23Z
39,786,538
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>, but if <code>DataFrames</code> are large, scaling is problematic:</p> <pre><code>df1 = pd.merge(df, key_df, on='order', how='outer', suffixes=('','_key')) df1 = df1[(df1.start &lt;= df1.start_key) &amp; (df1.end &lt;= df1.end_key)] print (df1) order start end value start_key end_key value_key 3 1 1342 1357 category1 1345.0 1392.0 category29 4 1 1342 1357 category1 1371.0 1383.0 category31 5 1 1342 1357 category1 1471.0 1501.0 category31 11 1 1459 1489 category7 1471.0 1501.0 category31 </code></pre> <p>EDIT by comment:</p> <pre><code>df1 = pd.merge(df, key_df, on='order', how='outer', suffixes=('','_key')) df1 = df1[(df1.start &lt;= df1.start_key) &amp; (df1.end &lt;= df1.end_key)] df1 = pd.merge(df, df1, on=['order','start','end', 'value'], how='left') print (df1) order start end value start_key end_key value_key 0 1 1342 1357 category1 1345.0 1392.0 category29 1 1 1342 1357 category1 1371.0 1383.0 category31 2 1 1342 1357 category1 1471.0 1501.0 category31 3 1 1459 1489 category7 1471.0 1501.0 category31 4 1 1572 1601 category23 NaN NaN NaN 5 1 1587 1599 category2 NaN NaN NaN 6 1 1591 1639 category1 NaN NaN NaN 7 15 792 813 category13 NaN NaN NaN 8 15 892 913 category5 NaN NaN NaN </code></pre>
1
2016-09-30T08:01:52Z
[ "python", "pandas", "dataframe", "match", "intervals" ]
Portable PySide libraries?
39,786,420
<p>Is there any way to execute python with pyside on a computer that has only python installed?</p> <p>I need to distribute a simple tool on a lot of computers and we can't install pyside everywhere.</p>
1
2016-09-30T07:55:27Z
39,787,158
<p>PySide is a set of bindings for Qt, which is a library written in C++. And it is not part of the Python core.</p> <p>If you want a GUI that is portable and that can be used with a default Python installation, consider <a href="https://docs.python.org/3/library/tk.html" rel="nofollow"><code>tkinter</code></a>.</p>
2
2016-09-30T08:38:52Z
[ "python", "pyside", "portability" ]
Robot Framework - get span element from table
39,786,528
<p>I'm trying to write some test cases to automatically test my websites but I'm having trouble clicking on checkbox witch is situated on every single row in the left column. User can click on every cell in the row he wants and checkbox will became checked or unchcked.. </p> <p>But I'm not able to simulate this click into table cell. First I'm trying to get some cell into variable and then to click on this cell using this variable like this:</p> <pre><code> Page Should Contain Element xpath=//div[contains(@id,'-tableCtrlCnt')] ${item1} Get Table Cell xpath=//div[contains(@id,'-tableCtrlCnt')]/table/tbody 1 2 Click Element ${item1} </code></pre> <p>But I'm getting error on the second line of code, I just cannot get the column.<br> The error/fail is:</p> <blockquote> <p>Cell in table xpath=//div[contains(@id,'-tableCtrlCnt')]/table/tbody in row #2 and column #2 could not be found.</p> </blockquote> <p>And this is how part of my html code looks like:</p> <pre><code>&lt;div id="__table1-tableCtrlCnt" class="sapUiTableCtrlCnt" style="height: 160px;"&gt; &lt;table id="__table1-table" role="presentation" data-sap-ui-table-acc-covered="overlay,nodata" class="sapUiTableCtrl sapUiTableCtrlRowScroll sapUiTableCtrlScroll" style="min-width:648px"&gt; &lt;tbody&gt; &lt;tr id="__table1-rows-row0" data-sap-ui="__table1-rows-row0" class="sapUiTableRowEven sapUiTableTr" data-sap-ui-rowindex="0" role="row" title="Click to select or press SHIFT and click to select a range" style="height: 32px;"&gt; &lt;td role="rowheader" aria-labelledby="__table1-ariarowheaderlabel" headers="__table1-colsel" aria-owns="__table1-rowsel0"&gt;&lt;/td&gt; &lt;td id="__table1-rows-row0-col0" tabindex="-1" role="gridcell" headers="__table1_col0" aria-labelledby="__table1-0" style="text-align:left" class="sapUiTableTd sapUiTableTdFirst"&gt; &lt;div class="sapUiTableCell"&gt; &lt;span id="__text37-col0-row0" data-sap-ui="__text37-col0-row0" title="1010" class="sapMText sapMTextMaxWidth sapMTextNoWrap sapUiSelectable" style="text-align:left"&gt;1010 &lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;td id="__table1-rows-row0-col1" tabindex="-1" role="gridcell" headers="__table1_col1" aria-labelledby="__table1-1" style="text-align:left" class="sapUiTableTd"&gt; &lt;div class="sapUiTableCell"&gt; &lt;span id="__text38-col1-row0" data-sap-ui="__text38-col1-row0" title="Company Code 1010" class="sapMText sapMTextMaxWidth sapMTextNoWrap sapUiSelectable" style="text-align:left"&gt;Company Code 1010 &lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; ... &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>Don't you have any idea how to solve this click into table issue?</p>
0
2016-09-30T08:01:17Z
39,894,954
<p>Check whether this helps you-</p> <pre><code>${item1} Get Table Cell xpath=//table[contains(@id,'__table1-table')] 1 2 </code></pre> <p><strong>OR</strong></p> <p>${item1} = Get Text //table[contains(@id,'__table1-table')]//tr[1]//td[2]//div/span</p>
0
2016-10-06T11:35:45Z
[ "python", "testing", "automated-tests", "pycharm", "robotframework" ]
Skip some bytes of a file and return content
39,786,543
<p>Given a list of byte ranges that have to be skipped:</p> <pre><code>skip_ranges = [(1, 3), (5,7)] </code></pre> <p>and a binary file:</p> <pre><code>f = open('test', 'rb') </code></pre> <p>What is the fastest way to return file contents without bytes 1-3 and 5-7 without modifying the original file?</p> <p>Input (file contents):</p> <pre><code>012345678 </code></pre> <p>Output:</p> <pre><code>048 </code></pre> <p>Please note that this question is specifically about (possibly large) binary files, so a generator would be the best.</p>
0
2016-09-30T08:02:10Z
39,786,625
<p>You said the file might potentially be huge so I have adapted @juanpa.arrivillaga solution to read the file in chunks and yield the individual chunks as a generator:</p> <pre><code>def read_ranges(filename, skip_ranges, chunk_size=1024): with open(filename, 'rb') as f: prev = -1 for start, stop in skip_ranges: end = start - prev - 1 # Go to next skip-part in chunk_size steps while end &gt; chunk_size: data = f.read(chunk_size) if not data: break yield data end -= chunk_size # Read last bit that didn't fit in chunk yield f.read(end) # Seek to next skip f.seek(stop + 1, 0) prev = stop else: # Read remainder of file in chunks while True: data = f.read(chunk_size) if not data: break yield data print list(read_ranges('test', skip_ranges)) </code></pre>
2
2016-09-30T08:07:03Z
[ "python", "python-2.7" ]
Skip some bytes of a file and return content
39,786,543
<p>Given a list of byte ranges that have to be skipped:</p> <pre><code>skip_ranges = [(1, 3), (5,7)] </code></pre> <p>and a binary file:</p> <pre><code>f = open('test', 'rb') </code></pre> <p>What is the fastest way to return file contents without bytes 1-3 and 5-7 without modifying the original file?</p> <p>Input (file contents):</p> <pre><code>012345678 </code></pre> <p>Output:</p> <pre><code>048 </code></pre> <p>Please note that this question is specifically about (possibly large) binary files, so a generator would be the best.</p>
0
2016-09-30T08:02:10Z
39,786,961
<p>This approach should be relatively fast:</p> <pre><code>ba = bytearray() with open('test.dat','rb') as f: prev = -1 for start, stop in skip_ranges: ba.extend(f.read(start - prev - 1)) f.seek(stop + 1,0) prev = stop else: ba.extend(f.read()) </code></pre>
0
2016-09-30T08:27:30Z
[ "python", "python-2.7" ]
How to show animation in Python while function is working?
39,786,565
<p>I have a loading-function:</p> <pre><code>def animation(loadingtext): word = list(loadingtext) for i in range(0,len(word)): os.system('cls') lower=word[i-1].lower() word[i-1]=lower caps=word[i].upper() word[i]=caps wordstr=''.join(word) print(wordstr) time.sleep(0.3) </code></pre> <p>And i want to display that function while some work is done (for example fetcha big SQL-Query). Or how can I make some other Loading animations? </p> <p>Thanks in advance, Patrick!</p>
0
2016-09-30T08:03:24Z
39,787,225
<p>First I would not use <code>system("cls")</code> at all: it clears the screen when it might be interesting to still see what was written. I would just prepend a <code>\r</code> to <code>wordstr</code>.</p> <p>Then to have <code>animation</code> to do its display while some other work is done, you could just repeatedly call them in a second thread waiting for some event, and set that event when the job is done.</p> <p>Here is what is could look like:</p> <pre><code>def animation(loadingtext): word = list(loadingtext) for i in range(0,len(word)): #os.system('cls') lower=word[i-1].lower() word[i-1]=lower caps=word[i].upper() word[i]=caps wordstr=''.join(word) sys.stdout.write('\r' + wordstr) time.sleep(0.3) def start_anim(txt): ev = threading.Event() def _loop(ev, txt): while not ev.is_set(): animation(txt) threading.Thread(target=_loop, args=(ev, txt)).start() return ev </code></pre> <p>You could then use it that way:</p> <pre><code>ev = start_anim(loadingtext) # heavy work - loadingtext is animated on screen ev.set() # stop the animation </code></pre>
0
2016-09-30T08:42:19Z
[ "python", "function", "animation", "loading" ]
python3 How do I click dropdown box using selenium
39,786,704
<p>I'm trying to click on dropbox using selenium on python3. but I got an error msg.</p> <pre><code> raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchWindowException: Message: Unable to find element on closed window </code></pre> <p>My code is below.</p> <pre><code>driver.find_element_by_css_selector("#RegularCategory&gt;div.pagination dl.dropdown dt a span").click() </code></pre> <p>and..code is ... I want to click on "sort by" but I can't. <a href="http://i.stack.imgur.com/3bDFl.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/3bDFl.jpg" alt="enter image description here"></a></p>
0
2016-09-30T08:11:55Z
39,786,853
<p>You can use selenium's <strong>select</strong> Class and its APIs like select_by_index or select_by_value: refer : <a href="http://selenium-python.readthedocs.io/api.html" rel="nofollow">[http://selenium-python.readthedocs.io/api.html]</a></p>
0
2016-09-30T08:22:12Z
[ "python", "selenium" ]
Customising MPL in PyQt
39,786,721
<p>So I've been doing a great deal of research in to PyQt and MPL, and I'm still having some issues that I can't get past. </p> <p><strong>The first is this</strong>: How do you change the FigureCanvas background color (it's the gray part in <a href="http://i.stack.imgur.com/etvHq.jpg" rel="nofollow">this image</a>). FigureCanvas does not have attributes for facecolor or backgroundcolor or anything else I can think of or find. I can change color on the axes, the plots (that's how I got the black background you can see), but not the canvas itself. </p> <p><strong>Second problem:</strong> How can I get rid of the mouse pointer that is still visible over the top of the crosshairs? Or better yet change the cursor when it enters the mpl FigureCanvas widget (and consequently back again when it leaves).</p> <p><strong>EDIT:</strong> Here is some of my code as requested. I am calling MPL figures from Qt via the following.</p> <p>My main window:</p> <pre><code>from PyQt5.QtCore import pyqtSlot as Slot from PyQt5 import QtCore from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import uic # MPL class from pyqt5_mpl import mpl_figure # Select Qt5 user interface. qtCreatorFile = '&lt;local filepath&gt;' Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class main(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): # Inititate UI. QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # Create data structures. global a a = a_dataclass() # Create MPL Canvases (Layout-&gt;CreateMPLCanvas-&gt;AddWidget). # Create class instances for each figure. a.im1 = mpl_figure() a.im2 = mpl_figure() # Create Layouts and add widgets. a_layout = QtWidgets.QHBoxLayout(self.tab1) a_layout.addWidget(a.im1.canvas) a_layout.addWidget(a.im2.canvas) # Load images. a.im1.loadimage('image file path',a.pix) a.im2.loadimage('image file path',a.pix) # a.pix is dimensions for extent in plot. if __name__ == "__main__": # QApp app = QtWidgets.QApplication(sys.argv) # QWidget (MainWindow) window = main() window.show() sys.exit(app.exec_()) </code></pre> <p>My mpl_figure class:</p> <pre><code>import matplotlib as mpl mpl.use('Qt5Agg') import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas class mpl_figure: def __init__(self): # Set up empty plot variables. self.image = None # Create a figure to plot on. fig = plt.figure() fig.set_facecolor('black') # This does nothing... # Create an axis in the figure. self.ax = fig.add_subplot(111, axisbg='black') # Create a canvas widget for Qt to use. self.canvas = FigureCanvas(fig) # Create cursor widget. self.cursor = mpl.widgets.Cursor(self.ax) # Refresh the canvas. self.canvas.draw() def loadimage(self,fn,pix): # Read in image. self.data = plt.imread(fn) # Calculate the extent. self.dims = np.array([0, pix[0]*np.shape(self.data)[1],0,pix[1]*np.shape(self.data)[0]]) # Display the image. self.image = self.ax.imshow(self.data, cmap='gray', extent=self.dims) self.ax.set_autoscale_on(False) # Refresh the canvas. self.canvas.draw() # Start Callback ID self.cid = self.canvas.mpl_connect('button_press_event', self.onclick) def onclick(self,event): # Do stuff... pass </code></pre> <p>All my attempts to try and make changes to self.canvas or fig. in terms of its styling are rendered mute and it does nothing. And as far as changing the cursor (or hiding it, it being the pointer) when you enter an mpl_widget I'm just not sure on how to do it. I remember seeing something within mpl that was to the effect of connect "event_leave_figure", but couldn't make a connection between that and PyQt &lt;- that's the important bit. Any ideas?</p>
1
2016-09-30T08:13:08Z
39,794,379
<p>Thanks for providing a <a href="http://stackoverflow.com/help/mcve">MINIMAL WORKING example</a> and for googling before asking a question. That always saves a lot of time. </p> <p>So the following code produces the image shown below.</p> <pre><code>import sys from PyQt4 import QtGui, QtCore import matplotlib import numpy as np from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure class ApplicationWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("application main window") self.main_widget = QtGui.QWidget(self) self.setCentralWidget(self.main_widget) l = QtGui.QVBoxLayout(self.main_widget) self.fig = Figure(figsize=(5,3), dpi=100) self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) l.addWidget(self.canvas) t = np.arange(0.0, 3.0, 0.01) s = np.sin(2*np.pi*t)*np.exp(-t/7/np.pi) self.ax.plot(t, s, color="#0095a2", lw=3) #set some alpha self.fig.patch.set_alpha(0.5) #set color self.fig.patch.set_facecolor('#cd0e49') self.cursor = matplotlib.widgets.Cursor(self.ax) #set cursor #self.canvas.setCursor(QtGui.QCursor(QtCore.Qt.BlankCursor)) #since I find Blank cursor very confusing, I will use a better one: self.canvas.setCursor(QtGui.QCursor( QtCore.Qt.SizeAllCursor)) qApp = QtGui.QApplication(sys.argv) aw = ApplicationWindow() aw.show() sys.exit(qApp.exec_()) </code></pre> <p><a href="http://i.stack.imgur.com/k8koY.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/k8koY.jpg" alt="enter image description here"></a></p>
0
2016-09-30T14:53:21Z
[ "python", "matplotlib", "pyqt5" ]
Reformat datetime value with regex in a textfile
39,786,734
<p>I want to change the time format in some text lines with using regex. How can I use the old time values? My code until now:</p> <pre><code>def file_replace_words(file_in, word_to_replace, replace_with): f = open(file_in, "r+") data = f.readlines() f.seek(0) for line in data: line = re.sub(word_to_replace, replace_with, line) f.write(line) f.truncate() f.close() f.file_replace_words(path_putty_log, r"(\d\d\/\d\d\/\d\d) - \d\d:\d\d:\d\d:\d\d\d", "my time in format 31.12.1999 11:54:23") </code></pre> <p>I want to change the values from 29/09/16 - 16:38:09:808 to 29.09.16 16:38:09.</p>
2
2016-09-30T08:13:46Z
39,786,795
<p>You may add some more capturing groups into your regex, and use a replacement pattern with corresponding backreferences.</p> <p>Use</p> <pre><code>r'(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}' |- 1-| |- 2-| |-3 -| | ----- 4 ---- | </code></pre> <p>and replace with <code>r'\1.\2.\3 \4'</code>.</p> <p>See the <a href="https://regex101.com/r/QUQ5jN/1" rel="nofollow">regex demo</a>.</p> <p>NOTE: If there are longer substrings that look like these datetime stamps, you might want to enclose the whole pattern with word boundaries <code>\b</code>: <code>r'\b(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}\b'</code>.</p>
1
2016-09-30T08:18:51Z
[ "python", "regex", "datetime", "reformatting" ]
Python: get list with nearest dates and same size for list with dates and values
39,786,772
<p>I am trying to get list of nearest dates for current list of lists (dates and value) </p> <p>Have two lists:</p> <pre><code>[["20160901", 0.244], ["20160902", 0.232], ["20160906", 0.214], ["20160909", 0.235], ["20160910", 0.244], ["20160911", 0.271], ["20160912", 0.239], ["20160914", 0.25], ...] </code></pre> <p>length is X</p> <p>and:</p> <pre><code>[["20160907", -9.39979076385498, -6.318868160247803], ["20160913", -10.568793296813965, -6.815752029418945], ... ] </code></pre> <p>length is Y</p> <p>Need to get first list with length is Y and nearest dates for second list.</p> <p>e.g. </p> <pre><code>[["20160906", 0.214], ["20160912", 0.239], ...] </code></pre> <p>Here is my code:</p> <pre><code>def nearest_date(dates, pivot): return min(dates, key=lambda x: abs(x - pivot)) </code></pre> <p>But I get lists different sizes.</p>
0
2016-09-30T08:16:50Z
39,787,447
<pre><code>list_dates = [["20160901", 0.244], ["20160902", 0.232], ["20160906", 0.214], ["20160909", 0.235], ["20160910", 0.244], ["20160911", 0.271], ["20160912", 0.239], ["20160914", 0.25]] list_comp = [["20160907", -9.39979076385498, -6.318868160247803], ["20160913", -10.568793296813965, -6.815752029418945]] [ min(list_dates, key = lambda x: abs(int(x[0])-int(p[0]))) for p in list_comp ] </code></pre> <p>result :</p> <pre><code>[['20160906', 0.214], ['20160912', 0.239]] </code></pre>
-1
2016-09-30T08:53:20Z
[ "python" ]
Extract AJAX content and java scripted content using scrapy
39,786,788
<p>I am trying to crawling this <a href="http://www.freeindex.co.uk/profile(the-main-event-management-company)_266537.htm" rel="nofollow">site</a> and want to extract contact number which is inside the call button.</p> <p>How can I implement this code??</p>
0
2016-09-30T08:18:09Z
39,788,898
<p>Seems like a simple AJAX request is being made to retrieve html string with the phone numbers:</p> <p><a href="http://i.stack.imgur.com/HNQ7y.png" rel="nofollow"><img src="http://i.stack.imgur.com/HNQ7y.png" alt="enter image description here"></a></p> <pre><code>import re import scrapy class MySpider(scrapy.Spider): name = 'sophone' start_urls = [ 'http://www.freeindex.co.uk/profile(the-main-event-management-company)_266537.htm' ] def parse(self, response): # item id can be extracted from url item_id = re.findall("(\d+)\.htm", response.url)[0] # phone api can be made using this id url = 'http://www.freeindex.co.uk/customscripts' \ '/popup_view_tel_details.asp?id={}'.format(item_id) yield scrapy.Request(url, self.parse_phone) def parse_phone(self, response): from scrapy.shell import inspect_response inspect_response(response, self) </code></pre>
1
2016-09-30T10:03:56Z
[ "python", "scrapy", "web-crawler" ]
Python regex not matching against pattern
39,786,906
<p>I'm trying to write a block that will take a file path from the user and check that the file path is a) actually a legitimate file path that opens a file, and b) that the first and last line of the .txt file fit this pattern:</p> <p>-53.750 120.900 49.805</p> <p>As it is now, the code that I'm using is not pattern-matching and is accepting any file. Does anyone know which part of the code needs adjustment in order to get the desired filter? I feel like I'm missing something obvious.</p> <p>This is what I'm trying:</p> <pre><code>while True: try: fileInput = input("What is the file path?: ") openedInput = open(fileInput, 'r') inputList = [] for line in openedInput: inputList.append(line) firstLine = inputList[0] lastLine = inputList[-1] print(firstLine) print(lastLine) if not re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',firstLine) and re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',lastLine): print("The data file must be in XYZ format, please submit a usable file: ") continue break except: print("That file path was not valid, try again") </code></pre>
0
2016-09-30T08:24:38Z
39,787,088
<p>You need to add <strong>\</strong> before <strong>.</strong> in you regular expression. like this : [0-9]+<strong>\.</strong>[0-9]</p> <p>Hope it helps, cheers.</p>
-1
2016-09-30T08:34:25Z
[ "python", "regex" ]
Python regex not matching against pattern
39,786,906
<p>I'm trying to write a block that will take a file path from the user and check that the file path is a) actually a legitimate file path that opens a file, and b) that the first and last line of the .txt file fit this pattern:</p> <p>-53.750 120.900 49.805</p> <p>As it is now, the code that I'm using is not pattern-matching and is accepting any file. Does anyone know which part of the code needs adjustment in order to get the desired filter? I feel like I'm missing something obvious.</p> <p>This is what I'm trying:</p> <pre><code>while True: try: fileInput = input("What is the file path?: ") openedInput = open(fileInput, 'r') inputList = [] for line in openedInput: inputList.append(line) firstLine = inputList[0] lastLine = inputList[-1] print(firstLine) print(lastLine) if not re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',firstLine) and re.match('.[0-9]+.[0-9]+\s.[0-9]+.[0-9]+\s[0-9]+.[0-9]+',lastLine): print("The data file must be in XYZ format, please submit a usable file: ") continue break except: print("That file path was not valid, try again") </code></pre>
0
2016-09-30T08:24:38Z
39,787,262
<p>You have a problem of negation. What your code is currently doing is printing the error message only if the first line does not match and the last line does match.</p> <p>It works fine with <code>if not (re.match(regex,firstLine) and re.match(regex,lastLine)):</code>, or <code>if not re.match(regex,firstLine) or not re.match(regex,lastLine):</code></p>
1
2016-09-30T08:44:19Z
[ "python", "regex" ]
Python functions recursively calling each other using dictionary storing their name
39,786,925
<p>I have following scenario:</p> <ul> <li>there are multiple function each accepting certain arguments</li> <li>they call each other based on arguments recursively/iteratively till certain conditions that can be inferred from arguments are met</li> <li>I can do <code>if-elif</code> in those functions, but since that will cause a lot of <code>if-elif</code> inside all of these functions, I thought I should use dictionary storing reference to these functions against their name as a key and then hash into this dictionary (using argument contents) to obtain and call the function to be called. </li> </ul> <p>The issue is that I am not able to decide where to define that dictionary, before all functions (as all functions will be using this dictionary) or after all functions (as dictionary will use all these functions).</p> <p>Below I tried to imitate the scenario. I used random function do decide upon which function to call instead of inferring it from the arguments. Also I have used <code>recurCount</code> to decide when to stop recursive calls.</p> <pre><code>import random # funcDict = {"fun1": fun1, # "fun2": fun2, # "fun3": fun3, # "fun4": fun4} #Traceback (most recent call last): # File "C:\...\temp.py", line 107, in &lt;module&gt; # funcDict = {"fun1": fun1, #NameError: name 'fun1' is not defined funcList = ["fun1","fun2","fun3","fun4"] recurCount = 5 def fun1(): global recurCount print("fun1") if(recurCount == 0): return else: recurCount= recurCount-1 funcDict[random.choice(funcList)]() #recursive call def fun2(): global recurCount print("fun2") if(recurCount == 0): return else: recurCount= recurCount-1 funcDict[random.choice(funcList)]() #recursive call def fun3(): global recurCount print("fun3") if(recurCount == 0): return else: recurCount= recurCount-1 funcDict[random.choice(funcList)]() #recursive call def fun4(): global recurCount print("fun4") if(recurCount == 0): return else: recurCount= recurCount-1 funcDict[random.choice(funcList)]() #recursive call fun1() # funcDict = {"fun1": fun1, # "fun2": fun2, # "fun3": fun3, # "fun4": fun4} #Traceback (most recent call last): # File "C:\...\temp.py", line 152, in &lt;module&gt; # fun1() # File "C:\...\temp.py", line 123, in fun1 # funcDict[random.choice(funcList)]() #NameError: name 'funcDict' is not defined </code></pre>
0
2016-09-30T08:25:44Z
39,787,025
<p>The dictionary requires that the functions are already defined, while the first call to any of the functions requires that the dictionary is already defined. Therefore, you should define the dictionary <em>after</em> all the function definitions and <em>before</em> making the first call to any of the functions:</p> <pre><code>def fun1(): ... def fun2(): ... def fun3(): ... def fun4(): ... funcDict = {"fun1": fun1, "fun2": fun2, "fun3": fun3, "fun4": fun4} fun1() </code></pre>
0
2016-09-30T08:31:16Z
[ "python", "recursion" ]
Django Serializer - Create object with relations
39,786,969
<p>What I'm trying to accomplish is to create and App object through the Django REST Framework. I am using a nested Version object and relate this to a already existing client.</p> <p>This is the model that I have, so you could get a better idea:</p> <pre><code>class Client(models.Model): client = models.CharField(max_length=200) mail = models.CharField(max_length=200, null=True) class Keyword(models.Model): keyword = models.CharField(max_length=200) client = models.ForeignKey(Client, related_name='client_keywords',on_delete=models.CASCADE) class App(models.Model): client = models.ForeignKey(Client, related_name='client_apps', on_delete=models.CASCADE) appname = models.CharField(max_length=200, unique=True) class Version(models.Model): apps = models.ForeignKey(App, related_name='version',on_delete=models.CASCADE) version = models.CharField(max_length=20, null=True) </code></pre> <p>As you can see Clients can have multiples Apps(1->N), and Apps can have multiple versions (1 -> N)</p> <p>I've implemented the following serializer so I can create the App object with the necessari relations but I must be doing something wrong: </p> <pre><code>class AppSerializer(serializers.ModelSerializer): version = VersionSerializer(many=True) client = ClientSerializer() class Meta: model = App fields = ('pk','client',..., 'version') def create(self, validated_data): versions_data = validated_data.pop('version') clients_data = validated_data.pop('client') app = App.objects.create(**validated_data) app.client = Client.objects.get(pk=clients_data['client']) for version_data in versions_data: Version.objects.create(apps=app, **version_data) return app </code></pre> <p>My idea here is to get the pk from "clients_data['client']" which i'm sending in the POST, get the client object for that PK and assign it for this new app, and after that create the required versions.</p> <p>But after a lot of tests the client_id in the database continuous empty. How can I assign the client correctly ?</p>
0
2016-09-30T08:28:11Z
39,788,320
<p>Finally!</p> <p>If it helps to someone else, you need to pass the client object to the app when you create it!</p> <pre><code>class AppSerializer(serializers.ModelSerializer): version = VersionSerializer(many=True) client = ClientSerializer() class Meta: model = App fields = ('pk','client',..., 'version') def create(self, validated_data): versions_data = validated_data.pop('version') clients_data = validated_data.pop('client') clients_info = Client.objects.get(pk=clients_data['client']) app = App.objects.create(client=clients_info,**validated_data) for version_data in versions_data: Version.objects.create(apps=app, **version_data) return app </code></pre>
0
2016-09-30T09:36:35Z
[ "python", "django", "django-rest-framework" ]
Indexing by datetime pandas dataframe fail
39,787,103
<p>I have the following dataframe <code>df</code>:</p> <pre><code> Candy Apple Banana 2016-09-14 19:00:00 109.202060 121.194138 130.372082 2016-09-14 20:00:00 109.199083 121.188817 130.380736 2016-09-14 21:00:00 109.198894 121.180553 130.366054 2016-09-14 22:00:00 109.192076 121.148722 130.307342 2016-09-14 23:00:00 109.184374 121.131068 130.276691 2016-09-15 00:00:00 109.191582 121.159304 130.316872 2016-09-15 01:00:00 109.183895 121.133062 130.269966 2016-09-15 02:00:00 109.193550 121.174708 130.337563 2016-09-15 03:00:00 109.196597 121.153076 130.274463 2016-09-15 04:00:00 109.195608 121.168936 130.276042 2016-09-15 05:00:00 109.211957 121.208946 130.330430 2016-09-15 06:00:00 109.210598 121.214454 130.365404 2016-09-15 07:00:00 109.224667 121.285534 130.508604 2016-09-15 08:00:00 109.220784 121.248828 130.389024 2016-09-15 09:00:00 109.199448 121.155439 130.212834 2016-09-15 10:00:00 109.226648 121.276439 130.427642 2016-09-15 11:00:00 109.239957 121.311719 130.462447 </code></pre> <p>I want to create a second dataframe with just data from the past 6 hours. </p> <pre><code>df.index = pd.to_datetime(df.index,infer_datetime_format=True) last_row = df.tail(1).index six_hour = last_row - timedelta(hours=6) df_6hr = df.loc[six_hour:last_row] print df_6hr </code></pre> <p>I get the following error:</p> <blockquote> <p>File "pandas/tslib.pyx", line 298, in pandas.tslib.Timestamp.<strong>new</strong> (pandas/tslib.c:9013)<br> File "pandas/tslib.pyx", line 1330, in pandas.tslib.convert_to_tsobject (pandas/tslib.c:25826)</p> <p>TypeError: Cannot convert input to Timestamp</p> </blockquote> <p>How come it doesn't work?</p>
3
2016-09-30T08:35:19Z
39,787,233
<p>You need add <code>[0]</code>, because you need select first item of list:</p> <pre><code>last_row = df.tail(1).index[0] print (last_row) 2016-09-15 11:00:00 </code></pre> <hr> <pre><code>last_row = df.tail(1).index print (last_row) DatetimeIndex(['2016-09-15 11:00:00'], dtype='datetime64[ns]', freq=None) </code></pre> <p>Better solution is simple select last value of index by <code>[-1]</code>:</p> <pre><code>last_row = df.index[-1] print (last_row) 2016-09-15 11:00:00 </code></pre>
2
2016-09-30T08:42:54Z
[ "python", "datetime", "dataframe" ]
Access parameters in parameterized decorators
39,787,192
<p>I'm trying to understand python decorator from this <a href="https://realpython.com/blog/python/primer-on-python-decorators/" rel="nofollow">doc</a>. And was writing my own decorator required to handle API Exceptions.</p> <p>But in my decorator, I'm not getting how to access arguments (<code>method</code>, <code>api</code>, and <code>data</code>) inside my Custom Decorator. </p> <p>I know, I haven't passed <code>method</code> anywhere because I'm not getting where to pass so that I can accept it in my decorator.</p> <p>Here is my decorator:</p> <pre><code>import requests as r import json def handle_api_exceptions(http_api_call): """ """ def wrapper(*args, **kwargs): """ """ response = {} try: response = http_api_call(*args, **kwargs) if response.ok: result = response.json() if result.get('code', 200) in INVALID_STATUS_CODES: #INVALID_STATUS_CODES = [1801, 1803, 1806,... ] response = {"data":{}, "status":False} else: return result else: capture_failed_requests(method, api, data, response, error=None, reason=response.reason) return {} except r.exceptions.ConnectionError as e: capture_failed_requests(method, api, data, response, error=e, reason="Connection Aborted") return {} except json.decoder.JSONDecodeError as e: capture_failed_requests(method, api, data, response, error=e, reason="Invalid Response") return {} except r.exceptions.ReadTimeout as e: capture_failed_requests(method, api, data, response, error=e, reason="Request Timed Out") return {} except Exception as e: capture_failed_requests(method, api, data, response, error=e, reason="Internal Server Error") return {} return wrapper </code></pre> <p>Custom GET, POST API requests:</p> <pre><code>@handle_api_exceptions def get(self, api, data, token=None): """ """ if token:data.update(self.get_token(token)) response = r.get(api, data, verify=self.config.SSL_VERIFY, timeout=self.config.REQUEST_TIMEOUT) return response @handle_api_exceptions def post(self, api, data, token=None): """ """ if token: data.update(self.get_secret_token(token)) response = r.post(api, data, verify=self.config.SSL_VERIFY, timeout=self.config.REQUEST_TIMEOUT) return response def post_call(self): """ """ api = "http://192.168.0.24/api/v1/reset/" data = {"k1":[], "k2":{}, "id":123456} #-- Some Key val return self.post(api, data, token="SOME_SECRET_TOKEN") </code></pre> <p>Query is : How to pass <code>method</code>, <code>api</code>, and <code>data</code> in <code>capture_failed_requests()</code>?</p>
0
2016-09-30T08:40:31Z
39,787,430
<p><code>data</code> and <code>api</code> are in the <code>args</code> inside <code>wrapper</code>. <code>method</code> you will have to provide separately, e.g. by parameterising the decorator (see e.g. <a href="http://stackoverflow.com/q/5929107/3001761">python decorators with parameters</a>). You could therefore do this as follows:</p> <pre><code>def handle_api_exceptions(method): def decorator(http_api_call): def wrapper(api, data, *args, **kwargs): ... </code></pre> <p>and your decorating would become e.g.</p> <pre><code>@handle_api_exceptions(method='GET') def get(self, api, data, token=None): ... </code></pre> <p>Alternatively, you could use <code>method = http_api_call.__name__</code> (which would give you <code>'get'</code>), and avoid the extra layer of nesting and duplication of the method name.</p> <hr> <p>Note that I have removed the empty docstrings - either write an actual docstring (I like <a href="http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html" rel="nofollow">Google-style</a>, but YMMV) or don't have one at all. If your linting rules <em>require</em> docstrings, that's because whoever set it up wants you to write <em>useful</em> ones, not just cheat on it.</p>
2
2016-09-30T08:52:26Z
[ "python", "python-decorators" ]
Pandas - scatter matrix set title
39,787,204
<p>I'm searching for a way to set a title to Pandas <code>scatter matrix</code>:</p> <pre><code>from pandas.tools.plotting import scatter_matrix scatter_matrix(data, alpha=0.5,diagonal='kde') </code></pre> <p>I tried <code>plt.title('scatter-matrix')</code> but it creates a new figure.</p> <p>Any help is appreciated.</p>
1
2016-09-30T08:41:04Z
39,787,437
<p>I think you need <code>suptitle</code>:</p> <pre><code>import matplotlib.pyplot as plt from pandas.tools.plotting import scatter_matrix scatter_matrix(df, alpha=0.5,diagonal='kde') plt.suptitle('scatter-matrix') plt.show() </code></pre>
1
2016-09-30T08:52:35Z
[ "python", "pandas", "plot", "title", "scatter-plot" ]
Regex to match an exact number of floating point numbers
39,787,218
<p>I have a string containing several float (or integer) numbers plus random stuff at the beginning and at the end. I want a regex that matches only the string that contains at least a given number of float and report as a group the first given number of floats.</p> <p>Example: Let's assume the string must contain exactly 6 float numbers. Remember that each string contains random stuff at the begin and at the end so <code>$</code> and <code>^</code> cannot be used.</p> <pre><code>5.13e12 4.5774 4.743E-1 .655E3 NO MATCH (only 4 float) 5.13e12 4.5774 4.743E-1 .655E3 1 2 MATCH (6 float -&gt; all in 1 group) 5.13e12 4.5774 4.743E-1 .655E3 1 2 3 5 6 MATCH (6 first float in a group) </code></pre> <p>Until now I elaborated the following</p> <pre><code>((\s*\d*\.?\d+[Ee]?[+-]?\d*){6}) </code></pre> <p>but this one matches also lines with less than 6 float numbers.</p> <p><strong>EDIT:</strong> After many tests the regex closer to what I wanted is the one from @Sebastian Proske. However, when I try to match 9 floats the computer stall. Reading around seems that this is due to the fact that the regex tries to match with any of the possible combinations that can be formed using the + and the *. Do you have any idea on how to make this possible?</p>
0
2016-09-30T08:41:54Z
39,788,228
<p>This regex with otional groups should work for you to match at least 6 numbers in each line:</p> <pre><code>(?:[+-]?\d*\.?\d+(?:E[+-]?\d+)?(?:\s+|$)){6} </code></pre> <p><a href="https://regex101.com/r/valhn1/3" rel="nofollow">RegEx Demo</a></p>
0
2016-09-30T09:31:39Z
[ "python", "regex", "python-2.7" ]
Python SQLAlchemy get retruning ID after inserting
39,787,274
<p>I want to get the ID of the last inserted record after inserting in postgresql using SQLAlchemy. Here is code,</p> <pre><code>insert_record = {list of data} result = connection.execute(tbl_example.insert().returning(tbl_example.c.id), insert_record) print result.id </code></pre> <p>The inserting does fine but I can't seem to get the ID of the last inserted, I get the following error,</p> <blockquote> <p>AttributeError: 'ResultProxy' object has no attribute 'id'</p> </blockquote> <p>Where is the return ID located in the returning object? </p>
0
2016-09-30T08:45:01Z
39,787,806
<p>It's located directly in returning object. There is example from <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html" rel="nofollow">documentation:</a></p> <pre><code>stmt = table.update().\ where(table.c.data == 'value').\ values(status='X').\ returning(table.c.server_flag, table.c.updated_timestamp) for server_flag, updated_timestamp in connection.execute(stmt): print(server_flag, updated_timestamp) </code></pre> <p>Also, <code>ResultProxy</code> <a href="http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.ResultProxy" rel="nofollow">supports</a> accessing via positon (as in example) and via name. So, you can use something like: <code>row_id = result['id']</code>.</p>
0
2016-09-30T09:09:29Z
[ "python", "mysql", "postgresql", "sqlalchemy" ]
Python stops at a print statement
39,787,333
<pre><code>while Winner == "": while First_Player_Turn == "Y": while rtd != "": try: rtd = input("{} press enter to roll the dice".format(First_Player)) if rtd == "": dice = random.randint(1, 6) First_Player_Position = dice + First_Player_Position steps_left = 50 - First_Player_Position print("{} needs {} steps to finish".format(First_Player, steps_left)) if First_Player_Position &gt;= 50: Winner = "Y" First_Player_Turn = "N" Second_Player_Turn = "Y" print("Test to see if this is printed - It is but not in wingide") continue except: print("Please press enter") while Second_Player_Turn == "Y": </code></pre> <p>I have tested this multiple times and I have found out that wingide doesn't show the Tested part but normal Python does. What I want to happen is when it has run through the <code>First_Player_Turn</code> loop to go to the <code>Second_Player_Turn</code> loop.</p>
-3
2016-09-30T08:47:41Z
39,787,501
<p>You do not show the initialisation of the string variables. Your program starts with the following:</p> <pre><code>while Winner == "": while First_Player_Turn == "Y": while rtd != "": </code></pre> <ul> <li>If <code>Winner</code> is initialised as <code>""</code>, the outer loop will run.</li> <li>If <code>First_Player_Turn</code> is initialised as <code>"Y"</code>, the middle loop will run.</li> <li>If <code>rtd</code> is <em>not</em> initialised as <code>""</code>, the inner loop will run.</li> </ul> <p>Because you haven't shown the initialisation of <strong>all</strong> three variables, you're obviously relying on magic for them to start with exactly the right values. Because that is unlikely, odds on <em>none</em> of the loops will run.</p>
0
2016-09-30T08:55:17Z
[ "python" ]
Python stops at a print statement
39,787,333
<pre><code>while Winner == "": while First_Player_Turn == "Y": while rtd != "": try: rtd = input("{} press enter to roll the dice".format(First_Player)) if rtd == "": dice = random.randint(1, 6) First_Player_Position = dice + First_Player_Position steps_left = 50 - First_Player_Position print("{} needs {} steps to finish".format(First_Player, steps_left)) if First_Player_Position &gt;= 50: Winner = "Y" First_Player_Turn = "N" Second_Player_Turn = "Y" print("Test to see if this is printed - It is but not in wingide") continue except: print("Please press enter") while Second_Player_Turn == "Y": </code></pre> <p>I have tested this multiple times and I have found out that wingide doesn't show the Tested part but normal Python does. What I want to happen is when it has run through the <code>First_Player_Turn</code> loop to go to the <code>Second_Player_Turn</code> loop.</p>
-3
2016-09-30T08:47:41Z
39,801,563
<p>I've figured it out myself, the rtd was conflicting with other rtd's sorry for wasting your time. </p>
0
2016-09-30T23:48:39Z
[ "python" ]
How to parse file and make a dataframe
39,787,518
<p>I have a text file in a bespoke format. I also have a parser that extracts the relevant columns from each line. I would like to read in the file one row at a time and add them to a dataframe.</p> <p>The problem is that appending a row to a dataframe is slow.</p> <p>What is the right way to do this?</p>
0
2016-09-30T08:55:54Z
39,787,622
<p>If the file is large, your code is probably bound by the time to read the file from disk, not the time to add rows to the dataframe, unless you have some concrete profiling data to suggest otherwise. For example on an SSD (read throughput ~ 400MB/s) a 4GB file will take 10 seconds just to load from disk. On an HDD (~40MB/s) this might go up to 100 seconds. If this is the case one way to speed up the loading is to convert the file to a format supported by pandas, compress it, and then use the runtime de-<code>compression</code> option of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html#pandas.read_table" rel="nofollow">read_table()</a> to decompress it on the fly while creating the dataframes.</p> <p>Otherwise, if you are sure this is really not the issue, you have these options, if adding one by one is not OK and the file is too large to buffer in memory:</p> <ol> <li>Change your data format to match something supported in Pandas; e.g. a CSV file seems like a pretty standard option you could go for;</li> <li>Use one of the other constructors listed below to create the dataframes in larger batches (e.g. of 1-10K rows), then merge them, which might be faster than adding entries one by one, while using a constant amount of memory; </li> </ol> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">The other ways to construct a dataframe</a> from the data structure you extract the file into:</p> <blockquote> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html#pandas.DataFrame.from_records" rel="nofollow">DataFrame.from_records</a> constructor from tuples, also record arrays </p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html#pandas.DataFrame.from_dict" rel="nofollow">DataFrame.from_dict</a> from dicts of Series, arrays, or dicts</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_items.html#pandas.DataFrame.from_items" rel="nofollow">DataFrame.from_items</a> from sequence of (key, value) pairs</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv" rel="nofollow">pandas.read_csv</a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html#pandas.read_table" rel="nofollow">pandas.read_table</a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_clipboard.html#pandas.read_clipboard" rel="nofollow">pandas.read_clipboard</a></p> </blockquote>
1
2016-09-30T09:01:15Z
[ "python", "pandas" ]
Packages in same namespace: declare version in code
39,787,557
<p>I'm curious about the following situation. Let's say I have two projects named <code>project_alpha</code> and <code>project_bravo</code>, both defining a top-level namespace package <code>mymeta</code>. The layout:</p> <pre><code>project_alpha/ -&gt; mymeta/ -&gt; __init__.py -&gt; project_alpha/ -&gt; __init__.py -&gt; version.py -&gt; setup.py project_bravo/ -&gt; mymeta/ -&gt; __init__.py -&gt; project_bravo/ -&gt; __init__.py -&gt; version.py -&gt; setup.py </code></pre> <p>Both <code>mymeta/__init__.py</code>s contain only the line <code>__import__('pkg_resources').declare_namespace(__name__)</code> (according to <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html#namespace-packages" rel="nofollow">namespace section in setuptools docs</a>). Contents of both <code>version.py</code>s: </p> <pre><code>__version_info__ = (0, 9, 9, 'dev0') __version__ = '.'.join((str(entry) for entry in __version_info__)) </code></pre> <p>The <code>setup.py</code> script for <code>project_alpha</code> is pretty simple. The namespace package <code>mymeta</code> is declared, and the version is taken from the <code>version</code> module: </p> <pre><code># project_alpha from setuptools import find_packages, setup from mymeta.project_alpha.version import __version__ setup( name='mymeta.project-alpha', version=__version__, namespace_packages=['mymeta'], packages=find_packages(), ) </code></pre> <p>The <code>setup.py</code> script for <code>project_bravo</code> has the same structure, but with a twist: <code>project_bravo</code> depends on <code>project_alpha</code> when building: </p> <pre><code>from setuptools import find_packages, setup from mymeta.project_bravo.version import __version__ setup( name='mymeta.project-bravo', version=__version__, namespace_packages=['mymeta'], setup_requires=['mymeta.project-alpha'], packages=find_packages(), ) </code></pre> <p>When building <code>project_bravo</code>, I get the following error:</p> <pre><code>~/project_bravo $ python setup.py sdist Traceback (most recent call last): File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 156, in save_modules yield saved File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 197, in setup_context yield File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 246, in run_setup DirectorySandbox(setup_dir).run(runner) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 276, in run return func() File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 245, in runner _execfile(setup_script, ns) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 47, in _execfile exec(code, globals, locals) File "/tmp/easy_install-ahmxos98/mymeta.project-alpha-0.9.9.dev0/setup.py", line 6, in &lt;module&gt; try: ImportError: No module named 'mymeta.project_alpha' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "setup.py", line 22, in &lt;module&gt; packages=find_packages(), File "/usr/lib64/python3.5/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/dist.py", line 315, in __init__ self.fetch_build_eggs(attrs['setup_requires']) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/dist.py", line 361, in fetch_build_eggs replace_conflicting=True, File "/tmp/tstenv/lib/python3.5/site-packages/pkg_resources/__init__.py", line 853, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "/tmp/tstenv/lib/python3.5/site-packages/pkg_resources/__init__.py", line 1125, in best_match return self.obtain(req, installer) File "/tmp/tstenv/lib/python3.5/site-packages/pkg_resources/__init__.py", line 1137, in obtain return installer(requirement) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/dist.py", line 429, in fetch_build_egg return cmd.easy_install(req) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/command/easy_install.py", line 665, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/command/easy_install.py", line 695, in install_item dists = self.install_eggs(spec, download, tmpdir) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/command/easy_install.py", line 876, in install_eggs return self.build_and_install(setup_script, setup_base) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/command/easy_install.py", line 1115, in build_and_install self.run_setup(setup_script, setup_base, args) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/command/easy_install.py", line 1101, in run_setup run_setup(setup_script, args) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 249, in run_setup raise File "/usr/lib64/python3.5/contextlib.py", line 77, in __exit__ self.gen.throw(type, value, traceback) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 197, in setup_context yield File "/usr/lib64/python3.5/contextlib.py", line 77, in __exit__ self.gen.throw(type, value, traceback) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 168, in save_modules saved_exc.resume() File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 143, in resume six.reraise(type, exc, self._tb) File "/tmp/tstenv/lib/python3.5/site-packages/pkg_resources/_vendor/six.py", line 685, in reraise raise value.with_traceback(tb) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 156, in save_modules yield saved File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 197, in setup_context yield File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 246, in run_setup DirectorySandbox(setup_dir).run(runner) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 276, in run return func() File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 245, in runner _execfile(setup_script, ns) File "/tmp/tstenv/lib/python3.5/site-packages/setuptools/sandbox.py", line 47, in _execfile exec(code, globals, locals) File "/tmp/easy_install-ahmxos98/mymeta.project-alpha-0.9.9.dev0/setup.py", line 6, in &lt;module&gt; try: ImportError: No module named 'mymeta.project_alpha' </code></pre> <p>Unfortunately, I don't understand the error here. It has something to do with the imports order, right? If I comment out the import of <code>mymeta.project_bravo.version</code> in <code>project_bravo/setup.py</code> and replace the <code>version</code> with some hard-coded string, suddenly the build succeeds...</p> <hr> <p>Edit: I introduced a workaround for this issue. Instead of trying to import the version directly, I <code>exec</code> the version module to avoid the import problems. Of course, this is not a proper solution, thus not posting this as answer, but still here it is: </p> <pre><code>__version__ = None # if the exec fails, leave the version unset, the resulting build version will be 0.0.0 version_script_path = os.path.relpath(os.path.join(os.path.dirname(__file__), 'mymeta', 'project_alpha', 'version.py')) with open(version_script_path) as version_script: exec(version_script.read()) </code></pre> <p>After the version script is read and executed, the version is initialized, thus no need to import anything from <code>mymeta</code> package.</p>
1
2016-09-30T08:57:54Z
39,792,743
<p>As mentioned in the comments: The command</p> <pre><code>$ python setup.py sdist </code></pre> <p>for <code>mymeta.project_bravo</code> downloads an egg of <code>mymeta.project_alpha</code> from a private pypi repo.</p> <p>Namespace packages are very delicate concerning their imports. </p> <p>e.g. I found out that when I install <code>ns.a</code> and <code>ns.b</code> regularly in my environment and supply the import path of <code>ns.d</code> in a .pth file in the site-packages directory, it will not work, no matter what. However when I symlink to <code>ns.d</code> in site-packeges/ns directory it will work.</p> <p>If I install none of the components and supply all paths in a .pth in the site-packages directory, everything works fine.</p> <p>If I install all of the components regularly also everything works fine.</p> <p>Just when I mix concepts it will not work.</p> <p>Therefore I suspect that this might also be the issue here: Different strategies for the import paths.</p> <p>You might want to try to modify your <code>__init__.py</code> file to:</p> <pre><code>from pkgutil import extend_path __path__ = extend_path(__path__, __name__) __import__('pkg_resources').declare_namespace(__name__) </code></pre> <p>I regret my decision to do namespace packages. I would never do it again. </p>
1
2016-09-30T13:29:53Z
[ "python", "setuptools" ]
"Unable to locate the SpatiaLite library." Django
39,787,700
<p>I'm trying to make Django's SQLite3 accept spatial queries. <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/gis/install/spatialite/" rel="nofollow">This tutorial</a> suggests that I add this to settings:</p> <pre><code>SPATIALITE_LIBRARY_PATH = 'mod_spatialite' </code></pre> <p>Which produces this error:</p> <blockquote> <p>django.core.exceptions.ImproperlyConfigured: Unable to load the SpatiaLite library extension "mod_spatialite" because: The specified module could not be found.</p> </blockquote> <p>I also tried doing this : </p> <pre><code>SPATIALITE_LIBRARY_PATH = r'C:\\Program Files (x86)\\Spatialite\\mod_spatialite-4.3.0a-win-x86\\mod_spatialite-4.3.0a-win-x86\\mod_spatialite.dll' </code></pre> <p>If I don't add this variable I receive this error when I migrate:</p> <blockquote> <p>django.core.exceptions.ImproperlyConfigured: Unable to locate the SpatiaLite library. Make sure it is in your library path, or set SPATIALITE_LIBRARY_PATH in your settings.</p> </blockquote> <p>Thank you..</p>
2
2016-09-30T09:04:25Z
39,881,926
<p>Amusingly enough 5 days later I'm having the same issue. After a little bit of poking around I got it working:</p> <p>Set</p> <pre><code>SPATIALITE_LIBRARY_PATH = 'mod_spatialite' </code></pre> <p>and extract ALL the DLL files from the mod_spatialite-x.x.x-win-x86.7z to your Python installation directory. The dll's apparently need to be in the same folder with python.exe. Also I imagine the mod_spatialite package needs to 32/64 bit according to your python installation. If you're missing some dll's, you get the same error "specified module not found" regardless of what dll file is missing, so it's a bit misleading.</p> <p>Downloaded from <a href="http://www.gaia-gis.it/gaia-sins/" rel="nofollow">http://www.gaia-gis.it/gaia-sins/</a></p> <p>I used mod_spatialite stable version 4.3.0a x86 with Python 3.5.2 32-bit.</p> <p>Other threads on the same issue with all sorts of answers:</p> <ul> <li><a href="http://stackoverflow.com/questions/27907818/use-spatialite-extension-for-sqlite-on-windows">Use spatialite extension for SQLite on Windows</a></li> <li><a href="http://stackoverflow.com/questions/22667981/getting-a-working-spatialite-sqlite-system-for-x64-c-sharp">Getting a working SpatiaLite + SQLite system for x64 c#</a></li> <li><a href="http://gis.stackexchange.com/questions/85674/sqlite-python-2-7-and-spatialite">http://gis.stackexchange.com/questions/85674/sqlite-python-2-7-and-spatialite</a></li> </ul>
1
2016-10-05T19:12:59Z
[ "python", "django", "sqlite3", "spatial", "geodjango" ]
"Unable to locate the SpatiaLite library." Django
39,787,700
<p>I'm trying to make Django's SQLite3 accept spatial queries. <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/gis/install/spatialite/" rel="nofollow">This tutorial</a> suggests that I add this to settings:</p> <pre><code>SPATIALITE_LIBRARY_PATH = 'mod_spatialite' </code></pre> <p>Which produces this error:</p> <blockquote> <p>django.core.exceptions.ImproperlyConfigured: Unable to load the SpatiaLite library extension "mod_spatialite" because: The specified module could not be found.</p> </blockquote> <p>I also tried doing this : </p> <pre><code>SPATIALITE_LIBRARY_PATH = r'C:\\Program Files (x86)\\Spatialite\\mod_spatialite-4.3.0a-win-x86\\mod_spatialite-4.3.0a-win-x86\\mod_spatialite.dll' </code></pre> <p>If I don't add this variable I receive this error when I migrate:</p> <blockquote> <p>django.core.exceptions.ImproperlyConfigured: Unable to locate the SpatiaLite library. Make sure it is in your library path, or set SPATIALITE_LIBRARY_PATH in your settings.</p> </blockquote> <p>Thank you..</p>
2
2016-09-30T09:04:25Z
39,977,824
<p>This is how to install SpatiaLite (almost) inside virtualenv for Python 3:</p> <ol> <li>Download <a href="http://sourceforge.net/projects/cyqlite/" rel="nofollow">cyqlite</a> a special SQLite build with R-Tree enabled. It is <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/gis/install/spatialite/#sqlite" rel="nofollow">required by GoeDjango</a>.</li> <li>Download <a href="http://www.gaia-gis.it/gaia-sins/" rel="nofollow">mod_spatialite</a> (Windows binaries are in the pink box at the bottom of the page) i.e. <code>mod_spatialite-[version]-win-x86.7z</code></li> <li>Unzip mod_spatialite files (flatten the tree and ignore the folder in the archive) into the virtuelenv <code>Scripts</code> folder. </li> </ol> <p>This part I don't like but I not could find a workable solution without touching main Python3 installation. </p> <ol start="5"> <li>Rename or otherwise backup <code>c:\Python35\DLLs\sqlite3.dll</code></li> <li>From <code>cyqlite</code> uznip <code>sqlite3.dll</code> file into the <code>c:\Python35\DLLs\</code></li> </ol> <hr> <p>Kudos: <a href="http://gis.stackexchange.com/a/169979/84121">http://gis.stackexchange.com/a/169979/84121</a></p>
0
2016-10-11T12:59:04Z
[ "python", "django", "sqlite3", "spatial", "geodjango" ]
PYCURL get a json file with utf-8 encoding problems
39,787,756
<p>i'm facing a problem with my PYCURL request. My json file on the server is encoded in utf-8 and look like this :</p> <pre><code>{ "address" : "123 rue de Labège" } </code></pre> <p>I use PYCURL to get this json and copy it into a new file on my computer. I use Python 2.7 and here is my setup for PYCURL :</p> <pre><code>def setup(self, _url, _method, _login, _passwd, _path, *args, **kwargs): self.curl = pycurl.Curl() self.url = 'https://%s:%d/' % (self.ip, self.port) + _url self.method = _method self.userpwd = '%s:%s' % (_login, _passwd) self.path = _path self.curl.setopt(pycurl.URL, self.url) curl_method = { "GET": pycurl.HTTPGET, "POST": pycurl.POST } if self.method in curl_method: self.curl.setopt(curl_method[self.method], 1) else: self.curl.setopt(pycurl.CUSTOMREQUEST, self.method) self.curl.setopt(pycurl.SSL_VERIFYPEER, 0) self.curl.setopt(pycurl.SSL_VERIFYHOST, 0) self.curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC) self.curl.setopt(pycurl.USERPWD, self.userpwd) if _url == 'MY_FILE_JSON': filename = 'file.json' self.file = open(self.path + filename, 'wb') self.curl.setopt(pycurl.WRITEDATA, self.file) </code></pre> <p>The problem is in the file i'm getting :</p> <pre><code>{ "address" : "123 rue de Lab\u00e8uge" } </code></pre> <p>I don't understand why PYCURL encoding my "è" into \u00e8. Is there any option with setopt with PYCURL to force it to print the good character ? </p>
1
2016-09-30T09:07:29Z
39,787,956
<p>Actually this is totally correct, once you do a <code>print</code> of the variable property, you can see it prints out fine.</p> <p>This is just how Python internally handles Unicode strings. Once PycURL receives the file it will be converted to whatever type is appropriate for the property. In your case this is a Unicode string.</p> <p>Check <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">this article</a> out for more information.</p> <p>So to recap, if you do:</p> <pre><code>&gt;&gt;&gt; test = u'123 rue de Lab\u00e8uge' &gt;&gt;&gt; print(test) 123 rue de Labèuge </code></pre> <p>Here you can see I create a Unicode string (starting with the <code>u</code>).</p>
2
2016-09-30T09:16:59Z
[ "python", "utf-8", "pycurl" ]
How to get the difference between two 24 hour times?
39,787,787
<p>Is there a simple way in pandas to tell the difference between 24 hour times as follows:</p> <pre><code>9:45 17:10 </code></pre> <p>The difference is 7 hours and 25 minutes which is 445 minutes.</p>
3
2016-09-30T09:08:25Z
39,787,879
<p>Sure:</p> <pre><code>&gt;&gt;&gt; from pandas import Timestamp &gt;&gt;&gt; Timestamp('9:45') Timestamp('2016-09-30 09:45:00') &gt;&gt;&gt; Timestamp('17:10') Timestamp('2016-09-30 17:10:00') &gt;&gt;&gt; Timestamp('17:10') - Timestamp('9:45') Timedelta('0 days 07:25:00') &gt;&gt;&gt; td = Timestamp('17:10') - Timestamp('9:45') &gt;&gt;&gt; td Timedelta('0 days 07:25:00') </code></pre> <p>And if you really need the time in minutes:</p> <pre><code>&gt;&gt;&gt; td.seconds/60 445 &gt;&gt;&gt; </code></pre> <h2> Edit </h2> <p>Just double-checked the documentation, and the <code>seconds</code> attribute of a Timedelta object returns: <code>Number of seconds (&gt;= 0 and less than 1 day)</code>.</p> <p>So, to really be safe if you want the minutes, use:</p> <pre><code>&gt;&gt;&gt; td.delta # returns the number of nanoseconds 26700000000000 &gt;&gt;&gt; td.delta * 1e-9 / 60 445.0 </code></pre>
4
2016-09-30T09:13:42Z
[ "python", "pandas" ]
How to get the difference between two 24 hour times?
39,787,787
<p>Is there a simple way in pandas to tell the difference between 24 hour times as follows:</p> <pre><code>9:45 17:10 </code></pre> <p>The difference is 7 hours and 25 minutes which is 445 minutes.</p>
3
2016-09-30T09:08:25Z
39,788,395
<p>I think you can also use the Python standard library <code>datetime.datetime</code> without installing the pandas.</p> <pre><code>&gt;&gt;&gt; t1 = datetime.datetime.strptime('09:45', '%H:%M') &gt;&gt;&gt; t2 = datetime.datetime.strptime('17:10', '%H:%M') &gt;&gt;&gt; t1 datetime.datetime(1900, 1, 1, 9, 45) &gt;&gt;&gt; t2 datetime.datetime(1900, 1, 1, 17, 10) &gt;&gt;&gt; td = t2 - t1 &gt;&gt;&gt; td.total_seconds() 26700.0 &gt;&gt;&gt; str(td) '7:25:00' </code></pre>
2
2016-09-30T09:40:11Z
[ "python", "pandas" ]
How to convert all lists to sets when json file is loaded
39,787,795
<p>I have json files that look like this:</p> <pre><code>{ "K1": { "p": [ "A" ], "s": [ "B", "C" ] }, "K2": { "p": [ "A", "F" ], "s": [ "G", "H", "J" ] } } </code></pre> <p>I can easily read in this data:</p> <pre><code>import json with open('json_lists_to_sets.json') as fi: data = json.load(fi) </code></pre> <p>Then <code>data</code> looks as follows:</p> <pre><code>{u'K2': {u'p': [u'A', u'F'], u's': [u'G', u'H', u'J']}, u'K1': {u'p': [u'A'], u's': [u'B', u'C']}} </code></pre> <p>For my further analysis, however, it would be better to use <code>sets</code> instead of <code>lists</code>. I can of course convert <code>lists</code> to <code>sets</code> after I have read in the data:</p> <pre><code>for vi in data.values(): vi['p'] = set(vi['p']) vi['s'] = set(vi['s']) </code></pre> <p>which gives me the desired output:</p> <pre><code>print data['K2'] </code></pre> <p>yields</p> <pre><code>{u'p': {u'A', u'F'}, u's': {u'G', u'H', u'J'}} </code></pre> <p>My questions is whether I can convert these <code>lists</code> to <code>sets</code> directly when I read in the data in the <code>json.load</code> command, so something like "convert all lists you find to sets". Does something like this exist?</p>
2
2016-09-30T09:08:56Z
39,787,955
<p>Below is the one liner expression to achieve this using <code>dict comprehension</code>:</p> <pre><code>&gt;&gt;&gt; {key: {k: set(v) for k, v in nested_dict.items()} for key, nested_dict in data.items()} {'K2': {'s': {'H', 'G', 'J'}, 'p': {'A', 'F'}}, 'K1': {'s': {'B', 'C'}, 'p': {'A'}}} </code></pre> <p>However, in case you want achieve it using <code>loop</code>, below is the example:</p> <pre><code>data = {u'K2': {u'p': [u'A', u'F'], u's': [u'G', u'H', u'J']}, u'K1': {u'p': [u'A'], u's': [u'B', u'C']}} for key, nested_dict in data.items(): data[key] = {k: set(v) for k, v in nested_dict.items()} # Value of 'data': {'K2': {'s': {'H', 'G', 'J'}, 'p': {'A', 'F'}}, 'K1': {'s': {'B', 'C'}, 'p': {'A'}}} </code></pre>
2
2016-09-30T09:16:59Z
[ "python", "json" ]
How to convert all lists to sets when json file is loaded
39,787,795
<p>I have json files that look like this:</p> <pre><code>{ "K1": { "p": [ "A" ], "s": [ "B", "C" ] }, "K2": { "p": [ "A", "F" ], "s": [ "G", "H", "J" ] } } </code></pre> <p>I can easily read in this data:</p> <pre><code>import json with open('json_lists_to_sets.json') as fi: data = json.load(fi) </code></pre> <p>Then <code>data</code> looks as follows:</p> <pre><code>{u'K2': {u'p': [u'A', u'F'], u's': [u'G', u'H', u'J']}, u'K1': {u'p': [u'A'], u's': [u'B', u'C']}} </code></pre> <p>For my further analysis, however, it would be better to use <code>sets</code> instead of <code>lists</code>. I can of course convert <code>lists</code> to <code>sets</code> after I have read in the data:</p> <pre><code>for vi in data.values(): vi['p'] = set(vi['p']) vi['s'] = set(vi['s']) </code></pre> <p>which gives me the desired output:</p> <pre><code>print data['K2'] </code></pre> <p>yields</p> <pre><code>{u'p': {u'A', u'F'}, u's': {u'G', u'H', u'J'}} </code></pre> <p>My questions is whether I can convert these <code>lists</code> to <code>sets</code> directly when I read in the data in the <code>json.load</code> command, so something like "convert all lists you find to sets". Does something like this exist?</p>
2
2016-09-30T09:08:56Z
39,787,960
<p>Although the <code>json</code> library offers many hooks to alter decoding, there is no hook to hook into loading a JSON array.</p> <p>You'll have to recursively update the decoded result afterwards instead:</p> <pre><code>def to_sets(o): if isinstance(o, list): return {to_sets(v) for v in o} elif isinstance(o, dict): return {k: to_sets(v) for k, v in o.items()} return o </code></pre> <p>This handles lists at any nested dictionary depth:</p> <pre><code>&gt;&gt;&gt; to_sets(data) {u'K2': {u'p': set([u'A', u'F']), u's': set([u'H', u'J', u'G'])}, u'K1': {u'p': set([u'A']), u's': set([u'C', u'B'])}} </code></pre> <p>Take into account however, that lists containing other dictionaries <em>can't</em> be handled because dictionaries are not hashable.</p> <p>If you expect to find lists nested inside other lists, you'd have to switch to using a <code>frozenset()</code> rather than a <code>set()</code> to be able to nest those:</p> <pre><code>def to_sets(o): if isinstance(o, list): return frozenset(to_sets(v) for v in o) elif isinstance(o, dict): return {k: to_sets(v) for k, v in o.items()} return o </code></pre>
5
2016-09-30T09:17:15Z
[ "python", "json" ]
How to cross-platform compile on windows for linux using gcc?
39,787,862
<p>My aim is to create cross-platform C++ python modules. I'm using<code>Cyther</code> (cross-platform The Cross-Platform Cython/Python Compiler).</p> <p>Cyther uses <code>GCC</code> to compile modules and gives the user the ability to add GCC command-line args.</p> <p>So, I need run compiler on Windows, but compile for Linux. What args I must pass to GCC to compile a module for Linux (or other platform)? </p> <p>Is this possible, if so how?</p>
1
2016-09-30T09:12:51Z
39,788,143
<p>Gcc must be built separately for each compilation target. It can be built for any target on any host. The target you need is <code>i386-linux-gnu</code> (or often <code>i586-linux-gnu</code>) for 32-bit and <code>x86_64-linux-gnu</code> for 64-bit Linux.</p> <p>Note that it provides separate binaries, <code>i386-linux-gnu-gcc</code>, <code>x86_64-linux-gnu-gcc</code> etc. Parameters are then the same.</p> <p>I am not sure anybody provides that, but you can build it yourself. A tool to help you with that is described in <a href="http://stackoverflow.com/questions/4769968/c-cross-compiler-from-windows-to-linux">C++ cross-compiler from Windows to Linux</a>.</p> <p>Or you can go the simpler way and build on Linux (including cross-compilation to Windows). This kind of things is just so much easier on a decent Linux distribution.</p>
1
2016-09-30T09:27:17Z
[ "python", "c++", "linux", "gcc", "cross-compiling" ]
What is the code to ask a user to input a number and print the square and cube of that number in python 3.5?
39,788,059
<p>I'm using Python 3.5.2 and have been asked to write a small program to ask a user to enter a number and the program will then print out the square and the cube of the number entered. This is the code I've written so far:</p> <pre><code> number = input ('Please enter a number ') y = (number)**2 z = (number)**3 print (y+z) </code></pre> <p>and when I run it I get the following error message:</p> <pre><code>TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' </code></pre> <p>What is the correct code to get this to work?</p>
-1
2016-09-30T09:22:34Z
39,788,138
<p>when in doubt, add print statements</p> <pre><code>number = input ('Please enter a number ') print("number is %s of type %s" % (number, type(number))) print("number is {} of type {}".format(number, type(number))) y = number ** 2 print("y is {} of type {}".format(y, type(y))) z = number **3 print("z is {} of type {}".format(z, type(z))) print (y+z) </code></pre> <p>Output:</p> <pre><code>python3 x.py Please enter a number 4 number is 4 of type &lt;class 'str'&gt; number is 4 of type &lt;class 'str'&gt; Traceback (most recent call last): File "x.py", line 5, in &lt;module&gt; y = number ** 2 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' </code></pre> <p>AS you can see, number is a string because in python3, <code>input</code> returns the users input as a string</p> <p>change it to <code>int(input('Please enter a number'))</code></p>
2
2016-09-30T09:26:57Z
[ "python" ]
What is the code to ask a user to input a number and print the square and cube of that number in python 3.5?
39,788,059
<p>I'm using Python 3.5.2 and have been asked to write a small program to ask a user to enter a number and the program will then print out the square and the cube of the number entered. This is the code I've written so far:</p> <pre><code> number = input ('Please enter a number ') y = (number)**2 z = (number)**3 print (y+z) </code></pre> <p>and when I run it I get the following error message:</p> <pre><code>TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' </code></pre> <p>What is the correct code to get this to work?</p>
-1
2016-09-30T09:22:34Z
39,788,151
<p>The error is quite self-explanatory :</p> <pre><code>TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' </code></pre> <p>Basically <code>(number)</code>is a string while <code>2</code>is an integer. What you need to do is convert <code>number</code> from <code>str</code> to <code>int</code>. Try this :</p> <pre><code>y = int(number) ** 2 z = int(number) ** 3 print(y+z) </code></pre> <p>This should do the trick.</p>
0
2016-09-30T09:27:48Z
[ "python" ]
Python: edit matrix row in parallel
39,788,140
<p>here is my problem:<br> I would like to define an array of persons and change the entries of this array in a for loop. Since I also would like to see the asymptotics of the resulting distribution, I want to repeat this simulation quiet a lot, thus I'm using a matrix to store the several array in each row. I know how to do this with two for loops: </p> <pre><code>import random import numpy as np nobs = 100 rep = 10**2 steps = 10**2 dmoney = 1 state = np.matrix([[10] * nobs] * rep) for i in range(steps): for j in range(rep) sample = random.sample(range(state.shape[1]),2) state[j,sample[0]] = state[j,sample[0]] + dmoney state[j,sample[1]] = state[j,sample[1]] - dmoney </code></pre> <p>I thought I use the multiprocessing library but I don't know how to do it, because in my simple mind, the workers manipulate the same global matrix in parallel, which I read is not a good idea.<br> So, how can I do this, to speed up calculations?</p> <p>Thanks in advance.</p>
0
2016-09-30T09:27:09Z
39,789,694
<p>OK, so this might not be much use, I haven't profiled it to see if there's a speed-up, but list comprehensions will be a little faster than normal loops anyway.</p> <pre><code>... y_ix = np.arange(rep) # create once as same for each loop for i in range(steps): # presumably the two locations in the population to swap need refreshing each loop x_ix = np.array([np.random.choice(nobs, 2) for j in range(rep)]) state[y_ix, x_ix[:,0]] += dmoney state[y_ix, x_ix[:,1]] -= dmoney </code></pre> <p>PS what numpy splits over multiple processors depends on what libraries have been included when compiled (BLAS etc). You will be able to find info on line about this.</p> <p>EDIT I can confirm, after comparing the original with the numpy indexed version above, that the original method is faster!</p>
0
2016-09-30T10:45:47Z
[ "python", "matrix", "multiprocessing", "row" ]
How do i change my code to not include builtin functions
39,788,247
<p>I had an assignment for school with a test to make a program that checks password strength. as you can see below i've made the program. When I turned it in, I received it back because it's to convenient to use the builtin function <code>any()</code>. how can i adjust or change my program to not include the <code>any()</code> function.</p> <pre><code>import time print ("Check of uw wachtwoord veilig genoeg is in dit programma.") time.sleep(1) print ("Uw wachtwoord moet tussen minimaal 6 en maximaal 12 karakters bestaan") print ("U kunt gebruik maken van hoofdletters,getallen en symbolen (@,#,$,%)") klein = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] groot = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] nummers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] symbolen= [' ', '!', '#', '$', '%', '&amp;', '"', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '&lt;', '=', '&gt;', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~',"'"] def ok(passwd,l): return any(k in passwd for k in l) # checkt of een letter in de lijst in het wachtwoord zit. while True: inp = input("Wilt u dit programma gebruiken? ja/nee: ") if inp == "nee" and "Nee" and "NEE": break elif inp == "ja" and "Ja" and "JA": ww = input("Voer uw wachtwoord in: ") if len(ww) &lt; 6: print ("uw wachtwoord is te kort, uw wachtwoord moet uit minimaal 6 en maximaal 12 karakters bestaan!") elif len(ww) &gt; 12: print ("uw wachtwoord is te lang, uw wachtwoord moet uit minimaal 6 en maximaal 12 karakters bestaan!") elif len(ww) &gt;= 6 and len(ww)&lt;= 12: sww = set(ww) # set is een onorganiseerde verzameling dat betekent dat het niet op order is bijv. SaUj%2F3 = Oonorganiseerd if all(ok(sww,l) for l in [klein,groot,nummers,symbolen]): print ("uw wachtwoord is Zeer sterk") elif all(ok(sww,l) for l in [klein,groot,nummers]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [klein,groot,symbolen]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [groot,nummers,symbolen]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [nummers,symbolen,klein]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [nummers,symbolen]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [groot,nummers]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [groot,symbolen]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein,groot]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein,nummers]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein,symbolen]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein]): print ("uw wachtwoord is Zwak") elif all(ok(sww,l) for l in [symbolen]): print ("uw wachtwoord is Zwak") elif all(ok(sww,l) for l in [nummers]): print ("uw wachtwoord is Zwak") elif all(ok(sww,l) for l in [groot]): print ("uw wachtwoord is Zwak") </code></pre>
-4
2016-09-30T09:32:45Z
39,794,108
<p>After fixing errors with the original</p> <pre><code>import time print ("Check of uw wachtwoord veilig genoeg is in dit programma.") time.sleep(1) print ("Uw wachtwoord moet tussen minimaal 6 en maximaal 12 karakters bestaan") print ("U kunt gebruik maken van hoofdletters,getallen en symbolen (@,#,$,%)") klein = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] groot = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] nummers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] symbolen= [' ', '!', '#', '$', '%', '&amp;', '"', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '&lt;', '=', '&gt;', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~',"'"] def ok(passwd,l): return any(k in passwd for k in l) # checkt of een letter in de lijst in het wachtwoord zit. while True: inp = raw_input("Wilt u dit programma gebruiken? ja/nee: ") if inp.lower() == "nee": break elif inp.lower() == "ja": ww = raw_input("Voer uw wachtwoord in: ") if len(ww) &lt; 6: print ("uw wachtwoord is te kort, uw wachtwoord moet uit minimaal 6 en maximaal 12 karakters bestaan!") elif len(ww) &gt; 12: print ("uw wachtwoord is te lang, uw wachtwoord moet uit minimaal 6 en maximaal 12 karakters bestaan!") elif len(ww) &gt;= 6 and len(ww)&lt;= 12: sww = set(ww) # set is een onorganiseerde verzameling dat betekent dat het niet op order is bijv. SaUj%2F3 = Oonorganiseerd if all(ok(sww,l) for l in [klein,groot,nummers,symbolen]): print ("uw wachtwoord is Zeer sterk") elif all(ok(sww,l) for l in [klein,groot,nummers]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [klein,groot,symbolen]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [groot,nummers,symbolen]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [nummers,symbolen,klein]): print ("uw wachtwoord is Sterk") elif all(ok(sww,l) for l in [nummers,symbolen]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [groot,nummers]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [groot,symbolen]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein,groot]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein,nummers]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein,symbolen]): print ("uw wachtwoord is Medium") elif all(ok(sww,l) for l in [klein]): print ("uw wachtwoord is Zwak") elif all(ok(sww,l) for l in [symbolen]): print ("uw wachtwoord is Zwak") elif all(ok(sww,l) for l in [nummers]): print ("uw wachtwoord is Zwak") elif all(ok(sww,l) for l in [groot]): print ("uw wachtwoord is Zwak") </code></pre> <p>if you really do not want to use any() something like the following would do</p> <pre><code>def ok(passwd,l): for c in passwd: if c in l: return True return False </code></pre> <p>iterates through the password until it finds a character within the list</p>
0
2016-09-30T14:40:21Z
[ "python", "python-3.x" ]
Switching between python2 and python3 as the default python
39,788,251
<p>Is there a standard way to switch between python2 to python3 as the default python, similar to how virtualenv can be used to switch between different sandboxed python environments?</p> <p>I would like to avoid manually fiddling with symlinks and the PATH variable so that the solution is portable.</p> <p>Since it is about switching python version, the solution must obviously not be written in python but rather in bash or something portable.</p> <p>And a slight deviation from the original question: if there was a way to have something like <code>mkvirtualenv2</code> and <code>mkvirtualenv3</code> that would be an ever better solution. Is it possible? I understand it's not, because virtualenv can only operate within a single Python interpreter env. If I install virtualenv for both python2 and python3, then how to switch between executables in a clean way?</p> <p>Ideally it would be something like <a href="https://github.com/creationix/nvm" rel="nofollow">nvm</a> for nodejs or <a href="http://rbenv.org/" rel="nofollow">rbenv</a> for Ruby.</p>
0
2016-09-30T09:33:11Z
39,788,447
<p>I guess you're talking about using Python under Windows because you mention the PATH variable. Recent versions of Python3 ship with the so-called Python launcher. You can run <code>py -2</code> in order to start a Python2 interpreter and <code>py -3</code> in order to start a Python3 interpreter. I hope this answers your question.</p>
0
2016-09-30T09:43:15Z
[ "python", "python-3.x", "virtualenv", "python-2.x", "pyenv" ]
Switching between python2 and python3 as the default python
39,788,251
<p>Is there a standard way to switch between python2 to python3 as the default python, similar to how virtualenv can be used to switch between different sandboxed python environments?</p> <p>I would like to avoid manually fiddling with symlinks and the PATH variable so that the solution is portable.</p> <p>Since it is about switching python version, the solution must obviously not be written in python but rather in bash or something portable.</p> <p>And a slight deviation from the original question: if there was a way to have something like <code>mkvirtualenv2</code> and <code>mkvirtualenv3</code> that would be an ever better solution. Is it possible? I understand it's not, because virtualenv can only operate within a single Python interpreter env. If I install virtualenv for both python2 and python3, then how to switch between executables in a clean way?</p> <p>Ideally it would be something like <a href="https://github.com/creationix/nvm" rel="nofollow">nvm</a> for nodejs or <a href="http://rbenv.org/" rel="nofollow">rbenv</a> for Ruby.</p>
0
2016-09-30T09:33:11Z
39,788,455
<p><a href="https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux" rel="nofollow">This</a> shows us how to use <code>update-alternatives</code> and/or use an alias in <code>~./bashrc</code>: <code>alias python=/usr/local/bin/python2.7</code></p>
0
2016-09-30T09:44:02Z
[ "python", "python-3.x", "virtualenv", "python-2.x", "pyenv" ]
Switching between python2 and python3 as the default python
39,788,251
<p>Is there a standard way to switch between python2 to python3 as the default python, similar to how virtualenv can be used to switch between different sandboxed python environments?</p> <p>I would like to avoid manually fiddling with symlinks and the PATH variable so that the solution is portable.</p> <p>Since it is about switching python version, the solution must obviously not be written in python but rather in bash or something portable.</p> <p>And a slight deviation from the original question: if there was a way to have something like <code>mkvirtualenv2</code> and <code>mkvirtualenv3</code> that would be an ever better solution. Is it possible? I understand it's not, because virtualenv can only operate within a single Python interpreter env. If I install virtualenv for both python2 and python3, then how to switch between executables in a clean way?</p> <p>Ideally it would be something like <a href="https://github.com/creationix/nvm" rel="nofollow">nvm</a> for nodejs or <a href="http://rbenv.org/" rel="nofollow">rbenv</a> for Ruby.</p>
0
2016-09-30T09:33:11Z
39,788,540
<p>There is a way, and it is called <a href="http://conda.pydata.org/docs/intro.html" rel="nofollow">Conda</a> (you can install <a href="http://conda.pydata.org/miniconda.html" rel="nofollow">Miniconda</a> to start with).</p> <p>It lets you create virtual environments in which you can specify the Python interpreter version you want to use. In example:</p> <pre><code>conda create -n new_environment python=3.5 </code></pre> <p>Conda will download the interpreter for you, so you don't need to have it available in your system.</p> <p>Appart from that, you can install packages without needing to compile them (in case they are not fully written in Python), which is something very convenient specially if you are on Windows. So, for example, <code>conda install numpy matplotlib</code> will not require you to compile any of those packages.</p>
1
2016-09-30T09:48:09Z
[ "python", "python-3.x", "virtualenv", "python-2.x", "pyenv" ]
Switching between python2 and python3 as the default python
39,788,251
<p>Is there a standard way to switch between python2 to python3 as the default python, similar to how virtualenv can be used to switch between different sandboxed python environments?</p> <p>I would like to avoid manually fiddling with symlinks and the PATH variable so that the solution is portable.</p> <p>Since it is about switching python version, the solution must obviously not be written in python but rather in bash or something portable.</p> <p>And a slight deviation from the original question: if there was a way to have something like <code>mkvirtualenv2</code> and <code>mkvirtualenv3</code> that would be an ever better solution. Is it possible? I understand it's not, because virtualenv can only operate within a single Python interpreter env. If I install virtualenv for both python2 and python3, then how to switch between executables in a clean way?</p> <p>Ideally it would be something like <a href="https://github.com/creationix/nvm" rel="nofollow">nvm</a> for nodejs or <a href="http://rbenv.org/" rel="nofollow">rbenv</a> for Ruby.</p>
0
2016-09-30T09:33:11Z
39,804,955
<p>After some more research it looks like a possible solution could have been <a href="https://github.com/yyuu/pyenv" rel="nofollow">pyenv</a> which is supposed to be used as described in the <a href="https://amaral.northwestern.edu/resources/guides/pyenv-tutorial" rel="nofollow">pyenv tutorial</a> <strong><em>but</em></strong> it only recognizes a <em>single</em> system-wide python runtime (whichever is the default at the moment), and for some strange reason it doesn't provide the option to switch between the system-wide python2 and python3. </p> <p>Looks like pyenv can switch only between the system python and any of the versions explicitly installed via pyenv which can all be seen via <code>pyenv install --list</code> and installed with e.g. <code>pyenv install 3.6-dev</code>.</p> <p><a href="http://stackoverflow.com/a/29950604/191246">Pyenv can integrate with virtualenv</a> which could be handy for dev testing since it includes all versions of anaconda, miniconda, pypy, jython, stackless, etc. It's probably the easiest way of installing multiple versions of python which do not come with your package manager, ie on older Linux distros that don't have a modern python in their repos.</p> <p>But in the long run, all things considered, I found that the solution proposed by <a href="http://stackoverflow.com/users/2904896/metatoaster">metatoaster</a> is simpler and totally meets my requirements since I can use the python2 virtualenv to create both python2 and python3 environments without any overhead:</p> <pre><code>python -V Python 2.7.12 mkdir -p ~/.virtualenvs &amp;&amp; cd ~/.virtualenvs virtualenv -p /usr/bin/python3 mypy3env workon mypy3env python -V &gt;&gt;&gt; Python 3.5.2 </code></pre>
0
2016-10-01T09:23:16Z
[ "python", "python-3.x", "virtualenv", "python-2.x", "pyenv" ]
Obtaining the most informative features after dimensionality reduction
39,788,262
<p>I basically have a python script that tries a variety of dimensionality reduction techniques combined with a variety of classifiers. I attempted to collect the most informative features for each classifier:</p> <pre><code>if 'forest' in type(classifier).__name__.lower(): importances = classifier.feature_importances_ coefs_with_fns = numpy.argsort(importances)[::-1] else: coefs_with_fns = sorted(zip(classifier.coef_, reduced_training.columns)) </code></pre> <p>While this works in principal, the output is just a series of integers, which (i assume) correspond to the column numbers in the feature array before the classifier. Which brings me to the problem: This array is the direct result of one dimensionality reduction method, which throws away all the previously attached column labels. </p> <p>So my question is: is there a way to trace back the result of the dimensionality reduction to the actual columns/labels in the original dataset?</p>
-1
2016-09-30T09:33:52Z
39,796,052
<p>You can't.</p> <p>When you do dimensionality reduction (like PCA), what you get is some new vectors and not a subset of the original feature set. And in the process you lose information. You project the the features of the original feature set, from a high dimensional space to a new (lower) space. You can't go back.</p> <p>Note that <code>Dimensionality Reduction</code> or <code>Feature Extraction</code> is different from <code>Feature Selection</code>. In <code>Feature Selection</code> you select a subset of the original feature set.</p> <p>Edit: in case you decide to use a Feature Selection technique, look at <a href="http://stackoverflow.com/questions/11116697/how-to-get-most-informative-features-for-scikit-learn-classifiers">this answer</a> in order to do what you want.</p>
1
2016-09-30T16:27:32Z
[ "python", "machine-learning", "scikit-learn" ]
List index while loop python
39,788,290
<p>I have an issue with the following code. When i typed the exact secret words character, the following code wont match the secret codes. </p> <pre><code>#initiate words for guessing secretWords =['cat','mouse','donkey','ant','lion'] #Generate a random word to be guessed generateWord = (random.choice(secretWords)) # User have attempts only to the random generate words LeftCount = 6 generateWord = ["_"] * len(secretWords) userInput="" LetterNumber=0 RightGuess =0 while (LeftCount !=0): print ("Word Contains", len(generateWord),"letters") print ("You have", str(LeftCount),"attempts remaining") print ("\n") print(generateWord) print ("\n") userInput=input("Enter word: ") while(LetterNumber&lt; len(generateWord)): if(generateWord[LetterNumber] == userInput): generateWord[LetterNumber]= userInput RightGuess +=1 LetterNumber +=1 LeftCount -=1 LetterNumber=0 if (RightGuess == len(generateWord)): print ("Congratulations") break if(LeftCount ==0): print ("Game over") </code></pre>
-2
2016-09-30T09:35:16Z
39,788,728
<p>You are overriding your selected word. <code>generateWord</code> is at the same time the secret word, and the user input. This can't work. Here is something that should do what you want (I also corrected some other problems):</p> <pre><code>import random secretWords = ["cat", "mouse", "donkey", "ant", "lion"] generatedWord = random.choice(secretWords) leftCount = 6 userWord = ["_"] * len(generatedWord) refusedLetters = "" #returns all positions of character ch in the string s def findOccurences(s, ch): return [i for i, letter in enumerate(s) if letter == ch] print("Word contains", len(generatedWord), "letters") while(leftCount &gt; 0 and generatedWord != "".join(userWord)): print ("\n") print ("You have", str(leftCount), "attempts remaining") print ("Letters not present in your word:", "".join(sorted(refusedLetters))) print ("Your word so far: ","".join(userWord)) print ("\n") #checks that the user enters something userInput = "" while not len(userInput): userInput=input("Enter letter or word: ") userInput = userInput.lower() #if len &gt; 1, then the user has tried to guess the whole word: if len(userInput) &gt; 1: if generatedWord == userInput: print("Congratulations") break else: print("Wrong word, sorry") #len == 1, thus the user asked for one letter else: #if letter isn't already found if not userInput in userWord: #for all occurences of the letter in the secret word occurences = findOccurences(generatedWord, userInput) for occurence in occurences: userWord[occurence] = userInput #if the letter was not found if not occurences: #if the letter has already been proposed if userInput in refusedLetters: print("You have already tried this letter") continue else: refusedLetters += userInput else: print("You have already tried this letter") continue leftCount -= 1 #the else statement will only be entered if we did not exit the previous loop via a break. #Thus, if the word has already been found, nothing happens here. else: if generatedWord == "".join(userWord): print("Congratulations") else: print("Game over") </code></pre>
0
2016-09-30T09:56:20Z
[ "python" ]
List index while loop python
39,788,290
<p>I have an issue with the following code. When i typed the exact secret words character, the following code wont match the secret codes. </p> <pre><code>#initiate words for guessing secretWords =['cat','mouse','donkey','ant','lion'] #Generate a random word to be guessed generateWord = (random.choice(secretWords)) # User have attempts only to the random generate words LeftCount = 6 generateWord = ["_"] * len(secretWords) userInput="" LetterNumber=0 RightGuess =0 while (LeftCount !=0): print ("Word Contains", len(generateWord),"letters") print ("You have", str(LeftCount),"attempts remaining") print ("\n") print(generateWord) print ("\n") userInput=input("Enter word: ") while(LetterNumber&lt; len(generateWord)): if(generateWord[LetterNumber] == userInput): generateWord[LetterNumber]= userInput RightGuess +=1 LetterNumber +=1 LeftCount -=1 LetterNumber=0 if (RightGuess == len(generateWord)): print ("Congratulations") break if(LeftCount ==0): print ("Game over") </code></pre>
-2
2016-09-30T09:35:16Z
39,788,802
<p>Why are you comparing one letter in generateWord to the entire userInput?</p> <pre><code>if(generateWord[LetterNumber] == userInput): </code></pre> <p>That line compares the character at "LetterNumber" index to the userInput, so if a user enters a word it will never return true. </p> <p>If you're attempting to count the number of correct letters in the users guess, shouldn't you be comparing each letter from the user input with the corresponding letter in the "generateWord". </p> <pre><code>if(generateWord[LetterNumber] == userInput[LetterNumber]): </code></pre> <p>Also some general points, variable names shouldn't start with a capital, it should be "letter_number" according to Python standards. Try to improve your variable names as well, maybe call it "generated_word", not "generate_word". "Generate_word" implies it is a function, as generate is a verb.</p> <p>The line after the if statement also reassigns the entire userInput into the generateWord value, at the letter index, why are you doing that?</p> <p>Finally, you need to generate a new word at the end of your while loop, or maybe the beginning, as at the moment you only generate a word at the beginning, then it will use the same word in each iteration.</p> <p><strong>Try to use print to print out some of your variables, it will help you debug your program, as it's definitely not doing what you expect.</strong></p>
2
2016-09-30T09:59:27Z
[ "python" ]
Python NameError: name '' is not defined
39,788,458
<p>I am fairly new to python, i have created this code for a controlled assessment but it is suggesting that 'q11' (the first of the web opening commands) is not defined. It is the same as the others and was working fine before but now i have begun work on it again but it just won't work. </p> <p>Thank you in advance </p> <p>Here is my code:</p> <pre><code>import webbrowser import random sol1 = ("Check if there is lint in the charging ports. This can be removed carefully with a toothpick or similar implement") sol2 = ("Turn on assistive touch if you have an iphone (settings &gt; general &gt; accessability &gt; assistive touch until you go to a shop to get them replaced. If you use android, download 'button savior' from the google play store") sol3 = ("Do a hard reset - hold down the power and home buttons until the screen turns off and keep them held down until the screen turns on again ") sol4 = ("Restore the phone to factory settings and set it up as new") sol5 = ("You need a screen replacement.") sol6 = ("You may need to replace the battery.") sol7 = ("You dont need to do anything. Your phone doesnt have any problems.") sol8 = ("Please update your phone software.") sol9 = ("Contact apple for support") sol10 = ("Take the phone and put it in a bag of rice for 24-36 hours to let the rice absorb the water.") q1=input("Is your phone charging correctly? ") if q1 == "no": print(sol1) if q1 == "yes": q2=input("Is your phone water damaged? ") if q2 == "yes": print(sol10) if q2 == "no": q3=input("Is the screen cracked or badly scratched? ") if q3 == "yes": print(sol5) if q3 == "no": q4=input("Is the phone working slowly and crashing? ") if q4 == "yes": print(sol3) if q4 == "no": q5=input("Do you wish to remove data from the phone? ") if q5 == "yes": print(sol4) if q5 == "no": q6=input("Does the phone work without issues? ") if q6 == "yes": print(sol7) if q6 == "no": q7=input("Are you running the lastest software version? ") if q7 == "no": print(sol8) if q7 == "yes": q8=input("Are the buttons producing accurate responses ") if q8 == "no": print(sol2) if q8 == "yes": q9=input("Is your phone battery draining and dying early? ") if q9 == "yes": print(sol6) if q9 == "no": q10=input("Does the phone turn on, even if it has been charged with a working charger? ") if q10 == "yes": print(sol9) if q10 == "no": q11=input("Would you like to visit the apple support site?: yes/no ") if q11 == "yes": webbrowser.open("https://support.apple.com/en-gb") if q11 == "no": q12=input("Would you like to visit the genius bar booking site?: yes/no ") if q12 == "yes": webbrowser.open("https://getsupport.apple.com/") if q12 == "no": </code></pre> <p>print("Thank you for using this service. We hope you found it useful")</p>
-1
2016-09-30T09:44:13Z
39,790,134
<p>Alright, been working on this for some time for you and I have added the following bits of code:</p> <pre><code>list = [] q1 = str(input("Is your phone charging correctly? ")) characters = len(q1) for i in range(characters): lowercase = str.lower(q1[i]) list.append(lowercase) q1 = ("".join(list)) </code></pre> <p>The characters variable counts the amount of characters entered in q1, eg if they typed 'yes' it would count 3 characters, 'no' it would count 2 characters etc. </p> <p>This lowercase variable bascially sets whatever they input into lowercase looping through the whole string. We created the for loop looping the amount of characters. (Example: they input 'YES' then the length would be saved as 3 and it would loop through each character in the string 'YES' changing it all to 'yes'.) </p> <p>The reason we need the length of the string is because without it we could not loop through the correct amount of times. (Example: if we just put a loop of 2 then if they inputted 'YES' it would only go through the string twice and would save as 'ye' and not include the third character. Same if the loop was 2 it would save it as 'y'.</p> <pre><code>list.append(lowercase) </code></pre> <p>This list.append basically adds the letter 'y' on the first loop into a list like this ['y'] then on the second loop it adds 'e' like this ['y','e'] and the third loop ['y','e','s']</p> <pre><code>q1 = ("".join(list)) </code></pre> <p>This part basically combines the list we just made ['y','e','s'] into a string called q1 which is the variable for your answers. It combines it into 'yes'.</p> <p>The reason I added the changing to lowercase in the first place is incase they enter 'Yes' or 'yES' or 'YES'... etc it will always be changed to all lowercase so that the answers can still work. </p> <pre><code>import webbrowser import random sol1 = ("Check if there is lint in the charging ports. This can be removed carefully with a toothpick or similar implement") sol2 = ("Turn on assistive touch if you have an iphone (settings &gt; general &gt; accessability &gt; assistive touch until you go to a shop to get them replaced. If you use android, download 'button savior' from the google play store") sol3 = ("Do a hard reset - hold down the power and home buttons until the screen turns off and keep them held down until the screen turns on again ") sol4 = ("Restore the phone to factory settings and set it up as new") sol5 = ("You need a screen replacement.") sol6 = ("You may need to replace the battery.") sol7 = ("You dont need to do anything. Your phone doesnt have any problems.") sol8 = ("Please update your phone software.") sol9 = ("Contact apple for support") sol10 = ("Take the phone and put it in a bag of rice for 24-36 hours to let the rice absorb the water.") list = [] q1 = str(input("Is your phone charging correctly? ")) characters = len(q1) for i in range(characters): lowercase = str.lower(q1[i]) list.append(lowercase) q1 = ("".join(list)) if q1 == "no": print(sol1) list = [] if q1 == "yes": q2 = str(input("Is your phone water damaged? ")) for i in range(len(q2)): lowercase = str.lower(q2[i]) list.append(lowercase) q2 = ("".join(list)) if q2 == "yes": print(sol10) list = [] if q2 == "no": q3 = str(input("Is the screen cracked or badly scratched? ")) for i in range(len(q3)): lowercase = str.lower(q3[i]) list.append(lowercase) q3 = ("".join(list)) if q3 == "yes": print(sol5) list = [] if q3 == "no": q4 = str(input("Is the phone working slowly and crashing? ")) for i in range(len(q4)): lowercase = str.lower(q4[i]) list.append(lowercase) q4 = ("".join(list)) if q4 == "yes": print(sol3) list = [] if q4 == "no": q5 = str(input("Do you wish to remove data from the phone? ")) for i in range(len(q5)): lowercase = str.lower(q5[i]) list.append(lowercase) q5 = ("".join(list)) if q5 == "yes": print(sol4) list = [] if q5 == "no": q6 = str(input("Does the phone work without issues? ")) for i in range(len(q6)): lowercase = str.lower(q6[i]) list.append(lowercase) q6 = ("".join(list)) if q6 == "yes": print(sol7) list = [] if q6 == "no": q7 = str(input("Are you running the lastest software version? ")) for i in range(len(q7)): lowercase = str.lower(q7[i]) list.append(lowercase) q7 = ("".join(list)) if q7 == "no": print(sol8) list = [] if q7 == "yes": q8 = str(input("Are the buttons producing accurate responses ")) for i in range(len(q8)): lowercase = str.lower(q8[i]) list.append(lowercase) q8 = ("".join(list)) if q8 == "no": print(sol2) list = [] if q8 == "yes": q9 = str(input("Is your phone battery draining and dying early? ")) for i in range(len(q9)): lowercase = str.lower(q9[i]) list.append(lowercase) q9 = ("".join(list)) if q9 == "yes": print(sol6) list = [] if q9 == "no": q10 = str(input("Does the phone turn on, even if it has been charged with a working charger? ")) for i in range(len(q10)): lowercase = str.lower(q10[i]) list.append(lowercase) q10 = ("".join(list)) if q10 == "yes": print(sol9) list = [] if q10 == "no": q11 = str(input("Would you like to visit the apple support site?: yes/no ")) for i in range(len(q11)): lowercase = str.lower(q11[i]) list.append(lowercase) q11 = ("".join(list)) if q11 == "yes": webbrowser.open("https://support.apple.com/en-gb") list = [] if q11 == "no": q12 = str(input("Would you like to visit the genius bar booking site?: yes/no ")) for i in range(len(q12)): lowercase = str.lower(q12[i]) list.append(lowercase) q12 = ("".join(list)) if q12 == "yes": webbrowser.open("https://getsupport.apple.com/") else: print() </code></pre>
-1
2016-09-30T11:09:21Z
[ "python", "undefined", "defined" ]
Python NameError: name '' is not defined
39,788,458
<p>I am fairly new to python, i have created this code for a controlled assessment but it is suggesting that 'q11' (the first of the web opening commands) is not defined. It is the same as the others and was working fine before but now i have begun work on it again but it just won't work. </p> <p>Thank you in advance </p> <p>Here is my code:</p> <pre><code>import webbrowser import random sol1 = ("Check if there is lint in the charging ports. This can be removed carefully with a toothpick or similar implement") sol2 = ("Turn on assistive touch if you have an iphone (settings &gt; general &gt; accessability &gt; assistive touch until you go to a shop to get them replaced. If you use android, download 'button savior' from the google play store") sol3 = ("Do a hard reset - hold down the power and home buttons until the screen turns off and keep them held down until the screen turns on again ") sol4 = ("Restore the phone to factory settings and set it up as new") sol5 = ("You need a screen replacement.") sol6 = ("You may need to replace the battery.") sol7 = ("You dont need to do anything. Your phone doesnt have any problems.") sol8 = ("Please update your phone software.") sol9 = ("Contact apple for support") sol10 = ("Take the phone and put it in a bag of rice for 24-36 hours to let the rice absorb the water.") q1=input("Is your phone charging correctly? ") if q1 == "no": print(sol1) if q1 == "yes": q2=input("Is your phone water damaged? ") if q2 == "yes": print(sol10) if q2 == "no": q3=input("Is the screen cracked or badly scratched? ") if q3 == "yes": print(sol5) if q3 == "no": q4=input("Is the phone working slowly and crashing? ") if q4 == "yes": print(sol3) if q4 == "no": q5=input("Do you wish to remove data from the phone? ") if q5 == "yes": print(sol4) if q5 == "no": q6=input("Does the phone work without issues? ") if q6 == "yes": print(sol7) if q6 == "no": q7=input("Are you running the lastest software version? ") if q7 == "no": print(sol8) if q7 == "yes": q8=input("Are the buttons producing accurate responses ") if q8 == "no": print(sol2) if q8 == "yes": q9=input("Is your phone battery draining and dying early? ") if q9 == "yes": print(sol6) if q9 == "no": q10=input("Does the phone turn on, even if it has been charged with a working charger? ") if q10 == "yes": print(sol9) if q10 == "no": q11=input("Would you like to visit the apple support site?: yes/no ") if q11 == "yes": webbrowser.open("https://support.apple.com/en-gb") if q11 == "no": q12=input("Would you like to visit the genius bar booking site?: yes/no ") if q12 == "yes": webbrowser.open("https://getsupport.apple.com/") if q12 == "no": </code></pre> <p>print("Thank you for using this service. We hope you found it useful")</p>
-1
2016-09-30T09:44:13Z
39,790,409
<p>Alternatively you could just make it so they input either y or n which would be a lot less lines of code.</p> <p>All I did differently from my previous answer is simply only made it loop once to change the 'Y' to lowercase or 'N' to lowercase. It's better to make it like this because when people use a program and are asked to input 'Y' they sometimes do 'y' instead, so always best to be sure.</p> <p>Also adding elif instead of if for a second if statement on the same thing is neater programming, somehow python allows it but if you ever move on to another programing language you have to use elif so may aswell get used to it now.</p> <pre><code>sol1 = ("Check if there is lint in the charging ports. This can be removed carefully with a toothpick or similar implement") </code></pre> <p>Another tip this variable above could be made into something a lot better than a spam of spaces, did you know '\n' in a string starts a new line. </p> <pre><code>import webbrowser import random sol1 = ("Check if there is lint in the charging ports. This can be removed\ncarefully with a toothpick or similar implement") sol2 = ("Turn on assistive touch if you have an iphone (settings &gt; general &gt;\naccessability &gt; assistive touch until you go to a shop to get them replaced If you use android, download 'button savior' from the google play store") sol3 = ("Do a hard reset - hold down the power and home buttons until the screen\nturns off and keep them held down until the screen turns on again ") sol4 = ("Restore the phone to factory settings and set it up as new") sol5 = ("You need a screen replacement.") sol6 = ("You may need to replace the battery.") sol7 = ("You dont need to do anything. Your phone doesnt have any problems.") sol8 = ("Please update your phone software.") sol9 = ("Contact apple for support") sol10 = ("Take the phone and put it in a bag of rice for\n24-36 hours to let the rice absorb the water.") q1 = str(input("Is your phone charging correctly? Y/N &gt;&gt; ")) for i in range(1): q1 = str.lower(q1) if q1 == "n": print(sol1) elif q1 == "y": q2 = str(input("Is your phone water damaged? Y/N &gt;&gt; ")) for i in range(1): q2 = str.lower(q2) if q2 == "y": print(sol10) elif q2 == "n": q3 = str(input("Is the screen cracked or badly scratched? Y/N &gt;&gt; ")) for i in range(1): q3 = str.lower(q3) if q3 == "y": print(sol5) elif q3 == "n": q4 = str(input("Is the phone working slowly and crashing? Y/N &gt;&gt; ")) for i in range(1): q4 = str.lower(q4) if q4 == "y": print(sol3) elif q4 == "n": q5 = str(input("Do you wish to remove data from the phone? Y/N &gt;&gt; ")) for i in range(1): q5 = str.lower(q5) if q5 == "y": print(sol4) elif q5 == "n": q6 = str(input("Does the phone work without issues? Y/N &gt;&gt; ")) for i in range(1): q6 = str.lower(q6) if q6 == "y": print(sol7) elif q6 == "n": q7 = str(input("Are you running the lastest software version? Y/N &gt;&gt; ")) for i in range(1): q7 = str.lower(q7) if q7 == "n": print(sol8) elif q7 == "y": q8 = str(input("Are the buttons producing accurate responses Y/N &gt;&gt; ")) for i in range(1): q8 = str.lower(q8) if q8 == "n": print(sol2) elif q8 == "y": q9 = str(input("Is your phone battery draining and dying early? Y/N &gt;&gt; ")) for i in range(1): q9 = str.lower(q9) if q9 == "y": print(sol6) elif q9 == "n": q10 = str(input("Does the phone turn on, even if it has been charged with a working charger? Y/N &gt;&gt; ")) for i in range(1): q10 = str.lower(q10) if q10 == "y": print(sol9) elif q10 == "n": q11 = str(input("Would you like to visit the apple support site?: yes/no Y/N &gt;&gt; ")) for i in range(1): q11 = str.lower(q11) if q11 == "y": webbrowser.open("https://support.apple.com/en-gb") elif q11 == "n": q12 = str(input("Would you like to visit the genius bar booking site?: Y/N &gt;&gt; ")) for i in range(1): q12 = str.lower(q12) if q12 == "y": webbrowser.open("https://getsupport.apple.com/") else: print() </code></pre>
-1
2016-09-30T11:24:33Z
[ "python", "undefined", "defined" ]
Python NameError: name '' is not defined
39,788,458
<p>I am fairly new to python, i have created this code for a controlled assessment but it is suggesting that 'q11' (the first of the web opening commands) is not defined. It is the same as the others and was working fine before but now i have begun work on it again but it just won't work. </p> <p>Thank you in advance </p> <p>Here is my code:</p> <pre><code>import webbrowser import random sol1 = ("Check if there is lint in the charging ports. This can be removed carefully with a toothpick or similar implement") sol2 = ("Turn on assistive touch if you have an iphone (settings &gt; general &gt; accessability &gt; assistive touch until you go to a shop to get them replaced. If you use android, download 'button savior' from the google play store") sol3 = ("Do a hard reset - hold down the power and home buttons until the screen turns off and keep them held down until the screen turns on again ") sol4 = ("Restore the phone to factory settings and set it up as new") sol5 = ("You need a screen replacement.") sol6 = ("You may need to replace the battery.") sol7 = ("You dont need to do anything. Your phone doesnt have any problems.") sol8 = ("Please update your phone software.") sol9 = ("Contact apple for support") sol10 = ("Take the phone and put it in a bag of rice for 24-36 hours to let the rice absorb the water.") q1=input("Is your phone charging correctly? ") if q1 == "no": print(sol1) if q1 == "yes": q2=input("Is your phone water damaged? ") if q2 == "yes": print(sol10) if q2 == "no": q3=input("Is the screen cracked or badly scratched? ") if q3 == "yes": print(sol5) if q3 == "no": q4=input("Is the phone working slowly and crashing? ") if q4 == "yes": print(sol3) if q4 == "no": q5=input("Do you wish to remove data from the phone? ") if q5 == "yes": print(sol4) if q5 == "no": q6=input("Does the phone work without issues? ") if q6 == "yes": print(sol7) if q6 == "no": q7=input("Are you running the lastest software version? ") if q7 == "no": print(sol8) if q7 == "yes": q8=input("Are the buttons producing accurate responses ") if q8 == "no": print(sol2) if q8 == "yes": q9=input("Is your phone battery draining and dying early? ") if q9 == "yes": print(sol6) if q9 == "no": q10=input("Does the phone turn on, even if it has been charged with a working charger? ") if q10 == "yes": print(sol9) if q10 == "no": q11=input("Would you like to visit the apple support site?: yes/no ") if q11 == "yes": webbrowser.open("https://support.apple.com/en-gb") if q11 == "no": q12=input("Would you like to visit the genius bar booking site?: yes/no ") if q12 == "yes": webbrowser.open("https://getsupport.apple.com/") if q12 == "no": </code></pre> <p>print("Thank you for using this service. We hope you found it useful")</p>
-1
2016-09-30T09:44:13Z
39,790,787
<p>You could even use a dictionary to get rid of all those variables such as sol1, sol2, sol3. That is really messy coding and inefficient. Try this dictionary:</p> <pre><code>solutions = {1: "Check if there is lint in the charging ports. This can be removed\ncarefully with a toothpick or similar implement", 2: "Turn on assistive touch if you have an iphone (settings &gt; general &gt;\naccessability &gt; assistive touch until you go to a shop to get them replaced If you use android, download 'button savior' from the google play store.", 3: "Do a hard reset - hold down the power and home buttons until the screen\nturns off and keep them held down until the screen turns on again ", 4: "Restore the phone to factory settings and set it up as new", 5: "You need a screen replacement.", 6: "You may need to replace the battery.", 7: "You dont need to do anything. Your phone doesnt have any problems.", 8: "Please update your phone software.", 9: "Contact apple for support", 10: "Take the phone and put it in a bag of rice for\n24-36 hours to let the rice absorb the water." } </code></pre> <p>It basically assigns the number 1: 'to the string here' and 2: 'to the string here'. It is pretty useful for what you are trying to do because making loads and loads of variables is not a clever thing to do as they can get confusing etc... </p> <p>But to get it to print the correct solution all you have to do is print(solutions[1]) for solution 1 or print(solutions[2]) for solution 2. Hope this helps!</p> <p><strong>Full code:</strong></p> <pre><code>solutions = {1: "Check if there is lint in the charging ports. This can be removed\ncarefully with a toothpick or similar implement", 2: "Turn on assistive touch if you have an iphone (settings &gt; general &gt;\naccessability &gt; assistive touch until you go to a shop to get them replaced If you use android, download 'button savior' from the google play store.", 3: "Do a hard reset - hold down the power and home buttons until the screen\nturns off and keep them held down until the screen turns on again ", 4: "Restore the phone to factory settings and set it up as new", 5: "You need a screen replacement.", 6: "You may need to replace the battery.", 7: "You dont need to do anything. Your phone doesnt have any problems.", 8: "Please update your phone software.", 9: "Contact apple for support", 10: "Take the phone and put it in a bag of rice for\n24-36 hours to let the rice absorb the water." } q1 = str(input("Is your phone charging correctly? Y/N &gt;&gt; ")) for i in range(1): q1 = str.lower(q1) if q1 == "n": print(solutions[1]) elif q1 == "y": q2 = str(input("Is your phone water damaged? Y/N &gt;&gt; ")) for i in range(1): q2 = str.lower(q2) if q2 == "y": print(solutions[2]) elif q2 == "n": q3 = str(input("Is the screen cracked or badly scratched? Y/N &gt;&gt; ")) for i in range(1): q3 = str.lower(q3) if q3 == "y": print(solutions[3]) elif q3 == "n": q4 = str(input("Is the phone working slowly and crashing? Y/N &gt;&gt; ")) for i in range(1): q4 = str.lower(q4) if q4 == "y": print(solutions[4]) elif q4 == "n": q5 = str(input("Do you wish to remove data from the phone? Y/N &gt;&gt; ")) for i in range(1): q5 = str.lower(q5) if q5 == "y": print(solutions[4]) elif q5 == "n": q6 = str(input("Does the phone work without issues? Y/N &gt;&gt; ")) for i in range(1): q6 = str.lower(q6) if q6 == "y": print(solutions[7]) elif q6 == "n": q7 = str(input("Are you running the lastest software version? Y/N &gt;&gt; ")) for i in range(1): q7 = str.lower(q7) if q7 == "n": print(solutions[8]) elif q7 == "y": q8 = str(input("Are the buttons producing accurate responses Y/N &gt;&gt; ")) for i in range(1): q8 = str.lower(q8) if q8 == "n": print(solutions[2]) elif q8 == "y": q9 = str(input("Is your phone battery draining and dying early? Y/N &gt;&gt; ")) for i in range(1): q9 = str.lower(q9) if q9 == "y": print(solutions[6]) elif q9 == "n": q10 = str(input("Does the phone turn on, even if it has been charged with a working charger? Y/N &gt;&gt; ")) for i in range(1): q10 = str.lower(q10) if q10 == "y": print(solutions[9]) elif q10 == "n": q11 = str(input("Would you like to visit the apple support site?: yes/no Y/N &gt;&gt; ")) for i in range(1): q11 = str.lower(q11) if q11 == "y": webbrowser.open("https://support.apple.com/en-gb") elif q11 == "n": q12 = str(input("Would you like to visit the genius bar booking site?: Y/N &gt;&gt; ")) for i in range(1): q12 = str.lower(q12) if q12 == "y": webbrowser.open("https://getsupport.apple.com/") else: print() </code></pre>
-1
2016-09-30T11:45:06Z
[ "python", "undefined", "defined" ]
converter wave 24 bit to 16 bit
39,788,464
<p>i wish to convert some wavs that are 48kHz 24 bit file.wav to 48kHz 16 bit file-2.wav</p> <pre><code>import wave origAudio = wave.open("Sample_5073.wav","r") frameRate = origAudio.getframerate() nChannels = origAudio.getnchannels() sampWidth = origAudio.getsampwidth() nbframe=origAudio.getnframes() da = np.fromstring(origAudio.readframes(48000), dtype=np.int16) left, right = da[0::2], da[1::2] </code></pre> <p>Thanks </p>
0
2016-09-30T09:44:33Z
39,804,023
<p>If converting files from 24 to 16 bit is the only thing you want to do, you could use <a href="http://sox.sourceforge.net/" rel="nofollow">SoX</a>, it doesn't get much easier than that:</p> <pre><code>sox file.wav -b 16 file-2.wav </code></pre> <p>SoX can also do many more things, just have a look at its <a href="http://sox.sourceforge.net/sox.html" rel="nofollow">man page</a>.</p> <p>If you want to use Python, I recommend the <a href="http://pysoundfile.readthedocs.io/" rel="nofollow">soundfile</a> module:</p> <pre><code>import soundfile as sf data, samplerate = sf.read('file.wav') sf.write('file-2.wav', data, samplerate, subtype='PCM_16') </code></pre> <p>Specifying <code>subtype='PCM_16'</code> isn't even strictly necessary, since it's the default anyway.</p> <p>If you really want to do it with the built-in <code>ẁave</code> module, have a look at my <a href="http://nbviewer.jupyter.org/github/mgeier/python-audio/blob/master/audio-files/audio-files-with-wave.ipynb" rel="nofollow">tutorial about the <code>wave</code> module</a>.</p>
0
2016-10-01T07:20:25Z
[ "python", "signals", "wave", "pyaudio" ]
moment.js date in Django template
39,788,572
<p>I want to display the date of the relevant text (for example, 3 days ago) using the moment.js. But my code does not work.</p> <p>My code, but it does not work:</p> <pre><code>&lt;div class="base"&gt; &lt;script type="text/javascript"&gt; var time = {{ obj.pub_date|date:'Ymd' }}; moment(time, "YYYYMMDD").fromNow(); &lt;/script&gt; &lt;p&gt;{{ obj.text }}&lt;/p&gt; &lt;/div&gt; </code></pre>
0
2016-09-30T09:49:26Z
39,788,691
<p>You are not assigning whatever is returned from your .fromNow() call to a variable, or doing anything with it.</p>
2
2016-09-30T09:54:23Z
[ "javascript", "python", "django", "momentjs" ]
Python SimpleHTTPServer to receive files
39,788,591
<p>I am using SimpleHTTPServer's do_POST method to receive file. The script is working fine if I upload the png file using curl but whenever I use python request library to upload file, File uploads but become corrupt. Here is the SimpleHTTPServer code</p> <pre><code>#!/usr/bin/env python # Simple HTTP Server With Upload. import os import posixpath import BaseHTTPServer import urllib import cgi import shutil import mimetypes import re try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): # Simple HTTP request handler with POST commands. def do_POST(self): """Serve a POST request.""" r, info = self.deal_post_data() print r, info, "by: ", self.client_address f = StringIO() if r: f.write("&lt;strong&gt;Success:&lt;/strong&gt;") else: f.write("&lt;strong&gt;Failed:&lt;/strong&gt;") length = f.tell() f.seek(0) self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(length)) self.end_headers() if f: self.copyfile(f, self.wfile) f.close() def deal_post_data(self): print self.headers boundary = self.headers.plisttext.split("=")[1] print 'Boundary %s' %boundary remainbytes = int(self.headers['content-length']) print "Remain Bytes %s" %remainbytes line = self.rfile.readline() remainbytes -= len(line) if not boundary in line: return (False, "Content NOT begin with boundary") line = self.rfile.readline() remainbytes -= len(line) fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line) if not fn: return (False, "Can't find out file name...") path = self.translate_path(self.path) fn = os.path.join(path, fn[0]) line = self.rfile.readline() remainbytes -= len(line) line = self.rfile.readline() remainbytes -= len(line) try: out = open(fn, 'wb') except IOError: return (False, "Can't create file to write, do you have permission to write?") preline = self.rfile.readline() remainbytes -= len(preline) while remainbytes &gt; 0: line = self.rfile.readline() remainbytes -= len(line) if boundary in line: preline = preline[0:-1] if preline.endswith('\r'): preline = preline[0:-1] out.write(preline) out.close() return (True, "File '%s' upload success!" % fn) else: out.write(preline) preline = line return (False, "Unexpect Ends of data.") def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path def copyfile(self, source, outputfile): """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. """ shutil.copyfileobj(source, outputfile) def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass) if __name__ == '__main__': test() </code></pre> <p>client side code to upload a file is here</p> <pre><code>#!/usr/bin/python import requests files = {'file': open('test.png', 'rb')} r = requests.post('http://192.168.5.134:8000', files=files) print r.request.headers </code></pre> <p>File was uploaded successfully but become corrupted. </p> <p><a href="http://i.stack.imgur.com/NOmXc.png" rel="nofollow">python request header</a></p> <p><a href="http://i.stack.imgur.com/Ct7ps.png" rel="nofollow">SimpleHTTPServer response</a></p> <p>Using curl [ curl -F 'file=@test.png' 192.168.5.134:8000/ -v ], file uploaded and opened successfully.</p> <p>Is there any issue in python-request code?</p>
1
2016-09-30T09:50:19Z
39,794,730
<p><code>curl</code> and <code>request</code> have a slightly different header, <code>curl</code> has an additional empty line while <code>requests</code> doesn't.</p> <p>Replace <code>preline = self.rfile.readline()</code> with the following block</p> <pre><code>if line.strip(): preline = line else: preline = self.rfile.readline() </code></pre>
0
2016-09-30T15:10:36Z
[ "python", "file-upload", "cgi", "python-requests", "simplehttpserver" ]
Speed optimisation in Flask
39,788,630
<p>My project (Python 2.7) consists of a screen scraper that collects data once a day, extracts what is useful and stores that in a couple of pickles. The pickles are rendered to an HTML-page using Flask/Ninja. All that works, but when running it on my localhost (Windows 10), it's rather slow. I plan to deploy it on PythonAnywhere. </p> <p>The site also has an about page. Content for the about page is a markdown file, that I convert to HTML using <code>markdown2</code> after each edit. The about-template loads the HTML, like so: </p> <pre><code>{% include 'about_content.html' %} </code></pre> <p>This loads <em>much</em> faster than letting <code>Flask-Markdown</code> render the about-text (as I had at first): </p> <pre><code>{% filter markdown %} {% include 'about_content.md' %} {% endfilter %} </code></pre> <p>Now then. I'm a bit worried that the main page will not load fast enough when I deploy the site. The content gets updated only once a day, there is no need to re-render anything if you refresh the main page. So I'm wondering if I can do a similar trick as with the about-content: </p> <p>Can I let Flask, after rendering the pickles, save the result as html, and then serve that from the site deployed? Or can I invoke some browser module, save its output, and serve that? Or is that a bad idea altogether, and shouldn't I worry because Flask is zoomingly fast on real life servers? </p>
1
2016-09-30T09:52:02Z
39,808,825
<h2>Your Question on Rendering</h2> <p>You can actually do a lot with Jinja. It is possible to run Jinja whenever you want and save it as a HTML file. This way every time you send a request for a file, it doesn't have to render it again. It just serves the static file.</p> <p>Here is some code. I have a view that doesn't change throughout it's lifetime. So I create a static HTML file once the view is created.</p> <pre><code>from jinja2 import Environment, FileSystemLoader def example_function(): '''Jinja templates are used to write to a new file instead of rendering when a request is received. Run this function whenever you need to create a static file''' # I tell Jinja to use the templates directory env = Environment(loader=FileSystemLoader('templates')) # Look for the results template template = env.get_template('results.html') # You just render it once. Pass in whatever values you need. # I'll only be changing the title in this small example. output_from_parsed_template = template.render(title="Results") with open("/directory/where/you/want/to/save/index.html", 'w') as f: f.write(output_from_parsed_template) # Flask route @app.route('/directory/where/you/want/to/save/&lt;path:path&gt;') def serve_static_file(path): return send_from_directory("directory/where/you/want/to/save/", path) </code></pre> <p>Now if you go the above URI <code>localhost:5000/directory/where/you/want/to/save/index.html</code> is served without rendering. </p> <p><strong>EDIT</strong> Note that <code>@app.route</code> takes a URL, so <code>/directory/where/you/want/to/save</code> must start at the root, otherwise you get <code>ValueError: urls must start with a leading slash</code>. Also, you can save the rendered page with the other templates, and then route it as below, eliminating the need for (and it's just as fast as) <code>send_from_directory</code>:</p> <pre><code>@app.route('/') def index(): return render_template('index.html') </code></pre> <h2>Other Ways</h2> <p>If you want to get better performance consider serving your Flask app via <em>gunicorn, nginx and the likes.</em> </p> <p><a href="https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-14-04" rel="nofollow">Setting up nginx, gunicorn and Flask</a> </p> <p><a href="http://stackoverflow.com/questions/33086555/why-shouldnt-flask-be-deployed-with-the-built-in-server">Don't use Flask in production</a></p> <p>Flask also has an option where you can enable multi threading. </p> <pre><code>app.run(threaded=True) </code></pre>
1
2016-10-01T16:16:57Z
[ "python", "html", "flask", "ninja" ]
How can I copy one collection from MongoDB using pymongo and paste to another empty collection?
39,788,664
<ol> <li>I want to copy full collection (e.g. name 'home').</li> <li>Then do some changes in the 'home' collection or remove doc inside it (not a collection).</li> <li>And then replace changed 'home' collection to its default state from item 1.</li> </ol> <p>I do next: </p> <pre><code>db = client["database"] home = db['home'].find() # get collection. db['home'].remove({}) # remove doc from home for i in home: self.db['home'].insert(i) </code></pre> <p>But the collection is empty.</p>
0
2016-09-30T09:53:31Z
39,927,543
<p>The problem with your code example is that <code>find()</code> returns a <a href="https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/" rel="nofollow">database cursor</a> to the collection, not all documents in the collection. So when you <code>remove</code> all documents from the <code>home</code> collection, the cursor will also point to an empty collection. </p> <p>In order to copy a collection to another collection in the same server, you can utilise <a href="https://docs.mongodb.com/manual/aggregation/" rel="nofollow">MongoDB Aggregation</a> operator <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/match/#pipe._S_match" rel="nofollow">$match</a> and <a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/out/" rel="nofollow">$out</a></p> <pre><code>pipeline = [ {"$match": {}}, {"$out": "destination_collection"}, ] db.source_collection.aggregate(pipeline) </code></pre> <p>Using your example code, <strong>now</strong> you can do </p> <pre><code>source = db["source_collection"] destination = db["destination_collection"] # Remove all documents, or make modifications. source.remove({}) # Restore documents from the source collection. for doc in destination: source.insert(doc) # or instead you can just use the same aggregation method above but reverse the collection name. </code></pre> <p><em>Note</em> : <a href="https://docs.mongodb.com/v3.2/reference/method/db.collection.copyTo/" rel="nofollow">db.collection.copyTo()</a> has been deprecated since MongoDB v3.0. </p> <p>If you would like to copy to another MongoDB server, you can utilise <a href="https://docs.mongodb.com/v3.2/reference/method/db.cloneCollection/" rel="nofollow">db.cloneCollection()</a>. In PyMongo it would be a command such below: </p> <pre><code>db.command("cloneCollection", **{'collection': "databaseName.source_collection", 'from': "another_host:another_port"}) </code></pre> <p>Depending on your overall goal, you may find <a href="https://docs.mongodb.com/manual/core/backups/" rel="nofollow">MongoDB BackUp methods</a> useful. </p>
1
2016-10-08T00:43:48Z
[ "python", "mongodb", "pymongo" ]
Tkinter ttk radiobutton variable update failure
39,788,665
<p>What's wrong with this?</p> <pre><code>var = StringVar() radBut1 = ttk.Radiobutton(root, text='A - Z', variable=var, value='AtoZ') radBut2= ttk.Radiobutton(root, text='Z - A', variable=var, value='ZtoA') </code></pre> <p>When I select either of the 2 radiobuttons, the var variable is not updated. I found a lot of conflicting material in different documentation sources and tutorials (and I tried everything I found) to no avail.</p> <p>I'm using the following to check the value of var:</p> <pre><code>print(var) </code></pre>
0
2016-09-30T09:53:36Z
39,803,642
<p>This works:</p> <pre><code>def updateRadioButtonVariable(radioButtonVar,updateString): radioButtonVar.set(updateString) #Sort Type Radio Button radioButtonVar = StringVar() radBut1= ttk.Radiobutton(root, text='A - Z', variable=radioButtonVar, value='AtoZ',command= lambda: updateRadioButtonVariable(radioButtonVar ,'AtoZ')) radBut2= ttk.Radiobutton(root, text='Z - A', variable=radioButtonVar, value='ZtoA',command= lambda: updateRadioButtonVariable(radioButtonVar ,'ZtoA')) </code></pre> <p>Not sure why the original code (which is almost template code from the documentation) doesn't work. If anyone has any ideas, please do share.</p>
0
2016-10-01T06:18:59Z
[ "python", "tkinter", "radio-button", "ttk" ]
Python - howto keep type of elements in list
39,788,683
<p>Sorry first to the pythonistas, C/C++ programmer having to do some python.</p> <p>I am porting some C (not C++), so I essentially want to create a list of structures to pass around for initialization, processing and writing on to a device over the serial port.</p> <p>I am keeping the python very close to the C so when the C is updated the python may easily get the same updates, so this means it looks procedural and there is some stuff I realize is nonsense, like creating an array, passing it off to be initialized and receiving it back (I understand that the one I create and pass in in is redundant)</p> <p>My problem is that when the array arrives to be processed, my list of recordtypes has become a flat list, so I can no longer accesses elements of my recordtype by name.</p> <p>I can cast them back (aka recreate each element from the list) but I would rather work out how to keep the type information intact.</p> <p>I have distilled the code to the following:</p> <pre><code>GainSettings = recordtype('GainSettings', 'label value') def init_arrays(Gains): labels = [ "Gain_1:", "Gain_2:", "Gain_48:" ] for itr in range(3): value = [] value.extend([0] * CHANNELS) label = labels[itr] entry = GainSettings(label, value) Gains.extend(entry) return True, Gains def process_array(Gains): thing = Gains[0].label # dies here with AttributeError: 'str' object has no attribute 'label' thing += "wibble" Gains[0].label = thing return True, Gains def main(args): # char* label; # sint16 value[CHANNELS]; Gains = [] # will be array of gain settings ret, Gain = init_arrays(Gains) ret, Gains = process_array(Gains) </code></pre> <p>I have a breakpoint where it fails so I can check the array, this tells me:</p> <pre><code>&gt;&gt;&gt; print type(Gains) &lt;type 'list'&gt; &gt;&gt;&gt; print Gains ['Gain_1:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Gain_2:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Gain_48:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] &lt;type 'list'&gt; &gt;&gt;&gt; print type(Gains[0]) &lt;type 'str'&gt; &gt;&gt;&gt; print type(Gains[1]) &lt;type 'list'&gt; </code></pre> <p>I would like it to say it is a list of "GainSettings".</p> <p>In reality there are a number of similar arrays, they have common items like label, the processing functions are supposed to take any type of array and use the similar parts to do the work.</p> <p>TIA</p> <p>Chris</p>
1
2016-09-30T09:54:09Z
39,788,873
<p>You don't have to return True, it is True already if the dictionary is non empty. I would suggest </p> <pre><code>CHANNELS = 14 def init_arrays(): labels = [ "Gain_1:", "Gain_2:", "Gain_48:" ] return {lab: [0]* CHANNELS for lab in labels} </code></pre> <p>then you just process it using </p> <pre><code>Gains[label] </code></pre> <p>edit: Well, now I realized you want to keep it C/C++like, so in this case I can't help, sorry :)</p>
0
2016-09-30T10:02:40Z
[ "python", "arrays", "recordtype" ]
Python - howto keep type of elements in list
39,788,683
<p>Sorry first to the pythonistas, C/C++ programmer having to do some python.</p> <p>I am porting some C (not C++), so I essentially want to create a list of structures to pass around for initialization, processing and writing on to a device over the serial port.</p> <p>I am keeping the python very close to the C so when the C is updated the python may easily get the same updates, so this means it looks procedural and there is some stuff I realize is nonsense, like creating an array, passing it off to be initialized and receiving it back (I understand that the one I create and pass in in is redundant)</p> <p>My problem is that when the array arrives to be processed, my list of recordtypes has become a flat list, so I can no longer accesses elements of my recordtype by name.</p> <p>I can cast them back (aka recreate each element from the list) but I would rather work out how to keep the type information intact.</p> <p>I have distilled the code to the following:</p> <pre><code>GainSettings = recordtype('GainSettings', 'label value') def init_arrays(Gains): labels = [ "Gain_1:", "Gain_2:", "Gain_48:" ] for itr in range(3): value = [] value.extend([0] * CHANNELS) label = labels[itr] entry = GainSettings(label, value) Gains.extend(entry) return True, Gains def process_array(Gains): thing = Gains[0].label # dies here with AttributeError: 'str' object has no attribute 'label' thing += "wibble" Gains[0].label = thing return True, Gains def main(args): # char* label; # sint16 value[CHANNELS]; Gains = [] # will be array of gain settings ret, Gain = init_arrays(Gains) ret, Gains = process_array(Gains) </code></pre> <p>I have a breakpoint where it fails so I can check the array, this tells me:</p> <pre><code>&gt;&gt;&gt; print type(Gains) &lt;type 'list'&gt; &gt;&gt;&gt; print Gains ['Gain_1:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Gain_2:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Gain_48:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] &lt;type 'list'&gt; &gt;&gt;&gt; print type(Gains[0]) &lt;type 'str'&gt; &gt;&gt;&gt; print type(Gains[1]) &lt;type 'list'&gt; </code></pre> <p>I would like it to say it is a list of "GainSettings".</p> <p>In reality there are a number of similar arrays, they have common items like label, the processing functions are supposed to take any type of array and use the similar parts to do the work.</p> <p>TIA</p> <p>Chris</p>
1
2016-09-30T09:54:09Z
39,789,266
<p>As I said in a comment, first of all, Python is not C. My suggestion is: take advantage of it, and use Python for your own good. Do not try to mimic C code. It will only make things harder.</p> <p>On the other hand, you are flattening your list in an unexpected way. I think instead of:</p> <pre><code>Gains.extend(entry) </code></pre> <p>You want:</p> <pre><code>Gains.append(entry) </code></pre> <p>See the difference:</p> <pre><code>&gt;&gt;&gt; from recordtype import recordtype &gt;&gt;&gt; A = recordtype('A', 'x y') &gt;&gt;&gt; x = A(1, 2) # Extend &gt;&gt;&gt; l = [] &gt;&gt;&gt; l.extend(x) &gt;&gt;&gt; l [1, 2] # Append &gt;&gt;&gt; l = [] &gt;&gt;&gt; l.append(x) &gt;&gt;&gt; l [A(x=1, y=2)] </code></pre> <p>The method <code>append()</code> adds an element to the list, while extend takes the recordtype as an iterable and, therefore, adds elements to the list for each of the records in the recordtype.</p> <p>Python is a beautiful programming language. Don't waste this opportunity and try to learn some! ;-)</p>
0
2016-09-30T10:22:59Z
[ "python", "arrays", "recordtype" ]
Python - howto keep type of elements in list
39,788,683
<p>Sorry first to the pythonistas, C/C++ programmer having to do some python.</p> <p>I am porting some C (not C++), so I essentially want to create a list of structures to pass around for initialization, processing and writing on to a device over the serial port.</p> <p>I am keeping the python very close to the C so when the C is updated the python may easily get the same updates, so this means it looks procedural and there is some stuff I realize is nonsense, like creating an array, passing it off to be initialized and receiving it back (I understand that the one I create and pass in in is redundant)</p> <p>My problem is that when the array arrives to be processed, my list of recordtypes has become a flat list, so I can no longer accesses elements of my recordtype by name.</p> <p>I can cast them back (aka recreate each element from the list) but I would rather work out how to keep the type information intact.</p> <p>I have distilled the code to the following:</p> <pre><code>GainSettings = recordtype('GainSettings', 'label value') def init_arrays(Gains): labels = [ "Gain_1:", "Gain_2:", "Gain_48:" ] for itr in range(3): value = [] value.extend([0] * CHANNELS) label = labels[itr] entry = GainSettings(label, value) Gains.extend(entry) return True, Gains def process_array(Gains): thing = Gains[0].label # dies here with AttributeError: 'str' object has no attribute 'label' thing += "wibble" Gains[0].label = thing return True, Gains def main(args): # char* label; # sint16 value[CHANNELS]; Gains = [] # will be array of gain settings ret, Gain = init_arrays(Gains) ret, Gains = process_array(Gains) </code></pre> <p>I have a breakpoint where it fails so I can check the array, this tells me:</p> <pre><code>&gt;&gt;&gt; print type(Gains) &lt;type 'list'&gt; &gt;&gt;&gt; print Gains ['Gain_1:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Gain_2:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Gain_48:', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] &lt;type 'list'&gt; &gt;&gt;&gt; print type(Gains[0]) &lt;type 'str'&gt; &gt;&gt;&gt; print type(Gains[1]) &lt;type 'list'&gt; </code></pre> <p>I would like it to say it is a list of "GainSettings".</p> <p>In reality there are a number of similar arrays, they have common items like label, the processing functions are supposed to take any type of array and use the similar parts to do the work.</p> <p>TIA</p> <p>Chris</p>
1
2016-09-30T09:54:09Z
39,789,353
<p>I think you should check this string:</p> <pre><code>Gains.extend(entry) </code></pre> <p>which just puts both label and value one after another into Gains list.</p> <p>Consider using</p> <pre><code>Gains.append(entry) </code></pre> <p>which will not unpack the tuple but append it whole to your list.</p>
1
2016-09-30T10:27:40Z
[ "python", "arrays", "recordtype" ]
Python tkinter: Canvas scrollbar appears but doesn't work
39,788,860
<p>I've been trying to add a scrollbar to a canvas that contains a single frame, this frame is what holds the widgets. I have added the scroll bar which shows up correctly but it has no effect on the canvas.</p> <pre><code>area2=Frame(border2,bg="#FAFAFA") area2.pack(side="top",fill=BOTH,expand=True) scrollbar=Scrollbar(area2) scrollbar.pack(side='right',fill=Y) scrollcanvas=Canvas(area2,height=1500,yscrollcommand=scrollbar.set) scrollcanvas.pack(side='left',fill=BOTH,expand=True) scrollcanvasframe=Frame(scrollcanvas) scrollcanvasframe.pack(side='top',fill=BOTH,expand=False) v2=IntVar() Label(scrollcanvasframe,textvariable=v2,bg="#FAFAFA").pack(side="top") canvas2=Canvas(scrollcanvasframe,width=800,height=566,bg='white') canvas2.pack(side="top") canvas3=Canvas(scrollcanvasframe,width=800,height=566,bg='grey') canvas3.pack(side="top") scrollbar.config(command=scrollcanvas.yview) scrollcanvas.config(yscrollcommand=scrollbar.set,scrollregion=(0,0,1000,1500)) </code></pre> <p>I think the issue might have something to do with the scrollregion which is added at the end because the canvas expands to fit the frame it is placed in.</p> <p>I have also tried looking at various posts here but nothing seems to be helping.</p>
0
2016-09-30T10:01:56Z
39,791,392
<p>You are trying to embed a frame which contains various other widgets into a canvas so that you can scroll around. However, after you create the <code>scrollcanvasframe</code> you pack it, with is incorrect. The canvas is a geometry manager in its own right and the correct way to make the canvas manage another widget is to use <code>create_window</code>.</p> <p>In this case, remove the <code>scrollcanvasframe.pack</code> call and replace as shown:</p> <pre><code>#scrollcanvasframe.pack(side='top',fill=BOTH,expand=False) scrollcanvas.create_window((5, 5), window=scrollcanvasframe, anchor=NW) </code></pre> <p>This creates a place holder for the frame widget in the canvas at position 5,5 and sets the anchor to the top left of the object (by default it is the center). Now the widget is being managed by the canvas and will scroll with any other elements. You can test this by adding a rectangle or line on there and see it scroll too.</p> <p>The other widgets that you have packed into the <code>scrollcanvasframe</code> are fine. They are being managed by the frame.</p>
1
2016-09-30T12:18:57Z
[ "python", "tkinter" ]
Python 2.7 Tk filedialog calling external programs
39,789,012
<p>I'm beginning to learn how to use python and need to develop some applications for a lab project.</p> <p>I am trying to create a GUI to select a couple of files I want to pass as arguments to another program. The GUI part seems to work, but when I try to call the external script using Popen method but the variables allegedly captured through the GUI are not being passed to the Popen call.</p> <p>I request your kind advice to solve this problem because it seems to be still a little beyond my current knowledge and I really need to use a Tk/GUI as interface for this project.</p> <p>Here is my code: </p> <pre><code>def button_fasta_callback(): fasta = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a FASTA') if fasta != None: data_fasta = fasta.read() fasta.close() def button_lista_callback(): lista = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a list') if lista !=None: data_lista = lista.read() lista.close() #####Create the buttons####### root = Tk() root.title("Sequence extractor") button_fasta = Button(root, text="Choose FASTA", command=button_fasta_callback) button_fasta.pack(padx=150, pady=50) button_lista = Button(root, text="Choose a list", command=button_lista_callback) button_lista.pack(padx=150, pady=50) entry = Entry(root, width=50) root.mainloop() caller = Popen(['C:\\Python_programs\\Seq_extractor.py', '-l', lista, '-f', fasta]) </code></pre> <p>Thank you all!</p>
-1
2016-09-30T10:10:16Z
39,790,242
<p>Your <code>fasta</code> and <code>lista</code> variables are local to the <code>button_*</code> functions and are not visible where you try and call <code>Popen</code>. A quick fix would be to use <code>global</code> to make these visible as global variables. A better fix would be to refactor this use use a class and assign <code>self.fasta</code> and <code>self.lista</code> making these be member variables of the class instance.</p>
1
2016-09-30T11:15:13Z
[ "python", "tkinter", "tk" ]
Prediction of sinusoidal function using pybrain
39,789,128
<p>In an attempt to understand neural networks and pybrain, I tried to predict a sinusoidal function in noise using only the time index as input. The premise therefore is that a simple NN structure can mimic <em>y(t) = sin(t)</em>.</p> <p>The design is: 1 input layer (linear), 1 hidden layer (tanh) and 1 output layer (linear). The number of nodes is: 1,10,1 for each respective layer.</p> <p>The input (time variable <em>t</em>) is scaled such that its range is <em>[0;1]</em>. The target is scaled either to have range <em>[0;1]</em> or <em>[-1;1]</em> with different results (given below).</p> <p>Here is my Python 2.7 code:</p> <pre><code>#!/usr/bin/python from __future__ import division import numpy as np import pylab as pl from pybrain.structure import TanhLayer, LinearLayer #SoftmaxLayer, SigmoidLayer from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure import FeedForwardNetwork from pybrain.structure import FullConnection np.random.seed(0) pl.close('all') #create NN structure: net = FeedForwardNetwork() inLayer = LinearLayer(1) hiddenLayer = TanhLayer(10) outLayer = LinearLayer(1) #add classes of layers to network, specify IO: net.addInputModule(inLayer) net.addModule(hiddenLayer) net.addOutputModule(outLayer) #specify how neurons are to be connected: in_to_hidden = FullConnection(inLayer, hiddenLayer) hidden_to_out = FullConnection(hiddenLayer, outLayer) #add connections to network: net.addConnection(in_to_hidden) net.addConnection(hidden_to_out) #perform internal initialisation: net.sortModules() #construct target signal: T = 1 Ts = T/10 f = 1/T fs = 1/Ts #NN input signal: t0 = np.arange(0,10*T,Ts) L = len(t0) #NN target signal: x0 = 10*np.cos(2*np.pi*f*t0) + 10 + np.random.randn(L) #normalise input signal: t = t0/np.max(t0) #normalise target signal to fit in range [0,1] (min) or [-1,1] (mean): dcx = np.min(x0) #np.min(x0) #np.mean(x0) x = x0-dcx sclf = np.max(np.abs(x)) x /= sclf #add samples and train NN: ds = SupervisedDataSet(1, 1) for c in range(L): ds.addSample(t[c], x[c]) trainer = BackpropTrainer(net, ds, learningrate=0.01, momentum=0.1) for c in range(20): e1 = trainer.train() print 'Epoch %d Error: %f'%(c,e1) y=np.zeros(L) for c in range(L): #y[c] = net.activate([x[c]]) y[c] = net.activate([t[c]]) yout = y*sclf yout = yout + dcx fig1 = pl.figure(1) pl.ion() fsize=8 pl.subplot(211) pl.plot(t0,x0,'r.-',label='input') pl.plot(t0,yout,'bx-',label='predicted') pl.xlabel('Time',fontsize=fsize) pl.ylabel('Amplitude',fontsize=fsize) pl.grid() pl.legend(loc='lower right',ncol=2,fontsize=fsize) pl.title('Target range = [0,1]',fontsize=fsize) fig1name = './sin_min.png' print 'Saving Fig. 1 to:', fig1name fig1.savefig(fig1name, bbox_inches='tight') </code></pre> <p>The output figures are given below.</p> <p><a href="http://i.stack.imgur.com/CpOYx.png" rel="nofollow"><img src="http://i.stack.imgur.com/CpOYx.png" alt="Output when target is scaled to fit range *[0;1]*"></a></p> <p><a href="http://i.stack.imgur.com/zwxm7.png" rel="nofollow"><img src="http://i.stack.imgur.com/zwxm7.png" alt="Output when target is scaled to fit range *[-1;1]*"></a></p> <p>Although the first figure shows better results, both outputs are unsatisfactory. Am I missing some fundamental neural network principle or is my code defective? I know there are easier statistical methods of estimating the target signal in this case, but the aim is to use a simple NN structure here.</p>
1
2016-09-30T10:15:25Z
39,793,150
<p>With a little bit tuning (more learning steps) it is possible to predict with a neural network exactly the sinus function. To determine the limits of neural networks the prediction of "inverse kinematics" will be more usefull. In that example most neural networks will fail because the solver produces high CPU demand without any results. Another example for testing out the limits of neural networks are reinforcement learning problems from games.</p> <p>The disappointing aspect of neural networks is, that they can predict easy mathematical function but fail in complex domains. As "easy" is defined every problem where the solver (Backproptrainer) needs low cpu-power to reach a given accuracy.</p>
-1
2016-09-30T13:50:59Z
[ "python", "neural-network", "time-series", "prediction", "pybrain" ]
Prediction of sinusoidal function using pybrain
39,789,128
<p>In an attempt to understand neural networks and pybrain, I tried to predict a sinusoidal function in noise using only the time index as input. The premise therefore is that a simple NN structure can mimic <em>y(t) = sin(t)</em>.</p> <p>The design is: 1 input layer (linear), 1 hidden layer (tanh) and 1 output layer (linear). The number of nodes is: 1,10,1 for each respective layer.</p> <p>The input (time variable <em>t</em>) is scaled such that its range is <em>[0;1]</em>. The target is scaled either to have range <em>[0;1]</em> or <em>[-1;1]</em> with different results (given below).</p> <p>Here is my Python 2.7 code:</p> <pre><code>#!/usr/bin/python from __future__ import division import numpy as np import pylab as pl from pybrain.structure import TanhLayer, LinearLayer #SoftmaxLayer, SigmoidLayer from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure import FeedForwardNetwork from pybrain.structure import FullConnection np.random.seed(0) pl.close('all') #create NN structure: net = FeedForwardNetwork() inLayer = LinearLayer(1) hiddenLayer = TanhLayer(10) outLayer = LinearLayer(1) #add classes of layers to network, specify IO: net.addInputModule(inLayer) net.addModule(hiddenLayer) net.addOutputModule(outLayer) #specify how neurons are to be connected: in_to_hidden = FullConnection(inLayer, hiddenLayer) hidden_to_out = FullConnection(hiddenLayer, outLayer) #add connections to network: net.addConnection(in_to_hidden) net.addConnection(hidden_to_out) #perform internal initialisation: net.sortModules() #construct target signal: T = 1 Ts = T/10 f = 1/T fs = 1/Ts #NN input signal: t0 = np.arange(0,10*T,Ts) L = len(t0) #NN target signal: x0 = 10*np.cos(2*np.pi*f*t0) + 10 + np.random.randn(L) #normalise input signal: t = t0/np.max(t0) #normalise target signal to fit in range [0,1] (min) or [-1,1] (mean): dcx = np.min(x0) #np.min(x0) #np.mean(x0) x = x0-dcx sclf = np.max(np.abs(x)) x /= sclf #add samples and train NN: ds = SupervisedDataSet(1, 1) for c in range(L): ds.addSample(t[c], x[c]) trainer = BackpropTrainer(net, ds, learningrate=0.01, momentum=0.1) for c in range(20): e1 = trainer.train() print 'Epoch %d Error: %f'%(c,e1) y=np.zeros(L) for c in range(L): #y[c] = net.activate([x[c]]) y[c] = net.activate([t[c]]) yout = y*sclf yout = yout + dcx fig1 = pl.figure(1) pl.ion() fsize=8 pl.subplot(211) pl.plot(t0,x0,'r.-',label='input') pl.plot(t0,yout,'bx-',label='predicted') pl.xlabel('Time',fontsize=fsize) pl.ylabel('Amplitude',fontsize=fsize) pl.grid() pl.legend(loc='lower right',ncol=2,fontsize=fsize) pl.title('Target range = [0,1]',fontsize=fsize) fig1name = './sin_min.png' print 'Saving Fig. 1 to:', fig1name fig1.savefig(fig1name, bbox_inches='tight') </code></pre> <p>The output figures are given below.</p> <p><a href="http://i.stack.imgur.com/CpOYx.png" rel="nofollow"><img src="http://i.stack.imgur.com/CpOYx.png" alt="Output when target is scaled to fit range *[0;1]*"></a></p> <p><a href="http://i.stack.imgur.com/zwxm7.png" rel="nofollow"><img src="http://i.stack.imgur.com/zwxm7.png" alt="Output when target is scaled to fit range *[-1;1]*"></a></p> <p>Although the first figure shows better results, both outputs are unsatisfactory. Am I missing some fundamental neural network principle or is my code defective? I know there are easier statistical methods of estimating the target signal in this case, but the aim is to use a simple NN structure here.</p>
1
2016-09-30T10:15:25Z
39,823,709
<p>The issue is the range of input and output values. By <a href="https://en.wikipedia.org/wiki/Feature_scaling#Standardization" rel="nofollow">standardizing</a> these signals, the problem is solved.</p> <p><a href="http://i.stack.imgur.com/HmFIi.png" rel="nofollow"><img src="http://i.stack.imgur.com/HmFIi.png" alt="NN input and output signal"></a></p> <p>This can be explained by considering the <em>sigmoid</em> and <em>tanh</em> activation functions, displayed below. <a href="http://i.stack.imgur.com/X2gwQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/X2gwQ.png" alt="sigmoid and tanh activation functions"></a></p> <p>The results will depend on the specific application. Also, changing the activation function (see <a href="http://stackoverflow.com/questions/13632976/neural-network-with-tanh-wrong-saturation-with-normalized-data">this answer</a>) will probably also affect the optimal scaling values of the input and output signals.</p>
0
2016-10-03T02:09:51Z
[ "python", "neural-network", "time-series", "prediction", "pybrain" ]
Proper way to check type when object might be an object() instance
39,789,249
<p>I'm looking for the proper way to check a type of object that might be an instance of object() now i'm doing this:</p> <pre><code>def _default_json_encoder(obj): """ Default encoder, encountered must have to_dict method to be serialized. """ if hasattr(obj, "to_dict"): return obj.to_dict() else: # object() is used in the base code to be evaluated as True if type(obj) == type(object()): return {} raise TypeError( 'Object of type %s with value of ' '%s is not JSON serializable' % (type(obj), repr(obj)) ) </code></pre> <p>but </p> <pre><code>if type(obj) == type(object()): return {} </code></pre> <p>is not recommended, unfortunately</p> <pre><code>if isinstance(obj, object): return {} </code></pre> <p>won't work because all object will be evaluated as True. </p> <p>So <code>type(obj) == type(object())</code> is the only way ? </p>
0
2016-09-30T10:21:53Z
39,789,424
<p>If you really have instances of <code>object()</code> in your data structure, then you'd use:</p> <pre><code>type(obj) is object </code></pre> <p>to test for direct instances (classes are typically singletons).</p> <p>However, I'd rethink my data structure, and either use another primitive value (like <code>True</code>), a dedicated singleton, or a dedicated class.</p> <p>A dedicated singleton could be:</p> <pre><code>sentinel = object() </code></pre> <p>then test for that sentinel:</p> <pre><code>if obj is sentinel: return {} </code></pre>
1
2016-09-30T10:31:29Z
[ "python", "python-3.x", "types" ]
Efficient matrix vector structure for improving cython code
39,789,262
<p>I have to run some simulations over a system of SODEs. Since I need to use random graphs I thought it was a good idea to use python for generating the adjacent matrix for the graph and then C for the simulations. So I turned to cython.</p> <p>I wrote my code following the hints of <a href="http://docs.cython.org/en/latest/src/tutorial/numpy.html" rel="nofollow">cython documentation</a> for improving its speed as much as possible. But know I really don't know if my code is good or not. I run <code>cython toast.pyx -a</code> too, but I don't understand the problems.</p> <ul> <li>What is the best structure to use for vectors and matrix in cython? How should I define, for example, <code>bruit</code> on my code with <code>np.array</code> or <code>double</code>? Note that I will compare elements of the matrix (0 or 1) in order to do a sum or not. The result will be a matrix NxT, where N is the dimension of the system and T it's the time I want to use for simulations.</li> <li>Where can I find the documentation for <code>double[:]</code>?</li> <li>How can I declare vectors and matrix (es G, W and X below) in the input of a function? And how can I declare a vector with <code>double</code>?</li> </ul> <p>But I let my code talk for me:</p> <pre><code>from __future__ import division import scipy.stats as stat import numpy as np import networkx as net #C part from libc.math cimport sin from libc.math cimport sqrt #cimport cython cimport numpy as np cimport cython cdef double tau = 2*np.pi #http://tauday.com/ #graph def graph(int N, double p): """ It generates an adjacency matrix for a Erdos-Renyi graph G{N,p} (by default not directed). Note that this is an O(n^2) algorithm and it gives an array, not a (sparse) matrix. Remark: fast_gnp_random_graph(n, p, seed=None, directed=False) is O(n+m), where m is the expected number of edges m=p*n*(n-1)/2. Arguments: N : number of edges p : probability for edge creation """ G=net.gnp_random_graph(N, p, seed=None, directed=False) G=net.adjacency_matrix(G, nodelist=None, weight='weight') G=G.toarray() return G @cython.boundscheck(False) @cython.wraparound(False) #simulations def simul(int N, double H, G, np.ndarray W, np.ndarray X, double d, double eps, double T, double dt, int kt_max): """ For details view the general description of the package. Argumets: N : population size H : coupling strenght complete case G : adjiacenty matrix W : disorder X : initial condition d : diffusion term eps : 0 for the reversibily case, 1 for the non-rev case T : time of the simulation dt : increment time steps kt_max = (int) T/dt """ cdef int kt #kt_max = T/dt to check cdef np.ndarray xt = np.zeros([N,kt_max], dtype=np.float64) cdef double S1 = 0.0 cdef double Stilde1 = 0.0 cdef double xtmp, xtilde, x_diff, xi cdef np.ndarray bruit = d*sqrt(dt)*stat.norm.rvs(N) cdef int i, j, k for i in range(N): #setting initial conditions xt[i][0]=X[i] for kt in range(kt_max-1): for i in range(N): S1 = 0.0 Stilde1= 0.0 xi = xt[i][kt] for j in range(N): #computation of the sum with the adjiacenty matrix if G[i][j]==1: x_diff = xt[j][kt] - xi S2 = S2 + sin(x_diff) xtilde = xi + (eps*(W[i]) + (H/N)*S1)*dt + bruit[i] for j in range(N): if G[i][j]==1: x_diff = xt[j][kt] - xtilde Stilde2 = Stilde2 + sin(x_diff) #computation of xt[i] xtmp = xi + (eps*(W[i]) + (H/N)*(S1+Stilde1)*0.5)*dt + bruit xt[i][kt+1] = xtmp%tau return xt </code></pre> <p>Thank you very much!</p> <h1>Update</h1> <p>I changed the order of the variables definitions, <code>np.array</code> to <code>double</code> and <code>xt[i][j]</code> to <code>xt[i,j]</code> and the matrix to <code>long long</code>. The code is pretty faster now and the yellow part on the html file is just around the declaration. Thanks!</p> <pre><code>from __future__ import division import scipy.stats as stat import numpy as np import networkx as net #C part from libc.math cimport sin from libc.math cimport sqrt #cimport cython cimport numpy as np cimport cython cdef double tau = 2*np.pi #http://tauday.com/ #graph def graph(int N, double p): """ It generates an adjacency matrix for a Erdos-Renyi graph G{N,p} (by default not directed). Note that this is an O(n^2) algorithm and it gives an array, not a (sparse) matrix. Remark: fast_gnp_random_graph(n, p, seed=None, directed=False) is O(n+m), where m is the expected number of edges m=p*n*(n-1)/2. Arguments: N : number of edges p : probability for edge creation """ G=net.gnp_random_graph(N, p, seed=None, directed=False) G=net.adjacency_matrix(G, nodelist=None, weight='weight') G=G.toarray() return G @cython.boundscheck(False) @cython.wraparound(False) #simulations def simul(int N, double H, long long [:, ::1] G, double[:] W, double[:] X, double d, double eps, double T, double dt, int kt_max): """ For details view the general description of the package. Argumets: N : population size H : coupling strenght complete case G : adjiacenty matrix W : disorder X : initial condition d : diffusion term eps : 0 for the reversibily case, 1 for the non-rev case T : time of the simulation dt : increment time steps kt_max = (int) T/dt """ cdef int kt #kt_max = T/dt to check cdef double S1 = 0.0 cdef double Stilde1 = 0.0 cdef double xtmp, xtilde, x_diff cdef double[:] bruit = d*sqrt(dt)*np.random.standard_normal(N) cdef double[:, ::1] xt = np.zeros((N, kt_max), dtype=np.float64) cdef double[:, ::1] yt = np.zeros((N, kt_max), dtype=np.float64) cdef int i, j, k for i in range(N): #setting initial conditions xt[i,0]=X[i] for kt in range(kt_max-1): for i in range(N): S1 = 0.0 Stilde1= 0.0 for j in range(N): #computation of the sum with the adjiacenty matrix if G[i,j]==1: x_diff = xt[j,kt] - xt[i,kt] S1 = S1 + sin(x_diff) xtilde = xt[i,kt] + (eps*(W[i]) + (H/N)*S1)*dt + bruit[i] for j in range(N): if G[i,j]==1: x_diff = xt[j,kt] - xtilde Stilde1 = Stilde1 + sin(x_diff) #computation of xt[i] xtmp = xt[i,kt] + (eps*(W[i]) + (H/N)*(S1+Stilde1)*0.5)*dt + bruit[i] xt[i,kt+1] = xtmp%tau return xt </code></pre>
1
2016-09-30T10:22:36Z
39,790,358
<p><code>cython -a</code> color codes the cython source. If you click on a line it shows the corrsponding C source. As a rule of thumb, you don't want anything yellow in your inner loops.</p> <p>A couple of things jump out in your code:</p> <ul> <li><code>x[j][i]</code> creates a temporary array for <code>x[j]</code> on each invocation, so use <code>x[j, i]</code> instead.</li> <li>instead of <code>cdef ndarray x</code> better either provide the dimensionality and dtype (<code>cdef ndarray[ndim=2, dtype=float]</code>) or --- preferably --- use the typed memoryview syntax: <code>cdef double[:, :] x</code>.</li> </ul> <p>E.g., instead of</p> <pre><code>cdef np.ndarray xt = np.zeros([N,kt_max], dtype=np.float64) </code></pre> <p>better use</p> <pre><code>cdef double[:, ::1] xt = np.zeros((N, kt_max), dtype=np.float64) </code></pre> <ul> <li>Make sure you're accessing memory in the cache-friendly pattern. E.g., make sure your arrays are in C order (last dimension varies the fastest), declare the memoryviews as <code>double[:, ::1]</code> and iterate over the array with the last index varying the fastest.</li> </ul> <p><strong>EDIT</strong>: See <a href="http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html" rel="nofollow">http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html</a> for the <em>typed memoryview</em> syntax <code>double[:, ::1]</code> etc</p>
1
2016-09-30T11:21:29Z
[ "python", "numpy", "optimization", "cython" ]
Python Import Error not working
39,789,284
<p>I currently have the following directory structure: </p> <pre><code>Folder/ package/ __init__.py, .. many python files subfolder/ file1.py </code></pre> <p>Now, my problem is that I am in the <code>Folder</code> directory. I can run python and then run <code>import package</code>. This works fine. However, in my <code>file1.py</code>, I import <code>package</code> at the beginning but when I run <code>python subfolder/file1.py</code>, it cannot find module named <code>package</code>.</p> <p>Edited: I currently have __ init__.py (with 2 underscores)</p>
0
2016-09-30T10:23:54Z
39,789,371
<p>Rename <code>_init_.py</code> to <code>__init__.py</code> (two underscores)</p>
0
2016-09-30T10:28:46Z
[ "python", "import" ]
Python Import Error not working
39,789,284
<p>I currently have the following directory structure: </p> <pre><code>Folder/ package/ __init__.py, .. many python files subfolder/ file1.py </code></pre> <p>Now, my problem is that I am in the <code>Folder</code> directory. I can run python and then run <code>import package</code>. This works fine. However, in my <code>file1.py</code>, I import <code>package</code> at the beginning but when I run <code>python subfolder/file1.py</code>, it cannot find module named <code>package</code>.</p> <p>Edited: I currently have __ init__.py (with 2 underscores)</p>
0
2016-09-30T10:23:54Z
39,789,516
<p>In the latter case, Python cannot find <code>package</code> because it is not visible on <code>sys.path</code>. <code>sys.path</code> will contain amongst other things the parent directory of the script currently being executed.</p> <p>So when you run Python from <code>Folder</code>, this entry is <code>/path/to/Folder</code> and <code>import package</code> correctly finds the <code>package</code> directory from this. In your second case, this entry will be <code>/path/to/Folder/subfolder</code> and <code>import package</code> will fail because it tries to find <code>/path/to/Folder/subfolder/package</code>.</p>
2
2016-09-30T10:35:51Z
[ "python", "import" ]
Tensorflow Variables and Ops vs. Python Equivalents
39,789,298
<p>I'm new to Tensorflow.</p> <ul> <li>Is it necessary to use tensorflow's function, such as using <code>tf.constant()</code> to replace <code>int32</code>, <code>float32</code> or else?</li> <li>Also during computation, using <code>tf.mul()</code> instead of normal Python multiplication <code>*</code>?</li> <li>Also the print function <code>tf.Print()</code> instead of <code>print()</code>?</li> </ul>
0
2016-09-30T10:24:18Z
39,797,939
<p>Because tensorflow is built upon a computation graph. When you construct the graph in python, you are just building is a description of computations (not actually doing the computation). To compute anything, a graph must be launched in a Session. So it's best to do the computation with the tensorflow ops.</p> <p><a href="https://www.tensorflow.org/versions/r0.11/get_started/basic_usage.html" rel="nofollow">https://www.tensorflow.org/versions/r0.11/get_started/basic_usage.html</a></p>
1
2016-09-30T18:32:29Z
[ "python", "tensorflow" ]
Tensorflow Variables and Ops vs. Python Equivalents
39,789,298
<p>I'm new to Tensorflow.</p> <ul> <li>Is it necessary to use tensorflow's function, such as using <code>tf.constant()</code> to replace <code>int32</code>, <code>float32</code> or else?</li> <li>Also during computation, using <code>tf.mul()</code> instead of normal Python multiplication <code>*</code>?</li> <li>Also the print function <code>tf.Print()</code> instead of <code>print()</code>?</li> </ul>
0
2016-09-30T10:24:18Z
39,801,361
<p>As noted <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/framework.md#class-tftensor-tensor" rel="nofollow">here</a>, </p> <blockquote> <p>A Tensor is a symbolic handle to one of the outputs of an Operation. It does not hold the values of that operation's output, but instead provides a means of computing those values in a TensorFlow Session</p> </blockquote> <p>So tensor variables aren't like python variables. Rather they specify the relationship between operations in the <a href="https://www.tensorflow.org/versions/r0.11/resources/faq.html#building-a-tensorflow-graph" rel="nofollow">computational graph</a>. The python variables that you use to describe the graph are for the programmer's convenience, but it might be easier to think about the python variables and the tensor variables as being in parallel namespaces. This example may help:</p> <pre><code>with tf.Session() as sess: a = tf.constant([1, 2, 3]) b = tf.Variable([]) b = 2 * a sess.run(tf.initialize_all_variables()) print(b) # Tensor("mul:0", shape=(3,), dtype=int32) print(b.eval()) # [2, 4, 6] b = tf.Print(b, [b]) # [2, 4, 6] (at the command line) </code></pre> <p>From this you can see:</p> <ul> <li><code>print(b)</code> returns information about the operation that 'b' refers to as well as the variable shape and data type, but not the value.</li> <li><code>b.eval()</code> (or <code>sess.run(b)</code>) returns the value of <code>b</code> as a numpy array which can be printed by a python <code>print()</code></li> <li><code>tf.Print()</code> allows you to see the value of <code>b</code> during graph execution. </li> </ul> <p>Note that the syntax of <code>tf.Print()</code> might seem a little strange to a newbie. As described in the documentation <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/control_flow_ops.html#Print" rel="nofollow">here</a>, <code>tf.Print()</code> is an identity operation that only has the side effect of printing to the command line. The first parameter is just passed through. The second parameter is the list of tensors that are printed and can be different than the first parameter. Also note that in order for <code>tf.Print()</code> to do something, a variable used in a subsequent call to <code>sess.run()</code> needs to be dependent on the tensor output by <code>tf.Print()</code>, otherwise this portion of the graph will not be executed.</p> <p>Finally with respect to math ops such as <code>tf.mul()</code> vs <code>*</code> many of the normal python ops are overloaded with the equivalent tensorflow ops, as described <a href="http://stackoverflow.com/a/37901852/5587428">here</a>.</p>
1
2016-09-30T23:18:20Z
[ "python", "tensorflow" ]
hl7apy not displaying data with multiple OBX fields
39,789,299
<p>I am trying to parse hl7 files using <strong>hl7apy</strong> i am having below hl7 sample</p> <p><strong>sample :</strong></p> <pre><code>MSH|^~\&amp;|XXXX|C|PRIORITYHEALTH|PRIORITYHEALTH|20080511103530||ORU^R01|Q335939501T337311002|P|2.3||| PID|1||94000000000^^^Priority Health||LASTNAME^FIRSTNAME^INIT||19460101|M||||| PD1|1|||1234567890^PCPLAST^PCPFIRST^M^^^^^NPI| OBR|1||185L29839X64489JLPF~X64489^ACC_NUM|JLPF^Lipid Panel - C||||||||||||1694^DOCLAST^DOCFIRST^^MD||||||20080511103529||| OBX|1|NM|JHDL^HDL Cholesterol (CAD)|1|62|CD:289^mg/dL|&gt;40^&gt;40|""||""|F|||20080511103500|||^^^""| OBX|2|NM|JTRIG^Triglyceride (CAD)|1|72|CD:289^mg/dL|35-150^35^150|""||""|F|||20080511103500|||^^^""| OBX|3|NM|JVLDL^VLDL-C (calc - CAD)|1|14|CD:289^mg/dL||""||""|F|||20080511103500|||^^^""| OBX|4|NM|JLDL^LDL-C (calc - CAD)|1|134|CD:289^mg/dL|0-100^0^100|H||""|F|||20080511103500|||^^^""| OBX|5|NM|JCHO^Cholesterol (CAD)|1|210|CD:289^mg/dL|90-200^90^200|H||""|F|||20080511103500|||^^^""| </code></pre> <p><strong>Code:</strong></p> <pre><code>from hl7apy import parser from hl7apy.exceptions import UnsupportedVersion hl7 = open('sample.hl7', 'r').read() try: m = parser.parse_message(hl7) except UnsupportedVersion: m = parser.parse_message(hl7.replace("n", "r")) print(m.obx.obx_1.value) </code></pre> <p>but when i am trying to read OBX (Repeating segments) i am not getting any data, it is displaying nothing. What is am i doing wrong ?</p>
1
2016-09-30T10:24:18Z
39,804,189
<p>You have an error in your code. It should be</p> <pre><code>hl7.replace("\n", "\r") </code></pre> <p>You have to write all groups, if you want to access a field in (a) group(s)</p> <p>try <code>m.ORU_R01_RESPONSE.ORU_R01_ORDER_OBSERVATION.ORU_R01_OBSERVATION.OBX[0].obx_1.value</code> for the first value of the first obx segment and so on.</p> <p>I recommend to read <a href="https://github.com/crs4/hl7apy/issues/8" rel="nofollow">Improve hl7apy documentation</a></p>
1
2016-10-01T07:41:09Z
[ "python", "hl7", "hl7-v2" ]
Filling dataframe columns based on ranges described in other columns
39,789,503
<p>I have a very interesting problem here, I have a dataset like,</p> <pre><code> id, start, end 1234 200 400 1235 300 500 1236 100 900 1236 200 1200 1236 300 1400 </code></pre> <p><strong>Main Objective</strong> : I want to count the number of concurrent sessions for each id.</p> <pre><code>at 100, id:1236 has 1 session running at 200, id:1236 has 2 sessions at 300, id:1236 has 3 sessions ... at 1000m id:1236 has 2 sessions etc </code></pre> <p><strong>My solution</strong> :</p> <ul> <li>Add columns from 1 to 1400 (min and max of sessions) to all rows</li> <li>fill the columns between session start value and session end value with 1</li> <li>then add all the rows of the user so to get the above result.</li> </ul> <p><strong>In pandas</strong> :</p> <pre><code>df = pd.read_csv(data+fileName,sep="\t",usecols=[0,1,2],names=['id','start','end']) for i in range(0,1440): df[str(i)]=0 print df.columns </code></pre> <p>I could add the columns and was thinking <strong>how to fill 1 to these columns between session start and end in each row</strong>. Each row can have different session start and end.</p> <p>Any hint would help a lot. I am just trying it in pandas, but later <em>I have to port it to Apache pyspark where there is no pandas in worker nodes</em>.</p>
0
2016-09-30T10:35:06Z
39,876,088
<p>In Pandas you could also do this: df[(df.start &lt;= t)&amp;(df.end >= t)].groupby("id").count()['start'].reset_index() where t is your desired time. Just rename the final column accordingly. But I don't know if this can be ported over the pyspark.@Khris</p>
0
2016-10-05T14:02:03Z
[ "python", "pandas", "dataframe", "pyspark-sql" ]
unable to use cmd command in python
39,789,535
<p>I am using this command to find disk usage in my shell script</p> <pre><code>df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}' </code></pre> <p>I want to use this command in my python script</p> <pre><code>ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'") </code></pre> <p>but unable to handle string literals.</p> <p>I tried replacing \ with \\ as suggested <a href="http://stackoverflow.com/questions/2102452/why-this-dos-command-does-not-work-inside-python">here</a> </p> <p>Can someone throw light on thiS?</p> <p>This is the error i am getting </p> <pre><code>ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'") ^ SyntaxError: invalid syntax </code></pre>
0
2016-09-30T10:36:56Z
39,789,574
<p>You are not escaping your double quotes and they are terminating the string early:</p> <pre><code>ssh.exec_command("df -h | awk '$NF==\"/\"{printf \"Disk Usage: %d/%dGB (%s)\\n\", $3,$2,$5}'") </code></pre>
1
2016-09-30T10:39:17Z
[ "python", "shell" ]
unable to use cmd command in python
39,789,535
<p>I am using this command to find disk usage in my shell script</p> <pre><code>df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}' </code></pre> <p>I want to use this command in my python script</p> <pre><code>ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'") </code></pre> <p>but unable to handle string literals.</p> <p>I tried replacing \ with \\ as suggested <a href="http://stackoverflow.com/questions/2102452/why-this-dos-command-does-not-work-inside-python">here</a> </p> <p>Can someone throw light on thiS?</p> <p>This is the error i am getting </p> <pre><code>ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'") ^ SyntaxError: invalid syntax </code></pre>
0
2016-09-30T10:36:56Z
39,790,211
<p>You can try the following using <a href="https://docs.python.org/2/library/shlex.html" rel="nofollow">shlex</a> and <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess</a> to prepare your command string.</p> <pre><code>from subprocess import list2cmdline import shlex cmd = list2cmdline(shlex.split("""df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'""")) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd) </code></pre>
-1
2016-09-30T11:13:43Z
[ "python", "shell" ]
Progressbar to show amount of music played
39,789,577
<p>Suppose I use <code>mp3play</code> module to play mp3 files, and using <code>ttk.Progressbar</code>, I want to show the amount(duration) of music played. Is there any code to achieve it? </p> <p>I also want a timer a to show the duration of music played.</p> <pre><code>import ttk import mp3play self.music = mp3play.load('filename') self.fr=ttk.Frame() self.fr.pack(expand=True, fill=BOTH, side=TOP) self.seek=ttk.Progressbar(self.fr, orient='horizontal', mode='determinate', length=500) self.seek.place(x=50, y=325) self.seek.start() </code></pre>
1
2016-09-30T10:39:30Z
39,789,945
<p>Looking at the code of <code>mp3play</code>module, <code>mp3play.load()</code> returns an <code>AudioClip</code> object. This object has the methods <code>seconds()</code> and <code>milliseconds()</code> that provide the length of the clip in seconds or milliseconds respectively.</p> <p>You can save the time when you started playing and compare it to the current time and the total length of the clip to determine the status of the progressbar.</p> <pre><code># assuming time would me measured in milliseconds start = time() while playing: # progress measured in percentages progress = 100 * (time() - start)/ clip.milliseconds() </code></pre>
3
2016-09-30T10:58:56Z
[ "python", "python-2.7", "tkinter" ]
Progressbar to show amount of music played
39,789,577
<p>Suppose I use <code>mp3play</code> module to play mp3 files, and using <code>ttk.Progressbar</code>, I want to show the amount(duration) of music played. Is there any code to achieve it? </p> <p>I also want a timer a to show the duration of music played.</p> <pre><code>import ttk import mp3play self.music = mp3play.load('filename') self.fr=ttk.Frame() self.fr.pack(expand=True, fill=BOTH, side=TOP) self.seek=ttk.Progressbar(self.fr, orient='horizontal', mode='determinate', length=500) self.seek.place(x=50, y=325) self.seek.start() </code></pre>
1
2016-09-30T10:39:30Z
39,790,166
<p>It appears that the mp3play module <a href="https://github.com/michaelgundlach/mp3play/blob/master/mp3play/windows.py" rel="nofollow">uses</a> the Windows <a href="https://msdn.microsoft.com/en-us/library/vs/alm/dd743606(v=vs.85).aspx" rel="nofollow">winmm</a> library. Specifically, it uses function <a href="https://msdn.microsoft.com/en-us/library/vs/alm/dd757161(v=vs.85).aspx" rel="nofollow"><code>mciSendString</code></a> to <a href="https://msdn.microsoft.com/en-us/library/vs/alm/dd743572(v=vs.85).aspx" rel="nofollow">control</a> the multimedia system.</p> <p>One option to achieve what you want would be to use the <a href="https://msdn.microsoft.com/en-us/library/vs/alm/dd798683%28v=vs.85%29.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow"><code>status</code></a> command to periodically retrieve the current playback position and display it as you like.</p> <p>It would seem most appropriate to modify both versions of the <code>AudioClip</code> class from the mp3play library.</p> <hr> <h1>Modifying mp3play Library</h1> <h2>Class AudioClip in windows.py</h2> <p>First, on line <a href="https://github.com/michaelgundlach/mp3play/blob/master/mp3play/windows.py#L59" rel="nofollow">59 of windows.py</a> you can see a function that uses the status command</p> <pre><code> def _mode(self): err, buf = self._mci.directsend('status %s mode' % self._alias) return buf </code></pre> <p>We can write a new function based on this example, which will get the current playback position:</p> <pre><code> def current_position(self): err, buf = self._mci.directsend('status %s position' % self._alias) return buf </code></pre> <p>This function will return a string encoding a number representing the current position in milliseconds.</p> <h2>Class AudioClip in <strong>init</strong>.py</h2> <p>The next step is to modify <code>AudioClip</code> class on line <a href="https://github.com/michaelgundlach/mp3play/blob/master/mp3play/__init__.py#L12" rel="nofollow">12 of __init__py</a>, adding the following function:</p> <pre><code> def current_position(self): """Get current position of clip in milliseconds.""" return int(self._clip.current_position()) </code></pre> <hr> <h1>CLI Example</h1> <p>Now we can test it with a simple script:</p> <pre><code>import time import mp3play clip = mp3play.load(r'test.mp3') clip.play() for i in range(5): print "Position: %d / %d" % (clip.current_position(), clip.milliseconds()) time.sleep(1) clip.stop() </code></pre> <p>The console output looks as follows:</p> <pre><code>&gt;python test.py Position: 0 / 174392 Position: 905 / 174392 Position: 1906 / 174392 Position: 2906 / 174392 Position: 3907 / 174392 </code></pre> <hr> <h1>GUI Example</h1> <pre><code>import tkinter as tk from tkinter import ttk import mp3play # ================================================================================ def format_duration(ms): total_s = ms / 1000 total_min = total_s / 60 remain_s = total_s % 60 return "%0d:%02d" % (total_min, remain_s) # ================================================================================ class SimplePlayer(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # Variables we use to dynamically update the text of the labels self.music_title = tk.StringVar() self.music_progress = tk.StringVar() self.fr=ttk.Frame() self.fr.pack(expand=True, fill=tk.BOTH, side=tk.TOP) # Label to display the song title self.title_lbl = ttk.Label(self.fr, textvariable = self.music_title) self.title_lbl.pack() # Playback progress bar self.progress_bar = ttk.Progressbar(self.fr, orient='horizontal', mode='determinate', length=500) self.progress_bar.pack() # Shows the progress numerically self.progress_lbl = ttk.Label(self.fr, textvariable = self.music_progress) self.progress_lbl.pack() def start(self, music_file): self.music = mp3play.load(music_file) # Update the title self.music_title.set(music_file) # Start playback self.music.play() # Start periodically updating the progress bar and progress label self.update_progress() def update_progress(self): pos_ms = self.music.current_position() total_ms = self.music.milliseconds() progress_percent = pos_ms / float(total_ms) * 100 # Update the label label_text = "%s / %s (%0.2f %%)" % (format_duration(pos_ms), format_duration(total_ms), progress_percent) self.music_progress.set(label_text) # Update the progress bar self.progress_bar["value"] = progress_percent # Schedule next update in 100ms self.after(100, self.update_progress) # ================================================================================ app = SimplePlayer() app.start('test.mp3') app.mainloop() </code></pre> <p>Screenshot: </p> <p><img src="http://i.imgur.com/J8rmTgx.png" alt="Screenshot of running GUI example"></p>
1
2016-09-30T11:10:55Z
[ "python", "python-2.7", "tkinter" ]
How to make Django generic views accessible to logged in users only?
39,789,588
<p>I've implemented the social-auth for Google for users to log in. I cannot understand how to restrict the visitors from accessing the generic views like UpdateView, ListView or CreateView, if they are not logged in with the social-auth system. Here is the code.</p> <p><strong><em>views.py</em></strong></p> <pre><code>class AchievementCreate(CreateView): form_class = AchievementForm2 model = Achievements def form_valid(self, form): achieves = form.save(commit=False) achieves.resume = Resume.objects.get(pk=2) return super(AchievementCreate, self).form_valid(form) def home(request): #logout(request) uname="" if request.method == 'POST' and 'submit' in request.POST: submit = request.POST['submit'] if submit=="sign-out": logout(request) if '_auth_user_id' in request.session: uname=sm.UserSocialAuth.objects.get( user_id=int(request.session['_auth_user_id']) ).user request.session['uname']=str(uname) return render(request,'cv/home.html',{'uname': uname}) </code></pre> <p><strong><em>home.html</em></strong></p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;Home&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" action="{% url 'cv:home' %}"&gt;{% csrf_token %} {% if uname %} Helo, {{uname}}&lt;br&gt; The user already signed in. He may need to sign out&lt;br&gt; &lt;input type="submit" name="submit" value="sign-out"&gt; {% else %} Please sign-in&lt;br&gt; &lt;a href="{% url 'social:begin' 'google-oauth2' %}"&gt;Google login&lt;/a&gt; {% endif %} &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong><em>urls.py</em></strong></p> <pre><code>urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^achievements/(?P&lt;pk&gt;[0-9]+)/delete/$', views.AchievementDelete.as_view(), name='achievement-delete'), url(r'^achievements/(?P&lt;pk&gt;[0-9]+)/$', views.AchievementUpdate.as_view(), name='achievement-update'), url(r'^achievements/add/$', login_required(views.AchievementCreate.as_view()), name='achievement-add'), url(r'^home/$', views.home, name='home'),] </code></pre> <p>I want the "AchievementCreate" class to be accessible only if the user has logged in. But I don't understand how. Is it possible to use sessions? How, in this case?</p>
0
2016-09-30T10:40:29Z
39,789,819
<p>You need to import the login_required decorator and put @login_reqired infront of the view. This view will than only be accesable when logged in.</p> <p>Example:</p> <pre><code> from django.contrib.auth.decorators import login_required @login_required #put your view here </code></pre>
0
2016-09-30T10:51:43Z
[ "python", "django", "django-socialauth" ]
How to make Django generic views accessible to logged in users only?
39,789,588
<p>I've implemented the social-auth for Google for users to log in. I cannot understand how to restrict the visitors from accessing the generic views like UpdateView, ListView or CreateView, if they are not logged in with the social-auth system. Here is the code.</p> <p><strong><em>views.py</em></strong></p> <pre><code>class AchievementCreate(CreateView): form_class = AchievementForm2 model = Achievements def form_valid(self, form): achieves = form.save(commit=False) achieves.resume = Resume.objects.get(pk=2) return super(AchievementCreate, self).form_valid(form) def home(request): #logout(request) uname="" if request.method == 'POST' and 'submit' in request.POST: submit = request.POST['submit'] if submit=="sign-out": logout(request) if '_auth_user_id' in request.session: uname=sm.UserSocialAuth.objects.get( user_id=int(request.session['_auth_user_id']) ).user request.session['uname']=str(uname) return render(request,'cv/home.html',{'uname': uname}) </code></pre> <p><strong><em>home.html</em></strong></p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;Home&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" action="{% url 'cv:home' %}"&gt;{% csrf_token %} {% if uname %} Helo, {{uname}}&lt;br&gt; The user already signed in. He may need to sign out&lt;br&gt; &lt;input type="submit" name="submit" value="sign-out"&gt; {% else %} Please sign-in&lt;br&gt; &lt;a href="{% url 'social:begin' 'google-oauth2' %}"&gt;Google login&lt;/a&gt; {% endif %} &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong><em>urls.py</em></strong></p> <pre><code>urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^achievements/(?P&lt;pk&gt;[0-9]+)/delete/$', views.AchievementDelete.as_view(), name='achievement-delete'), url(r'^achievements/(?P&lt;pk&gt;[0-9]+)/$', views.AchievementUpdate.as_view(), name='achievement-update'), url(r'^achievements/add/$', login_required(views.AchievementCreate.as_view()), name='achievement-add'), url(r'^home/$', views.home, name='home'),] </code></pre> <p>I want the "AchievementCreate" class to be accessible only if the user has logged in. But I don't understand how. Is it possible to use sessions? How, in this case?</p>
0
2016-09-30T10:40:29Z
39,790,900
<p>We need to write mixins to check whether the user is logged in or not.</p> <p>Django 1.9 has introduced a LoginRequiredMixin:</p> <pre><code>from django.contrib.auth.mixins import LoginRequiredMixin class UserProfile(LoginRequiredMixin, View): login_url = '/login/' </code></pre> <p>The following code is a custom mixin, which will check user is active or inactive. If the user is inactive, it will logout the session. We need to write mixins in a separate file like mixins.py, import the mixins in views</p> <pre><code>class UserMixin(object): def dispatch(self, request, *args, **kwargs): user = self.request.user if user: if user.is_active: return super(UserMixin, self).dispatch(request, *args, **kwargs) else: logout(self.request) return HttpResponseRedirect(reverse('cv:home')) </code></pre> <p>In Views.py </p> <pre><code>from mixins.py import UserMixin class UserEdit(UserMixin, View): model = UserProfile template_name = "dashboard/edit_user.html" </code></pre>
0
2016-09-30T11:52:15Z
[ "python", "django", "django-socialauth" ]
How to make Django generic views accessible to logged in users only?
39,789,588
<p>I've implemented the social-auth for Google for users to log in. I cannot understand how to restrict the visitors from accessing the generic views like UpdateView, ListView or CreateView, if they are not logged in with the social-auth system. Here is the code.</p> <p><strong><em>views.py</em></strong></p> <pre><code>class AchievementCreate(CreateView): form_class = AchievementForm2 model = Achievements def form_valid(self, form): achieves = form.save(commit=False) achieves.resume = Resume.objects.get(pk=2) return super(AchievementCreate, self).form_valid(form) def home(request): #logout(request) uname="" if request.method == 'POST' and 'submit' in request.POST: submit = request.POST['submit'] if submit=="sign-out": logout(request) if '_auth_user_id' in request.session: uname=sm.UserSocialAuth.objects.get( user_id=int(request.session['_auth_user_id']) ).user request.session['uname']=str(uname) return render(request,'cv/home.html',{'uname': uname}) </code></pre> <p><strong><em>home.html</em></strong></p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;Home&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" action="{% url 'cv:home' %}"&gt;{% csrf_token %} {% if uname %} Helo, {{uname}}&lt;br&gt; The user already signed in. He may need to sign out&lt;br&gt; &lt;input type="submit" name="submit" value="sign-out"&gt; {% else %} Please sign-in&lt;br&gt; &lt;a href="{% url 'social:begin' 'google-oauth2' %}"&gt;Google login&lt;/a&gt; {% endif %} &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong><em>urls.py</em></strong></p> <pre><code>urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^achievements/(?P&lt;pk&gt;[0-9]+)/delete/$', views.AchievementDelete.as_view(), name='achievement-delete'), url(r'^achievements/(?P&lt;pk&gt;[0-9]+)/$', views.AchievementUpdate.as_view(), name='achievement-update'), url(r'^achievements/add/$', login_required(views.AchievementCreate.as_view()), name='achievement-add'), url(r'^home/$', views.home, name='home'),] </code></pre> <p>I want the "AchievementCreate" class to be accessible only if the user has logged in. But I don't understand how. Is it possible to use sessions? How, in this case?</p>
0
2016-09-30T10:40:29Z
39,795,966
<p>So you are using 'social-auth' for your login system. In your case, you will have to use a custom function. I'm assuming you can access the logged in user by referring to: <code>request.SESSION</code></p> <p>If so, then you can override the dispatch method of your CreateView:</p> <pre><code>class AchievementCreate(CreateView): ..... ..... def dispatch(self, request, *args, **kwargs): user = request.session['_auth_user_id'] # handle authentication </code></pre>
0
2016-09-30T16:22:29Z
[ "python", "django", "django-socialauth" ]
Writing a list into the file by using Python
39,789,660
<p>I am trying to write a list into the file. I used:</p> <pre><code>studentFile = open("students1.txt", "w") for ele in studentList: studentFile.write(str(ele) + "\n") studentFile.close() </code></pre> <p>As a result, the output was:</p> <pre><code>['11609036', 'MIT', 'NE'] ['11611262', 'MIT', 'MD'] ['11613498', 'BIS', 'SA'] </code></pre> <p>instead of:</p> <pre><code>11609036 MIT NE 11611262 MIT MD 11613498 BIS SA </code></pre> <p>How can I fix it?</p>
0
2016-09-30T10:44:16Z
39,789,691
<p>Use <code>.join</code> to convert each <em>sublist</em> into a string: </p> <pre><code>studentFile.write(' '.join(ele) + "\n") </code></pre> <p>You may find the <a href="https://docs.python.org/3/whatsnew/2.6.html#pep-343-the-with-statement" rel="nofollow"><code>with</code></a> statement which creates a <em>context manager</em> a more cleaner alternative for opening, writing to, and closing files:</p> <pre><code>with open("students1.txt", "w") as student_file: for ele in studentList: student_file.write(' '.join(ele) + "\n") </code></pre> <p>The space in between the items can be increased by modifying <code>' '</code> or using tab spacing as in <code>'\t'.join</code>.</p>
4
2016-09-30T10:45:45Z
[ "python" ]
Writing a list into the file by using Python
39,789,660
<p>I am trying to write a list into the file. I used:</p> <pre><code>studentFile = open("students1.txt", "w") for ele in studentList: studentFile.write(str(ele) + "\n") studentFile.close() </code></pre> <p>As a result, the output was:</p> <pre><code>['11609036', 'MIT', 'NE'] ['11611262', 'MIT', 'MD'] ['11613498', 'BIS', 'SA'] </code></pre> <p>instead of:</p> <pre><code>11609036 MIT NE 11611262 MIT MD 11613498 BIS SA </code></pre> <p>How can I fix it?</p>
0
2016-09-30T10:44:16Z
39,789,843
<p>How does your <code>studentList</code> list look like? I suspect its a nested list and you need another loop to pick individual elements.</p> <pre><code>studentList = [['11609036', 'MIT', 'NE'], ['11611262', 'MIT', 'MD'], ['11613498', 'BIS', 'SA']] studentFile = open("students1.txt", "w") for student in studentList: for ele in student: studentFile.write(str(ele) + "\t") studentFile.write("\n") studentFile.close() </code></pre>
0
2016-09-30T10:53:06Z
[ "python" ]
Why collections.Callable provides __contains__(), __hash__(), __len__() and __call__()
39,789,876
<p>Why does the <a href="https://docs.python.org/2.7/library/collections.html?#collections.Callable" rel="nofollow">documentation</a> says:</p> <blockquote> <p>class collections.Callable</p> <p>ABCs for classes that provide respectively the methods <strong>contains</strong>(), <strong>hash</strong>(), <strong>len</strong>(), and <strong>call</strong>().</p> </blockquote> <p>And not only <code>__call__()</code> ?</p> <p>What is the role of <code>__contains__()</code>, <code>__hash__()</code>, <code>__len__()</code> for callable object?</p> <p>For instance, do I need to make my classes hashable?</p>
-1
2016-09-30T10:55:36Z
39,789,924
<p>You misunderstand what that text says. The documentation covers <strong>four</strong> ABCs:</p> <pre><code>class collections.Container class collections.Hashable class collections.Sized class collections.Callable </code></pre> <p>The <a href="http://english.stackexchange.com/questions/24525/what-does-the-word-respectively-mean-in-software-development">grammar construct <em>respectively</em></a> in the sentence <em>ABCs for classes that provide respectively the methods</em> attaches a separate method to each of the four classes here, in order.</p> <p>So <code>Container</code> provides <code>__contains__()</code>, <code>Hashable</code> covers <code>__hash__()</code>, <code>Sized</code> covers <code>__len__()</code> and <code>Callable</code> covers <code>__call__()</code>.</p> <p>In other words, <code>Callable</code> only provides a <code>__call__()</code> method, not any of the other 3 methods.</p>
1
2016-09-30T10:57:48Z
[ "python", "callable" ]
How to handle alerts with Python?
39,789,983
<p>I wuold like to handle alerts with Python. What I wuold like to do is:</p> <ul> <li>open a url</li> <li>submit a form or click some links</li> <li>check if an alert occurs in the new page</li> </ul> <p>I made this with Javascript using PhantomJS, but I would made even with Python. Here is the javascript code:</p> <p>file test.js:</p> <pre><code>var webPage = require('webpage'); var page = webPage.create(); var url = 'http://localhost:8001/index.html' page.onConsoleMessage = function (msg) { console.log(msg); } page.open(url, function (status) { page.evaluate(function () { document.getElementById('myButton').click() }); page.onConsoleMessage = function (msg) { console.log(msg); } page.onAlert = function (msg) { console.log('ALERT: ' + msg); }; setTimeout(function () { page.evaluate(function () { console.log(document.documentElement.innerHTML) }); phantom.exit(); }, 1000); }); </code></pre> <p>file index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; &lt;title&gt;&lt;/title&gt; &lt;meta charset="utf-8" /&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;input id="username" name="username" /&gt; &lt;button id="myButton" type="button" value="Page2"&gt;Go to Page2&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; &lt;script&gt; document.getElementById("myButton").onclick = function () { location.href = "page2.html"; }; &lt;/script&gt; </code></pre> <p>file page2.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; &lt;title&gt;&lt;/title&gt; &lt;meta charset="utf-8" /&gt; &lt;/head&gt; &lt;body onload="alert('hello')"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This works; it detects the alert on page2.html. Now I made this python script:</p> <p>test.py</p> <pre><code>import requests from test import BasicTest from selenium import webdriver from bs4 import BeautifulSoup url = 'http://localhost:8001/index.html' def main(): #browser = webdriver.Firefox() browser = webdriver.PhantomJS() browser.get(url) html_source = browser.page_source #browser.quit() soup = BeautifulSoup(html_source, "html.parser") soup.prettify() request = requests.get('http://localhost:8001/page2.html') print request.text #Handle Alert if __name__ == "__main__": main(); </code></pre> <p>Now, how can I check if an alert occur on page2.html with Python? First I open the page index.html, then page2.html. I'm at the beginning, so any suggestions will be appreciate.</p> <p>p.s. I also tested webdriver.Firefox() but it is extremely slow. Also i read this question : <a href="http://stackoverflow.com/questions/19003003/check-if-any-alert-exists-using-selenium-with-python">Check if any alert exists using selenium with python</a></p> <p>but it doesn't work (below is the same previous script plus the solution suggested in the answer).</p> <pre><code>..... from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException .... def main(): ..... #Handle Alert try: WebDriverWait(browser, 3).until(EC.alert_is_present(), 'Timed out waiting for PA creation ' + 'confirmation popup to appear.') alert = browser.switch_to.alert() alert.accept() print "alert accepted" except TimeoutException: print "no alert" if __name__ == "__main__": main(); </code></pre> <p>I get the error : "selenium.common.exceptions.WebDriverException: Message: Invalid Command Method.."</p>
1
2016-09-30T11:00:59Z
39,791,519
<p>PhantomJS uses GhostDriver to implement the WebDriver Wire Protocol, which is how it works as a headless browser within Selenium. </p> <p>Unfortunately, GhostDriver does not currently support Alerts. Although it looks like they would like help to implement the features:</p> <p><a href="https://github.com/detro/ghostdriver/issues/20" rel="nofollow">https://github.com/detro/ghostdriver/issues/20</a></p> <p>You could possibly switch to the javascript version of PhantomJS or use the Firefox driver within Selenium.</p> <pre><code>from selenium import webdriver from selenium.common.exceptions import NoAlertPresentException if __name__ == '__main__': # Switch to this driver and switch_to_alert will fail. # driver = webdriver.PhantomJS('&lt;Path to Phantom&gt;') driver = webdriver.Firefox() driver.set_window_size(1400, 1000) driver.get('http://localhost:8001/page2.html') try: driver.switch_to.alert.accept() print('Alarm! ALARM!') except NoAlertPresentException: print('*crickets*') </code></pre>
0
2016-09-30T12:26:20Z
[ "python", "selenium", "selenium-webdriver", "phantomjs", "alert" ]
Pandas dataframe comparison hangs without error message
39,789,990
<p>This is my first pandas attempt, so I was wondering what is the problem. I am trying to compare two dataframe of about 30.000 rows each. My first intuition led me to iterate both dataframes, so for every entry in the df1, we iterate all the rows in the df2 to see if it´s there. </p> <p>Maybe is not necessary at all and there are easier alternatives. Here is what I did. The problem is, it simply hangs without outputting any error message, but I cannot identify what is making it hang... </p> <pre><code>import pandas as pd dfOld = pd.read_excel("oldfile.xlsx", header=0) dfNew = pd.read_excel("newfile.xlsx", header=0) columns = ["NAME","ADDRESS","STATUS","DATE"] result = pd.DataFrame(columns=columns) for index, rowOld in dfOld.iterrows(): for index, rowNew in dfNew.iterrows(): if rowOld.all() != rowNew.all(): result.loc[len(result)] = rowOld.all() writer = pd.ExcelWriter('Deletions.xlsx', engine='xlsxwriter') result.to_excel(writer, sheet_name='Deleted') writer.save() </code></pre> <p>Sample data for each dataframe:</p> <pre><code>$1 &amp; UP STORE CORP.142A | N FRANKLIN ST | 409 408 | 31/07/2014 $1 store | 110 n martin ave | 408 | 07/01/2015 0713, LLC | 1412 N. County Road West | 405 408 413 | 16/07/2015 1 2 3 MONEY EXCHANGE LLC | 588 N MAIN ST | 405 409 408 | 22/05/2015 $1 store premium | 110 n martin ave | 408 | 07/01/2015 0713, LLC | 1412 N. County Road West | 405 408 413 | 16/07/2015 1 2 3 MONEY EXCHANGE LLC | 588 N MAIN ST | 405 409 408 | 22/05/2015 1145 Parsons Inc | 1145 Parsons Ave | 405 408 | 19/11/2013 </code></pre> <p>The desired output is that the dataframe <code>results</code> gets populated with the rows from <code>dfOld</code> that do not exist in <code>dfNew</code>. So, the new <code>results</code> dataframe would be comprised of:</p> <pre><code>$1 &amp; UP STORE CORP.142A | N FRANKLIN ST | 409 408 | 31/07/2014 $1 store | 110 n martin ave | 408 | 07/01/2015 </code></pre> <p>The problem is that it doesn't work with a large amount (30.000 entries per dataframe), so even if it can work with a smaller sample, I wonder if this is the way to proceed with that many entries. </p>
2
2016-09-30T11:01:25Z
39,790,507
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with parameter <code>indicator=True</code> and then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>df = pd.merge(dfOld, dfNew, how='outer', indicator=True) print (df) NAME ADDRESS STATUS \ 0 $1 &amp; UP STORE CORP.142A N FRANKLIN ST 409 408 1 $1 store 110 n martin ave 408 2 0713, LLC 1412 N. County Road West 405 408 413 3 1 2 3 MONEY EXCHANGE LLC 588 N MAIN ST 405 409 408 4 $1 store premium 110 n martin ave 408 5 1145 Parsons Inc 1145 Parsons Ave 405 408 DATE _merge 0 31/07/2014 left_only 1 07/01/2015 left_only 2 16/07/2015 both 3 22/05/2015 both 4 07/01/2015 right_only 5 19/11/2013 right_only print (df[df._merge == 'left_only']) NAME ADDRESS STATUS DATE _merge 0 $1 &amp; UP STORE CORP.142A N FRANKLIN ST 409 408 31/07/2014 left_only 1 $1 store 110 n martin ave 408 07/01/2015 left_only </code></pre> <p>Last delete helper column <code>_merge</code>:</p> <pre><code>print (df[df._merge == 'left_only'].drop('_merge', axis=1)) NAME ADDRESS STATUS DATE 0 $1 &amp; UP STORE CORP.142A N FRANKLIN ST 409 408 31/07/2014 1 $1 store 110 n martin ave 408 07/01/2015 </code></pre>
2
2016-09-30T11:29:15Z
[ "python", "pandas" ]