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
listlengths
1
5
Visualising a numpy array/matrix
38,669,230
<p>I have a function that returns a list. I think I use np.append to add this list as a new line in an array, my intention is as follow:</p> <pre><code>list = 4 5 6 b = 1 2 3 b = np.append(b, list) </code></pre> <p>output;</p> <pre><code>1 2 3 4 5 6 </code></pre> <p>This isn't the code I use (there's a lot of messing around in between). But the output I get is this:</p> <pre><code>2016-06-01 PRINT [ 99.86 99.928 99.9 99.875 99.8 89.7933 97.60018333 98.903 99.928 0.2801201 98.95 98.93 98.87 98.94 99.05 89.097 97.6712 98.87 99.59 0.23538903 99.711 99.732 99.725 99.724 99.769 89.777 98.12053333 99.68 99.88 0.30333219 99.805 99.79 99.743 99.71 99.69 89.7728 98.06653333 99.617 99.82 0.28981292 99.882 99.879 99.865 99.84 99.9 89.9206 98.29823333 99.82 100.08 0.31420778] </code></pre> <p>Is this a 10 column by 5 row array/matrix or is this a 50 column/row array? I feel like I'm missing something here - or is it just that the output doesn't really show the shape of the array?</p>
2
2016-07-30T00:29:36Z
38,669,384
<p>True list append:</p> <pre><code>In [701]: alist = [4,5,6] In [702]: b=[1,2,3] In [703]: b.append(alist) In [704]: b Out[704]: [1, 2, 3, [4, 5, 6]] </code></pre> <p>bad array operation:</p> <pre><code>In [705]: anArray=np.array([4,5,6]) In [706]: b=np.array([1,2,3]) In [707]: b=np.append(b,anArray) In [708]: b Out[708]: array([1, 2, 3, 4, 5, 6]) In [709]: b.shape Out[709]: (6,) </code></pre> <p>Here I just concatenated <code>anArray</code> onto <code>b</code>, making a longer array.</p> <p>I've said this before - <code>np.append</code> is not a good function. It looks too much like the list <code>append</code>, and people end up misusing it. Either they miss the fact that it returns a new array, as opposed to modifying in-place. Or they use it repeatedly.</p> <p>Here's the preferred way of collecting lists or arrays and joining them into one </p> <pre><code>In [710]: alist = [] In [711]: b=np.array([1,2,3]) # could be b=[1,2,3] In [712]: alist.append(b) In [713]: b=np.array([4,5,6]) # b=[4,5,6] In [714]: alist.append(b) In [715]: alist Out[715]: [array([1, 2, 3]), array([4, 5, 6])] In [716]: np.array(alist) Out[716]: array([[1, 2, 3], [4, 5, 6]]) In [717]: _.shape Out[717]: (2, 3) </code></pre> <p>The result is a 2d array. List append is much faster than array <code>append</code> (which is real array concatenate). Build the list and then make the array.</p> <p>The most common way of defining a 2d array is with a list of lists:</p> <pre><code>In [718]: np.array([[1,2,3],[4,5,6]]) Out[718]: array([[1, 2, 3], [4, 5, 6]]) </code></pre> <p><code>np.concatenate</code> is another option for joining arrays and lists. If gives more control over how they are joined, but you have to pay attention to the dimensions of the inputs (you should pay attention to those anyways).</p> <p>There are several 'stack' functions which streamline the dimension handling a bit, <code>stack</code>, <code>hstack</code>, <code>vstack</code> and yes, <code>append</code>. It's worth looking at their code.</p>
3
2016-07-30T01:00:57Z
[ "python", "arrays", "numpy" ]
Visualising a numpy array/matrix
38,669,230
<p>I have a function that returns a list. I think I use np.append to add this list as a new line in an array, my intention is as follow:</p> <pre><code>list = 4 5 6 b = 1 2 3 b = np.append(b, list) </code></pre> <p>output;</p> <pre><code>1 2 3 4 5 6 </code></pre> <p>This isn't the code I use (there's a lot of messing around in between). But the output I get is this:</p> <pre><code>2016-06-01 PRINT [ 99.86 99.928 99.9 99.875 99.8 89.7933 97.60018333 98.903 99.928 0.2801201 98.95 98.93 98.87 98.94 99.05 89.097 97.6712 98.87 99.59 0.23538903 99.711 99.732 99.725 99.724 99.769 89.777 98.12053333 99.68 99.88 0.30333219 99.805 99.79 99.743 99.71 99.69 89.7728 98.06653333 99.617 99.82 0.28981292 99.882 99.879 99.865 99.84 99.9 89.9206 98.29823333 99.82 100.08 0.31420778] </code></pre> <p>Is this a 10 column by 5 row array/matrix or is this a 50 column/row array? I feel like I'm missing something here - or is it just that the output doesn't really show the shape of the array?</p>
2
2016-07-30T00:29:36Z
38,669,481
<p>you should use hstack or vstack</p> <pre><code>import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) np.vstack((a,b)) </code></pre> <p>gives</p> <pre><code>array([[1, 2, 3], [4, 5, 6]]) </code></pre> <p>or </p> <pre><code>np.hstack((a,b)) </code></pre> <p>gives</p> <pre><code>array([1, 2, 3, 4, 5, 6]) </code></pre>
1
2016-07-30T01:19:00Z
[ "python", "arrays", "numpy" ]
Why Do I need Range(Len)) for a nested if?
38,669,242
<p>This works as is but when I didn't have range(len..)) in and do <code>for i in arr</code> and <code>for j in arr</code>, I get <code>IndexError: list index out of range</code> on the if statement. Why is this?</p> <pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4] mostFrq = 0 mostFrqAmount = 0 for i in range(len(arr)): amountOfCurrent = 0 # now look at temp element for j in range(len(arr)): if (arr[j] == arr[i]): amountOfCurrent = amountOfCurrent + 1 if (amountOfCurrent &gt; mostFrqAmount): mostFrqAmount = amountOfCurrent mostFrq = arr[i] print(mostFrq) print(mostFrqAmount) </code></pre>
0
2016-07-30T00:31:13Z
38,669,266
<p>When you're iterating over a list, you get its elements. Since you're then accessing list elements at the index of that element, it won't work when it's out of bounds (and wouldn't do what you expected anyways).</p> <p>Instead, just use the items you're provided by the loop:</p> <pre><code>mostFrq = 0 mostFrqAmount = 0 for i in arr: amountOfCurrent = 0 # now look at temp element for j in arr: if (j == i): amountOfCurrent += 1 if (amountOfCurrent &gt; mostFrqAmount): mostFrqAmount = amountOfCurrent mostFrq = i </code></pre>
0
2016-07-30T00:38:11Z
[ "python" ]
Why Do I need Range(Len)) for a nested if?
38,669,242
<p>This works as is but when I didn't have range(len..)) in and do <code>for i in arr</code> and <code>for j in arr</code>, I get <code>IndexError: list index out of range</code> on the if statement. Why is this?</p> <pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4] mostFrq = 0 mostFrqAmount = 0 for i in range(len(arr)): amountOfCurrent = 0 # now look at temp element for j in range(len(arr)): if (arr[j] == arr[i]): amountOfCurrent = amountOfCurrent + 1 if (amountOfCurrent &gt; mostFrqAmount): mostFrqAmount = amountOfCurrent mostFrq = arr[i] print(mostFrq) print(mostFrqAmount) </code></pre>
0
2016-07-30T00:31:13Z
38,669,268
<p>Not sure what you've tried. This should work the same way:</p> <pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4] mostFrq = 0 mostFrqAmount = 0 for i in arr: amountOfCurrent = 0 # now look at temp element for j in arr: if (j == i): amountOfCurrent = amountOfCurrent + 1 if (amountOfCurrent &gt; mostFrqAmount): mostFrqAmount = amountOfCurrent mostFrq = i print(mostFrq) print(mostFrqAmount) </code></pre>
0
2016-07-30T00:38:28Z
[ "python" ]
Why Do I need Range(Len)) for a nested if?
38,669,242
<p>This works as is but when I didn't have range(len..)) in and do <code>for i in arr</code> and <code>for j in arr</code>, I get <code>IndexError: list index out of range</code> on the if statement. Why is this?</p> <pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4] mostFrq = 0 mostFrqAmount = 0 for i in range(len(arr)): amountOfCurrent = 0 # now look at temp element for j in range(len(arr)): if (arr[j] == arr[i]): amountOfCurrent = amountOfCurrent + 1 if (amountOfCurrent &gt; mostFrqAmount): mostFrqAmount = amountOfCurrent mostFrq = arr[i] print(mostFrq) print(mostFrqAmount) </code></pre>
0
2016-07-30T00:31:13Z
38,669,298
<p>If you analyze what is going on with your code in the failing form, you have:</p> <pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4] mostFrq = 0 mostFrqAmount = 0 for i in arr: amountOfCurrent = 0 # now look at temp element for j in arr: if (arr[j] == arr[i]): amountOfCurrent = amountOfCurrent + 1 if (amountOfCurrent &gt; mostFrqAmount): mostFrqAmount = amountOfCurrent mostFrq = arr[i] print(mostFrq) print(mostFrqAmount) </code></pre> <p>Using the <code>for i in arr</code> form is returning an iterator that is handling the index information for you you, so your "i" is set to the values in your array.</p> <p>When you get to this line: <code>if (arr[j] == arr[i]):</code></p> <p>you end up with the variable substitution of <code>arr[45]</code></p> <p>Your index of the array only goes to 10, so, you have the error thrown.</p>
0
2016-07-30T00:44:41Z
[ "python" ]
Django Model Field from OneToOneField
38,669,253
<p>I have two models:</p> <pre><code>class FirstModel(models.Model): foo = models.IntegerField(default=0) class SecondModel(models.Model): bar = models.OneToOneField(FirstModel, on_delete=models.CASCADE, primary_key=True) </code></pre> <p>How do I make a variable <code>baz</code> that is from <code>FirstModel.foo</code>?</p> <p>I wish it was as easy as:</p> <pre><code>class SecondModel(models.Model): bar = models.OneToOneField(FirstModel, on_delete=models.CASCADE, primary_key=True) baz = bar.foo </code></pre> <p><strong>Ultimate Goal:</strong> To get <code>foo</code> from an instance of <code>SecondModel</code> like <code>second_model_instace.foo</code>.</p>
0
2016-07-30T00:34:08Z
38,669,426
<p>You can use <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.related_name" rel="nofollow"><code>related_name</code></a> in the linking model for backward reference: </p> <pre><code>class FirstModel(models.Model): foo = models.IntegerField(default=0) class SecondModel(models.Model): bar = models.OneToOneField(FirstModel, ,related_name'baz', on_delete=models.CASCADE, primary_key=True) </code></pre> <p>Now you can access as <code>first_model_intance.baz</code> if the link exists else you will get <code>DoesNotExsist</code> exception. The <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#onetoonefield" rel="nofollow">default</a> is:</p> <blockquote> <p>If you do not specify the related_name argument for the OneToOneField, Django will use the lower-case name of the current model as default value.</p> </blockquote> <p><strong>Update:</strong> If you want to get <code>second_model_instace.foo</code>, you do not even need <code>related_name</code> (backward reference). It is forward reference, which is already explicit. First get the first_model (via OneToOne Field) and then its attribute <code>foo</code>, that is:</p> <pre><code>second_model_instance.bar.foo </code></pre>
3
2016-07-30T01:09:11Z
[ "python", "django", "model" ]
Find if an item is in a lower dimension in a Python multidimensional array
38,669,300
<p>I have a three dimensional array, called grid. I now want to find whether an item is in the list of second dimensions containing the third dimension. For example, if I have this array:</p> <pre><code>grid = [ [ [ "0" , "1" ] , [ "2" , "1" ] ] , [ [ "3" , "0" ] ] ] </code></pre> <p>I want to find whether in all of the second dimensions of a first dimension (grid[0][all]) there is a specific item in a third dimension of that ([0][all][0]). I probably am not explaining this very well, but I don't know how else to say it. The all here and in the code below is meant to signify searching all of the second dimension.</p> <pre><code>for i in range 2: if "1" in grid[i][all][1]: #do something </code></pre> <p>So this code is meant to try and have me going through both the second dimensions of the array, and then, if a value is in one of those second dimensions third dimension's at a certain point, it will do something.</p>
0
2016-07-30T00:45:17Z
38,669,334
<p>Where you say <code>[all]</code>, you can use a for-loop to iterate through the elements.</p> <p>For example, <code>([0][all][0])</code></p> <pre><code>for y in grid[0]: if y[0] == "Your Value To Look For": print("I found the value") </code></pre>
1
2016-07-30T00:50:52Z
[ "python", "python-3.x" ]
group elements in an array and sum
38,669,307
<p>I have the following array</p> <pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1] </code></pre> <p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p> <pre><code>b = [1,0,2,0,3,0,1] </code></pre> <p>Any suggestions?</p>
-2
2016-07-30T00:46:00Z
38,669,372
<p>Maybe something like this:</p> <pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1] b = [] for i in range(0,len(a),3): b.append(sum(a[i:i+3])) print b </code></pre> <p>Output: </p> <pre><code>[1, 0, 2, 0, 3, 0, 1] </code></pre>
2
2016-07-30T00:59:26Z
[ "python", "arrays" ]
group elements in an array and sum
38,669,307
<p>I have the following array</p> <pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1] </code></pre> <p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p> <pre><code>b = [1,0,2,0,3,0,1] </code></pre> <p>Any suggestions?</p>
-2
2016-07-30T00:46:00Z
38,669,382
<p>Simply, most pythonicly would be the following</p> <pre><code>b = [sum(a[i:i+3]) for i in range(0, len(a), 3)] </code></pre> <p>where your input array is <code>a</code>.</p> <pre><code>&gt;&gt;&gt; a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1] &gt;&gt;&gt; b = [sum(a[i:i+3]) for i in range(0, len(a), 3)] &gt;&gt;&gt; b [1, 0, 2, 0, 3, 0, 1] </code></pre>
3
2016-07-30T01:00:42Z
[ "python", "arrays" ]
group elements in an array and sum
38,669,307
<p>I have the following array</p> <pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1] </code></pre> <p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p> <pre><code>b = [1,0,2,0,3,0,1] </code></pre> <p>Any suggestions?</p>
-2
2016-07-30T00:46:00Z
38,669,390
<p>You can split in chunk and sum:</p> <pre><code>step = 3 [sum(a[i:i+step]) for i in range(0, len(a),step)] [1, 0, 2, 0, 3, 0, 1] </code></pre> <p>If the length is not the multiple of step, last chunk might be smaller.</p>
2
2016-07-30T01:02:11Z
[ "python", "arrays" ]
group elements in an array and sum
38,669,307
<p>I have the following array</p> <pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1] </code></pre> <p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p> <pre><code>b = [1,0,2,0,3,0,1] </code></pre> <p>Any suggestions?</p>
-2
2016-07-30T00:46:00Z
38,669,471
<p>Another option using <code>groupby</code> from <code>itertools</code>:</p> <pre><code>from itertools import groupby [sum(v for _, v in g) for _, g in groupby(enumerate(a), key = lambda x: x[0]/3)] # [1, 0, 2, 0, 3, 0, 1] </code></pre> <p>Or another way to use <code>zip</code>:</p> <pre><code>[sum(v) for v in zip(a[::3], a[1::3], a[2::3])] # [1, 0, 2, 0, 3, 0, 1] </code></pre>
1
2016-07-30T01:17:06Z
[ "python", "arrays" ]
Python thread is not threading
38,669,374
<p>I've been looking all over google and can't seem to get this working. I'm trying to thread 2 functions, both of which are infinite loops.</p> <p>Looking at the extract below, it only starts the 1st thread and does not proceed to the next one in line.</p> <p>PS: When I swap the 2 threads around, then I have the same problem with the 2nd thread.</p> <pre><code>def syslog_service(): syslog_server = socketserver.UDPServer((syslog_host,syslog_port), Syslog_Server) syslog_server.serve_forever() def cleanup_old_logs_service(): # lock = threading.Lock() # threading.Thread.__init__(self) global syslog_retention_hours global RUNNING while RUNNING: # cleanup_old_logs_service.lock.acquire() cleanup.old_logs(syslog_retention_hours) # cleanup_old_logs_service.lock.release() time.sleep(10) if __name__ == "__main__": try: logger.info("Starting main thread") config() logger.info("Starting system testing") test() logger.info("Config loaded") thread1 = cleanup_old_logs_service() thread2 = syslog_service() thread1.start() logger.info("Syslog cleanup service running") thread2.start() logger.info("Syslog server running") </code></pre>
-2
2016-07-30T00:59:58Z
38,669,529
<p>The reason why only the first thread is executed is that you actually have ONLY one thread in your program. When you write <code>thread1 = cleanup_old_logs_service()</code> and <code>thread2 = syslog_service()</code>you are not creating new threads, but just assigning the return values of your functions to 2 different variables. For this reason, as soon as the program encounters <code>thread1</code>, it executes <code>cleanup_old_logs_service()</code> and gets stuck in an infinite loop.</p> <p>To create a new thread, I would import the <code>threading</code> module, create a new <code>threadObj</code> object and start the thread as follows:</p> <pre><code>import threading threadObj = threading.Thread(target=cleanup_old_logs_service) threadObj.start() </code></pre> <p>This way, the function <code>cleanup_old_logs_service()</code> will be executed in a new thread.</p>
1
2016-07-30T01:27:27Z
[ "python", "multithreading" ]
Python thread is not threading
38,669,374
<p>I've been looking all over google and can't seem to get this working. I'm trying to thread 2 functions, both of which are infinite loops.</p> <p>Looking at the extract below, it only starts the 1st thread and does not proceed to the next one in line.</p> <p>PS: When I swap the 2 threads around, then I have the same problem with the 2nd thread.</p> <pre><code>def syslog_service(): syslog_server = socketserver.UDPServer((syslog_host,syslog_port), Syslog_Server) syslog_server.serve_forever() def cleanup_old_logs_service(): # lock = threading.Lock() # threading.Thread.__init__(self) global syslog_retention_hours global RUNNING while RUNNING: # cleanup_old_logs_service.lock.acquire() cleanup.old_logs(syslog_retention_hours) # cleanup_old_logs_service.lock.release() time.sleep(10) if __name__ == "__main__": try: logger.info("Starting main thread") config() logger.info("Starting system testing") test() logger.info("Config loaded") thread1 = cleanup_old_logs_service() thread2 = syslog_service() thread1.start() logger.info("Syslog cleanup service running") thread2.start() logger.info("Syslog server running") </code></pre>
-2
2016-07-30T00:59:58Z
38,669,532
<p>By saying <code>thread1 = cleanup_old_logs_service()</code> you are actually executing the function <code>cleanup_old_logs_service</code> not saving a reference to a thread. You would have to say</p> <pre><code>import threading # If you have not already thread1 = threading.Thread(target=cleanup_old_logs_service) thread2 = threading.Thread(target=syslog_service) # Now you can start the thread thread1.start() logger.info("Syslog cleanup service running") thread2.start() logger.info("Syslog server running") </code></pre> <p>You can look at <a href="https://docs.python.org/3.5/library/threading.html" rel="nofollow">https://docs.python.org/3.5/library/threading.html</a> for documentation and <a href="https://pymotw.com/2/threading/" rel="nofollow">https://pymotw.com/2/threading/</a> for examples, because I believe you would need to use <code>locks</code> to manage access to your resources</p>
0
2016-07-30T01:27:38Z
[ "python", "multithreading" ]
How to choose only consecutive numbers from a list using python
38,669,527
<p>I did research and tried the code below. It almost works but I only want the consecutive numbers in the result. That would be [100,101,102]. I do not want the [75], [78], [109] in the result.</p> <pre><code>from operator import itemgetter from itertools import groupby data = [75, 78, 100, 101, 102, 109] for k, g in groupby(enumerate(data), lambda (i,x):i-x): print map(itemgetter(1), g) </code></pre> <p>The print out from above is:<br> [75]</p> <p>[78]</p> <p>[100, 101, 102]</p> <p>[109]</p> <p>What can I do to just get [100, 101, 102]?</p>
1
2016-07-30T01:26:47Z
38,669,554
<p><code>g</code> in your example is the iterable of elements (e.g., [75], or [100, 101, 102]). If you only want consecutive number<strong>s</strong>, it sounds like you're looking to print all <code>g</code>s where there are greater than one elements in <code>g</code> [Note, <code>g</code> is actually an iterable, but we can quickly convert it to a list with <code>list()</code> for a trivial amount of elements. We'll just need to save the contents, because an element can't be read <em>twice</em> from an iterator]</p> <p>Try wrapping the <code>print map(itemgetter(1), g)</code> in an if statement, such as:</p> <pre><code>x = list(g) if len(x) &gt; 1: print map(itemgetter(1), x) </code></pre>
2
2016-07-30T01:35:29Z
[ "python" ]
django 1.8.13 'User' object has no attribute 'user'
38,669,568
<p>I have a problem with the method Login(), the variable 'user' if it contains the user but that method fails. could help detect the problem.</p> <pre><code>from django.contrib.auth import authenticate, login def login(request): if request.user.is_authenticated(): return render(request, 'Default.html') mensaje = '' if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') User = authenticate(username=username, password=password) if User is not None: if User.is_active: login(User) return render(request, 'Default.html') else: return render(request, 'accounts/login.html', {'mensaje':mensaje}) else: return render(request, 'accounts/login.html', {'mensaje':mensaje}) </code></pre>
1
2016-07-30T01:39:00Z
38,669,579
<p>Also, according to the documentation, <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.login" rel="nofollow"><code>login()</code></a> function <em>expects 2 arguments</em> to be passed in - a request instance and a user model instance:</p> <pre><code>login(request, User) </code></pre>
0
2016-07-30T01:40:12Z
[ "python", "django", "user" ]
django 1.8.13 'User' object has no attribute 'user'
38,669,568
<p>I have a problem with the method Login(), the variable 'user' if it contains the user but that method fails. could help detect the problem.</p> <pre><code>from django.contrib.auth import authenticate, login def login(request): if request.user.is_authenticated(): return render(request, 'Default.html') mensaje = '' if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') User = authenticate(username=username, password=password) if User is not None: if User.is_active: login(User) return render(request, 'Default.html') else: return render(request, 'accounts/login.html', {'mensaje':mensaje}) else: return render(request, 'accounts/login.html', {'mensaje':mensaje}) </code></pre>
1
2016-07-30T01:39:00Z
38,669,625
<p>You are importing login from django.contrib.auth but look at your very next line of code.</p> <pre><code>from django.contrib.auth import authenticate, login def login(request): if request.user.is_authenticated(): return render(request, 'Default.html') </code></pre> <p>Yep, you are shadowing that login method with one for your own. The solution would be to rename your own funciton</p> <pre><code>def my_login(request): if request.user.is_authenticated(): return render(request, 'Default.html') </code></pre>
0
2016-07-30T01:49:13Z
[ "python", "django", "user" ]
Video Stream in GTK Window?
38,669,627
<p>Is there any way to embed a video stream (ffmpeg) in a GTK Window? Right now I am using Glade along with the Python GTK3 bindings, and I don't see any obvious methods provided by Glade.</p> <p>Perhaps a library or something part of GTK3 not exposed in Glade?</p>
0
2016-07-30T01:50:05Z
38,678,374
<p>The easiest way is by using GStreamer. They have a few docs over it: <a href="http://docs.gstreamer.com/display/GstSDK/Basic+tutorial+5%3A+GUI+toolkit+integration" rel="nofollow">http://docs.gstreamer.com/display/GstSDK/Basic+tutorial+5%3A+GUI+toolkit+integration</a></p> <p>Setting it in Glade directly probably won't be possible though.</p>
0
2016-07-30T20:50:45Z
[ "python", "user-interface", "video", "gtk3", "glade" ]
Tastypie using custom detail_uri_name, mismatched type error
38,669,717
<p>I am trying to override <code>get_bundle_detail_data</code></p> <pre><code>class MyResourse(ModelResource): foo = fields.CharField( attribute = 'modelA__variableOnModelA' ) def get_bundle_detail_data(self, bundle): return bundle.obj.foo class Meta: resource_name='resource' </code></pre> <p>With the line of code <code>foo = fields.CharField( attribute = 'modelA__variableOnModelA' )</code>, I am setting the variable <code>foo</code> on the resource <code>MyResource</code>, to a variable on <code>modelA</code> called <code>variableOnModelA</code>. This works nicly. </p> <p>But I am trying to make <code>variableOnModelA</code> be the identifier for <code>MyResource</code>, that way I can do <code>/api/v1/resource/bar/</code> to get the detailed <code>MyResource</code> with the variable <code>foo</code> set to <code>bar</code>. </p> <p>The problem I am having is the error: <code>Invalid resource lookup data provided (mismatched type).</code> What is this error saying?</p> <p><strong>Ultimate Question:</strong> How can I use <code>foo</code> as the <code>detail_uri_name</code>?</p> <p><strong>EDIT</strong> Model:</p> <pre><code>class AgoraUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='agora_user') class Meta: db_table = 'agora_users' </code></pre> <p>Urls:</p> <pre><code>full_api = Api(api_name='full') full_api.register(AgoraUserResourse()) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(full_api.urls)), url(r'^', include(min_api.urls)), url(r'^search/', include('haystack.urls')), url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), ] </code></pre> <p>Actual Resource:</p> <pre><code>class AgoraUserResourse_min(ModelResource): username = fields.CharField(attribute = 'user__username' ) class Meta: resource_name='user' #detail_uri_name = 'user__username' queryset = AgoraUser.objects.all() allowed_methods = ['get', 'put', 'post'] authentication = AgoraAuthentication() authorization = AgoraAuthorization() def get_bundle_detail_data(self, bundle): return bundle.obj.username </code></pre>
4
2016-07-30T02:08:36Z
38,793,845
<p>It looks like you need to override <code>detail_uri_kwargs</code> for your resource.</p> <p>I wound up with something like this:</p> <pre><code>from tastypie import fields from tastypie.resources import ModelResource from tastypie.bundle import Bundle from .models import AgoraUser class AgoraUserResourse(ModelResource): username = fields.CharField(attribute='user__username') class Meta: resource_name='user' detail_uri_name = 'user__username' queryset = AgoraUser.objects.all() allowed_methods = ['get', 'put', 'post'] # authentication = AgoraAuthentication() # authorization = AgoraAuthorization() def detail_uri_kwargs(self, bundle_or_obj): if isinstance(bundle_or_obj, Bundle): bundle_or_obj = bundle_or_obj.obj return { 'user__username': bundle_or_obj.user.username } def get_bundle_detail_data(self, bundle): return bundle.obj.username </code></pre>
1
2016-08-05T16:24:48Z
[ "python", "django", "model", "tastypie" ]
How do I pass variables between two different python scripts I have
38,669,746
<p>I'm trying to pass information between two different python scripts. They're quite long, so for simplification purposes, here are two other scripts where I encounter the same issue: </p> <p>a.py</p> <pre><code>f = open('test.txt', 'w+') num = int(raw_input('How many are there: ')) tipe = raw_input('What kind are they: ') if __name__ == '__main__': from b import fxn for x in xrange(num, num+11): fxn() num = x f.close() </code></pre> <p>b.py</p> <pre><code>from a import num, tipe def fxn(): print num, tipe f.writelines(str(num)+', '+tipe) </code></pre> <p>I am asked for num and tipe twice, then the entries from the second time are printed 11 times.</p> <p>How can I make it so the variables/files in a.py are passed to b.py, edited/opedned/manipulated in b.py, then passed back to/closed in a.py?</p> <p>Also, why am I asked for num and tipe twice, then the code under if <strong>name</strong> == '<strong>main</strong>': is run?</p>
1
2016-07-30T02:14:10Z
38,669,849
<p>When passing variables between Python scripts, remember that when you call a script, the calling script can access the namespace of the called script. </p> <p>That being said, you could give this a try: Start the called script with the code</p> <pre><code>from __main__ import * </code></pre> <p>This grants access to the namespace (variables and functions) of the caller script. Since these are not actually the files you will be manipulating as you said earlier I will leave it to you to apply this to the real files, hope this helps. </p>
0
2016-07-30T02:35:13Z
[ "python", "variables", "import", "module" ]
How do I pass variables between two different python scripts I have
38,669,746
<p>I'm trying to pass information between two different python scripts. They're quite long, so for simplification purposes, here are two other scripts where I encounter the same issue: </p> <p>a.py</p> <pre><code>f = open('test.txt', 'w+') num = int(raw_input('How many are there: ')) tipe = raw_input('What kind are they: ') if __name__ == '__main__': from b import fxn for x in xrange(num, num+11): fxn() num = x f.close() </code></pre> <p>b.py</p> <pre><code>from a import num, tipe def fxn(): print num, tipe f.writelines(str(num)+', '+tipe) </code></pre> <p>I am asked for num and tipe twice, then the entries from the second time are printed 11 times.</p> <p>How can I make it so the variables/files in a.py are passed to b.py, edited/opedned/manipulated in b.py, then passed back to/closed in a.py?</p> <p>Also, why am I asked for num and tipe twice, then the code under if <strong>name</strong> == '<strong>main</strong>': is run?</p>
1
2016-07-30T02:14:10Z
38,672,297
<p>you can pass them through functions</p> <p><strong>a.py</strong></p> <pre><code>f = open('test.txt', 'w+') num = int(raw_input('How many are there: ')) tipe = raw_input('What kind are they: ') if __name__ == '__main__': from b import fxn for x in xrange(num, num+11): fxn(num, tipe, f) # Pass parameters num, tipe and file handle num = x f.close() </code></pre> <p><strong>b.py</strong></p> <pre><code># from a import num, tipe --&gt; **This is not required** # receive inputs def fxn(num, tipe, f): print num, tipe f.writelines(str(num)+', '+tipe) </code></pre> <p>Executing a.py will result in</p> <pre><code>3 fruits 3 fruits 4 fruits 5 fruits 6 fruits 7 fruits 8 fruits 9 fruits 10 fruits 11 fruits 12 fruits </code></pre> <p>3 fruits prints twice because you are calling function first and then you are increasing num (by re-assigning). Instead you can have your <strong>a.py as below to have 3 fruits printed only once:</strong></p> <pre><code>f = open('test.txt', 'w+') num = int(raw_input('How many are there: ')) tipe = raw_input('What kind are they: ') if __name__ == '__main__': from b import fxn for x in xrange(num, num+11): fxn(x, tipe, f) # Pass parameters num, tipe and file handle f.close() </code></pre>
0
2016-07-30T09:14:15Z
[ "python", "variables", "import", "module" ]
excel converts a string of format "MM/DD/YYYY HH:MM:SS" to a date of format "MM/DD/YYYY HH:MM"
38,669,754
<p>I am using python's csv module to write a list to a csv file. One of the entries in the list is a string of format <code>"MM/DD/YYYY HH:MM:SS AM/PM"</code>. When i open the csv file using excel, the format of this entry is showing up as <code>"MM/DD/YYYY HH:MM"</code>. On highlighting the cell I can see the formula bar shows the true format of <code>"MM/DD/YYYY HH:MM:SS AM/PM"</code>. What is excel doing here and how can i ensure the original datetime format shows up correctly in excel. </p> <p>To give you some background on the problem, I am trying to export data from an oracle database in a csv format which i have to do quite frequently for analysis and review.</p> <p>Thanks for your help</p>
-1
2016-07-30T02:16:05Z
38,678,787
<ul> <li>select your cell(s)</li> <li>right click</li> <li>format cells </li> <li>custom</li> <li>type in [$-409]mm/dd/yyyy hh:mm:ss AM/PM;@</li> <li>press ok</li> </ul> <p>Some items may be named slightly different as I translated this from a German Excel version.</p>
0
2016-07-30T21:47:15Z
[ "python", "excel", "csv" ]
How to remove elements in a list based on another list in python, without loops?
38,669,859
<p>I have two lists of equal length:</p> <pre><code>list_a = ['a','b','c','d'] list_b = [-6.3, 3.1, 0.5, 4.1] </code></pre> <p>I want to remove the elements &lt; 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p> <pre><code>list_a_2 = ['b','d'] list_b_2 = [3.1, 4.1] </code></pre> <p>I know the second list, </p> <pre><code>list_b_2 = [item for item in hem if item &gt; 0.7]. </code></pre> <p>But is there a list-thinking way to get list_a_2, without using loops?</p>
2
2016-07-30T02:38:22Z
38,669,913
<p>One way is to use <code>zip</code>:</p> <pre><code>list_a_2, list_b_2 = zip(*[(a, b) for a, b in zip(list_a, list_b) if b &gt; 0.7]) list_a_2 # ('b', 'd') list_b_2 # (3.1, 4.1) </code></pre> <p>If a for loop is better suited, you can create two empty lists and conditionally append the values to them:</p> <pre><code>list_a_2, list_b_2 = [], [] for a, b in zip(list_a, list_b): if b &gt; 0.7: list_a_2.append(a) list_b_2.append(b) list_a_2 # ['b', 'd'] list_b_2 # [3.1, 4.1] </code></pre>
6
2016-07-30T02:48:14Z
[ "python" ]
How to remove elements in a list based on another list in python, without loops?
38,669,859
<p>I have two lists of equal length:</p> <pre><code>list_a = ['a','b','c','d'] list_b = [-6.3, 3.1, 0.5, 4.1] </code></pre> <p>I want to remove the elements &lt; 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p> <pre><code>list_a_2 = ['b','d'] list_b_2 = [3.1, 4.1] </code></pre> <p>I know the second list, </p> <pre><code>list_b_2 = [item for item in hem if item &gt; 0.7]. </code></pre> <p>But is there a list-thinking way to get list_a_2, without using loops?</p>
2
2016-07-30T02:38:22Z
38,669,940
<p>Without explicit loops, create both? Sure, if we use a temporary object:</p> <pre><code>list_a = ['a','b','c','d'] list_b = [-6.3, 3.1, 0.5, 4.1] tmp = zip(a, b) list_a_2 = [x[0] for x in tmp if x[1] &gt; 0.7] list_b_2 = [x[1] for x in tmp if x[1] &gt; 0.7] del tmp </code></pre> <p>But using an actual for-loop will be a bit more obvious:</p> <pre><code>for idx, value in enumerate(list_b): if value =&lt; 0.7: list_a.pop(idx) list_b.pop(idx) </code></pre> <p>But you're still managing two lists for mapping (basically) keys to values. This is what a dictionary is for! Consolidate those list and create your subset with some dictionary comprehension:</p> <pre><code>{x:y for x, y in zip(list_a, list_b) if y &gt; 0.7} </code></pre>
1
2016-07-30T02:55:17Z
[ "python" ]
How to remove elements in a list based on another list in python, without loops?
38,669,859
<p>I have two lists of equal length:</p> <pre><code>list_a = ['a','b','c','d'] list_b = [-6.3, 3.1, 0.5, 4.1] </code></pre> <p>I want to remove the elements &lt; 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p> <pre><code>list_a_2 = ['b','d'] list_b_2 = [3.1, 4.1] </code></pre> <p>I know the second list, </p> <pre><code>list_b_2 = [item for item in hem if item &gt; 0.7]. </code></pre> <p>But is there a list-thinking way to get list_a_2, without using loops?</p>
2
2016-07-30T02:38:22Z
38,670,098
<p>If you really want to avoid loops you can use a recursive function:</p> <pre><code>def unnecessarily_recursive_function(list_a,list_b): try: a = list_a.pop(0) b = list_b.pop(0) tmp_a, tmp_b = unnecessarily_recursive_function(list_a,list_b) if b &lt; 0.7: return [a] + tmp_a, [b] + tmp_b else: return tmp_a, tmp_b except IndexError: return [],[] </code></pre> <p>which you can call like:</p> <pre><code>list_a, list_b = unnecessarily_recursive_function(list_a, list_b) </code></pre> <p>Note that this is a really bad reason to use a recursive function and you should definitely actually go with the other suggestions above. </p>
0
2016-07-30T03:32:23Z
[ "python" ]
How to remove elements in a list based on another list in python, without loops?
38,669,859
<p>I have two lists of equal length:</p> <pre><code>list_a = ['a','b','c','d'] list_b = [-6.3, 3.1, 0.5, 4.1] </code></pre> <p>I want to remove the elements &lt; 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p> <pre><code>list_a_2 = ['b','d'] list_b_2 = [3.1, 4.1] </code></pre> <p>I know the second list, </p> <pre><code>list_b_2 = [item for item in hem if item &gt; 0.7]. </code></pre> <p>But is there a list-thinking way to get list_a_2, without using loops?</p>
2
2016-07-30T02:38:22Z
38,680,355
<p>Thanks a lot! For other people having a same problem:</p> <p>I end up with the following code:</p> <pre><code>list_a = ['a','b','c','d'] list_b = [-6.3, 3.1, 0.5, 4.1] tmp = zip(a, b) list_a_2 = [x[0] for x in tmp if x[1] &gt; 0.7] list_b_2 = [x[1] for x in tmp if x[1] &gt; 0.7] del tmp </code></pre> <p>And a better idea might be directly use a dataframe to match each element with its own label.</p>
0
2016-07-31T02:59:41Z
[ "python" ]
Excel add-in removed without consent
38,669,887
<p>I have programmed an excel add-in in VBA that makes calls to a MySQL server using python. My problem is the following : </p> <p>every once in a while, for no apparent reason, the add-in gets removed from the developer tab, and I can't access its code anymore. The way around this problem is to uninstall and reinstall the add-in (Files->OPtions->Add-ins->Go..). Since it is quite tedious, I am reaching out for help.</p> <p><a href="http://i.stack.imgur.com/lsXf1.png" rel="nofollow">Opening a existing file with formulas from my add-in, I first get the following warning</a></p> <p><a href="http://i.stack.imgur.com/93xAV.png" rel="nofollow">Leading to this when trying to edit the links</a></p> <p>Unfortunately the editing fails and gives an error message</p> <p>Then, the formulas stay broken and fail to call the add-in, just like it wasn't found, and i have to remove it and re-import it for the workbook to function.</p> <p>Has any VBA developer run into the issue before? </p>
2
2016-07-30T02:44:02Z
38,670,601
<p>Here is how I would do it IF I am facing the same issue as yours</p> <ol> <li>Close all open workbooks in Excel</li> <li>Create a new subroutine called <code>Auto_Open</code> in a Blank Excel File</li> <li>Add the code which is mentioned at the bottom of this post</li> <li>Save it to <code>C:\Users\&lt;your username&gt;\AppData\Roaming\Microsoft\Excel\XLSTART</code> after you have entered, tested and verified the code. <em>The path may vary depending on the OS that you are using</em>.</li> </ol> <p>And you are done. Next time Excel launches, it will check if the Add-In is installed and if not then it will install it.</p> <p><strong>Untested</strong></p> <pre><code>Sub Auto_Open() If IsAddinLoaded("Your Add-In Name") = False Then With Application .AddIns.Add "Filepath to your Add-In", False .AddIns("Your Add-In Name").Installed = True End With End If End Sub Function IsAddinLoaded(AddinName As String) As Boolean On Error Resume Next IsAddinLoaded = Len(Workbooks(AddIns(AddinName).Name).Name) &gt; 0 End Function </code></pre>
3
2016-07-30T05:21:32Z
[ "python", "excel", "vba", "excel-vba", "xlwings" ]
Retain ordering of text data when vectorizing
38,669,905
<p>I am attempting to write a machine learning algorithm with <code>scikit-learn</code> that parses text and classifies it based on training data.</p> <p>The example for using text data, taken directly from the <code>scikit-learn</code> documentation, uses a <code>CountVectorizer</code> to generate a sparse array for how many times each word appears.</p> <pre><code>&gt;&gt;&gt; from sklearn.feature_extraction.text import CountVectorizer &gt;&gt;&gt; count_vect = CountVectorizer() &gt;&gt;&gt; X_train_counts = count_vect.fit_transform(twenty_train.data) </code></pre> <p>Unfortunately, this does not take into account any ordering of the phrases. It is possible to use larger <code>ngrams</code> (<code>CountVectorizer(ngram_range=(min, max))</code>) to look at specific phrases, but this increases the number of features rapidly and isn't even that great.</p> <p>Is there a good way of dealing with ordered text in another way? I'm definitely open to using a natural language parser (<code>nltk</code>, <code>textblob</code>, etc.) along with <code>scikit-learn</code>.</p>
4
2016-07-30T02:47:22Z
38,670,377
<p>What about <a href="https://www.tensorflow.org/versions/r0.10/tutorials/word2vec/index.html" rel="nofollow">word2vec embedding?</a> It is a neural network based embedding of words into vectors, and takes context into account. This could provide a more sophisticated set of features for your classifier.</p> <p>One powerful python library for natural language processing with a good word2vec implementation is <a href="http://radimrehurek.com/gensim/" rel="nofollow">gensim</a>. Gensim is built to be very scalable and fast, and has advanced text processing capabilities. Here is a quick outline on how to get started:</p> <p><strong>Installing</strong></p> <p>Just do <code>easy_install -U gensim</code> or <code>pip install --upgrade gensim</code>.</p> <p><strong>A simple word2vec example</strong></p> <pre><code>import gensim documents = [['human', 'interface', 'computer'], ['survey', 'user', 'computer', 'system', 'response', 'time'], ['eps', 'user', 'interface', 'system'], ['system', 'human', 'system', 'eps'], ['user', 'response', 'time'], ['trees'], ['graph', 'trees'], ['graph', 'minors', 'trees'], ['graph', 'minors', 'survey']] model = gensim.models.Word2Vec(documents, min_count=1) print model["survey"] </code></pre> <p>This will output the vector that "survey" maps to, which you could use for a feature input to your classifier.</p> <p>Gensim has a lot of other capabilities, and it is worth getting to know it better if you're interested in Natural Language Processing.</p>
1
2016-07-30T04:37:00Z
[ "python", "python-3.x", "order", "scikit-learn", "nltk" ]
TensorFlow/TFLearn -Architecture Err - 'ValueError: Cannot feed value of shape (64,) for Tensor u'TargetsData/Y:0', which has shape '(?, 1)'
38,670,055
<p>I tried tflearn Quickstart titanic tutorial successfully and made some tests further. I was predicting a float target by 8 float inputs, and I modified some of the tutorial then 'ValueError: Cannot feed value of shape (64,) for Tensor u'TargetsData/Y:0', which has shape '(?, 1)''</p> <h1>Build neural network</h1> <pre><code>net = tflearn.input_data(shape=[None, 8]) net = tflearn.fully_connected(net, 32) net = tflearn.fully_connected(net, 32) net = tflearn.fully_connected(net, 1, activation='relu') net = tflearn.regression(net) </code></pre> <h1>Define model</h1> <pre><code>model = tflearn.DNN(net, tensorboard_verbose=0) </code></pre> <h1>Start training (apply gradient descent algorithm)</h1> <pre><code>model.fit(data, mfe, n_epoch=100)#Err occurs </code></pre> <p>Could somebody kindly help me: 1. What do 'shape (64,) ' and shape '(?, 1)' stand for? 2. How can I fix this Architecture Err? 3. Could you make some recommendation of materials learning neural networks architecture?</p> <p>Thanks &amp; Regards, Simon</p>
0
2016-07-30T03:22:15Z
38,670,172
<p>I have never used TensorFlow but I bet this is just a broadcasting issue. Try to change the shape of your problematic array which currently has shape (64,) into (64,1), that is from a row vector to a column vector:</p> <pre><code>my_array.shape = (64, 1) </code></pre> <p>or more generally for any length:</p> <pre><code>my_array.shape = (-1, 1) </code></pre> <p>You can read about shapes and broadcasting rules on the numpy documentation pages for more details. As for recommendation for neural networks architecture learning material, this is unfortunately off-topic (too opinion based) by SO rules.</p>
1
2016-07-30T03:49:14Z
[ "python", "neural-network", "deep-learning" ]
Saving wxPython scrolledcanvas contents to image
38,670,168
<p>I've been trying this for a bit and haven't found a solution that works for me</p> <p>I have a <code>wx.scrolledcanvas</code> that I'm trying to save to an image, however when i use the answers I've found they all save only the visible portion of the canvas, and not the full canvas. Is there any way to save the entirety of the scrolled canvas to a file?</p> <p>Thanks</p>
0
2016-07-30T03:48:30Z
38,679,469
<p>Refactor your code such that what you are drawing in your <code>EVT_PAINT</code> handler can be called passing it the <code>wx.DC</code> to be drawn upon, and then call that from your paint handler with the <code>wx.PaintDC</code> or whatever you are currently using. When you want to save it to an image call the same code passing a <code>wx.MemoryDC</code> with a <code>wx.Bitmap</code> selected into it. When it's done the bitmap will have the same contents as the window, and you can then save it to a file or whatever you need to do with it.</p>
1
2016-07-30T23:35:55Z
[ "python", "wxpython" ]
Different results from BeautifulSoup each time
38,670,187
<p>I'm doing a web scrape of a website with 122 different pages with 10 entries per page. The code breaks on random pages, on random entries each time it is ran. I can run the code on a url one time and it works while other times it does not.</p> <pre><code>def get_soup(url): soup = BeautifulSoup(requests.get(url).content, 'html.parser') return soup def from_soup(soup, myCellsList): cellsList = soup.find_all('li', {'class' : 'product clearfix'}) for i in range (len(cellsList)): ottdDict = {} ottdDict['Name'] = cellsList[i].h3.text.strip() </code></pre> <p>This is only a piece of my code, but this is where the error is occurring. The problem is that when I use this code, the h3 tag is not always appearing in each item in the cellsList. This results in a NoneType error when the last line of the code is ran. However, the h3 tag is always there in the HTML when I inspect the webpage. </p> <p><a href="http://i.stack.imgur.com/h8eyT.png" rel="nofollow">cellsList vs html 1</a></p> <p><a href="http://i.stack.imgur.com/qJEey.png" rel="nofollow">same comparison made from subsequent soup request</a></p> <p>What could be causing these differences and how can I avoid this problem? I was able to run the code successfully for a time, and it seems to have all of a sudden stopped working. The code is able to scrape some pages without problem but it randomly does not register the h3 tags on random entries on random pages.</p>
3
2016-07-30T03:53:41Z
38,673,300
<p>There are slight discrepancies in the html for various elements as you progress through the site pages, the best way to get the name is actually to select the outer div and extract the text from the anchor.</p> <p>This will get all the info from each product and put it into dicts where the keys are <em>'Tissue', 'Cell'</em> etc.. and the values are the relating descriptionm:</p> <pre><code>import requests from time import sleep def from_soup(url): with requests.Session() as s: s.headers.update({ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"}) # id for next oage anchor. id_ = "#layoutcontent_2_middlecontent_0_threecolumncontent_0_content_ctl00_rptCenterColumn_dcpCenterColumn_0_ctl00_0_productRecords_0_bottomPaging_0_liNextPage_0" soup = BeautifulSoup(s.get(url).content) for li in soup.select("ul.product-list li.product.clearfix"): name = li.select_one("div.product-header.clearfix a").text.strip() d = {"name": name} for div in li.select("div.search-item"): k = div.strong.text d[k.rstrip(":")] = " ".join(div.text.replace(k, "", 1).split()) yield d # get anchor for next page and loop until no longer there. nxt = soup.select_one(id_) # loop until mo more next page. while nxt: # sleep between requests sleep(.5) resp = s.get(nxt.a["href"]) soup = BeautifulSoup(resp.content) for li in soup.select("ul.product-list li.product.clearfix"): name = li.select_one("div.product-header.clearfix a").text.strip() d = {"name": name} for div in li.select("div.search-item"): k = div.strong.text d[k.rstrip(":")] = " ".join(div.text.replace(k,"",1).split()) yield d </code></pre> <p>After running:</p> <pre><code>for ind, h in enumerate(from_soup( "https://www.lgcstandards-atcc.org/Products/Cells_and_Microorganisms/Cell_Lines/Human/Alphanumeric.aspx?geo_country=gb")): print(ind, h) </code></pre> <p>You will see 1211 dicts with all the data.</p>
2
2016-07-30T11:15:19Z
[ "python", "beautifulsoup" ]
curl https://pypi.python.org/simple/pip returns nothing
38,670,217
<p>I have run into a very strange error on my MacBook. I've seen some similar posts but none of them solved my issue.</p> <p>I've been trying to install some Python libraries, and I tried to use curl to view this link: <a href="https://pypi.python.org/simple/pip/" rel="nofollow">https://pypi.python.org/simple/pip/</a></p> <p>It's very strange that the curl command returned nothing but a bash prompt like:</p> <pre><code>$ curl https://pypi.python.org/simple/pip $ </code></pre> <p>At the beginning, I thought that's my proxy/firewall's problem, but when I try the link in my Safari/Chrome, the web browser displays the page perfectly.</p> <p>What's wrong with my curl command? I am using curl coming alone with Mac OS El Capitan.</p> <pre><code>$ which curl /usr/bin/curl </code></pre>
0
2016-07-30T04:00:24Z
38,670,227
<p>Try using curl in verbose mode to see why:</p> <pre><code>curl -v https://pypi.python.org/simple/pip </code></pre> <p>The response is a permanent redirect. It works if you append a trailing slash as follows:</p> <pre><code>curl https://pypi.python.org/simple/pip/ </code></pre>
2
2016-07-30T04:03:29Z
[ "python", "osx", "curl" ]
Fastest way to xor all integers in a string
38,670,246
<p>I am trying to find the fastest way of xor'ing all integers(numerals actually) in a string consecutively. The problem makes me feel that there is an simple and a fast answer I just can't think of. But here what I came up with so far.</p> <p><strong>Setup:</strong></p> <pre><code>from operator import xor a = "123" </code></pre> <ul> <li><p>Regular loop</p> <pre><code>val = 0 for i in a: val = val ^ int(i) print val </code></pre></li> <li><p><code>operations.xor</code> with <code>reduce</code></p> <pre><code>reduce(xor, map(int, list(a))) </code></pre></li> </ul> <p>I expected the second one to be faster but when the string grows, the difference is almost none. Is there a faster way ?</p> <p><strong>Note1:</strong> And I would like to know if it is possible using just the integer as <code>123</code> instead of the string <code>"123"</code>. That would be unlogical because I need a list of integers, however sometimes interesting answers appear from places you never expect.</p> <p><strong>Edit:</strong> Here is the results from the methods suggested so far.</p> <pre><code>import timeit setup = """ from operator import xor a = "124" b = 124 """ p1 = """ val = 0 for i in a: val = val ^ int(i) val """ p2 = """ reduce(xor, map(int, list(a))) """ p3 = """ val = 0 for i in xrange(3): val = val ^ (b % 10) b /= 10 val """ p4 = """ 15 &amp; reduce(xor, map(ord, a)) """ print 1, timeit.timeit(p1, setup=setup, number = 100000) print 2, timeit.timeit(p2, setup=setup, number = 100000) print 3, timeit.timeit(p3, setup=setup, number = 100000) print 4, timeit.timeit(p4, setup=setup, number = 100000) # Gives 1 0.251768243842 2 0.377706036384 3 0.0885620849347 4 0.140079894386 </code></pre> <p>Please also note that using <code>int(a)</code> instead of <code>b</code> in process 3 makes it slower than 4.</p>
0
2016-07-30T04:07:16Z
38,670,540
<p>On my (Python 3) system, this rework of the solution runs measureably faster than those shown:</p> <pre><code>from operator import xor from functools import reduce print(15 &amp; reduce(xor, map(ord, a))) </code></pre> <p>If we know they are all digits, <code>15 &amp; ord('5')</code> pulls out the bits we need with less overhead than <code>int('5')</code>. And we can delay the logical "and", doing it just once at the end.</p> <p>To use a number instead of a string, you can do:</p> <pre><code>b = 31415926535897932384626433832795028841971693993751058209749445923078164 val = 0 while b: b, modulo = divmod(b, 10) val ^= modulo print(val) </code></pre>
1
2016-07-30T05:07:22Z
[ "python", "performance", "complexity-theory", "xor" ]
python get time stamp on file in mm/dd/yyyy-HH:MM format
38,670,267
<p>I'm trying to get the datestamp on the file in mm-dd-yyyy-hh:mm format.</p> <pre><code>time.ctime(os.path.getmtime(file)) </code></pre> <p>gives me detailed time stamp:</p> <pre><code>Fri Jun 07 16:54:31 2013 </code></pre> <p>How can I display the output as:</p> <pre><code>06-07-2013-16:54 </code></pre> <p>This is very similar to: <a href="http://stackoverflow.com/questions/16994696/python-get-time-stamp-on-file-in-mm-dd-yyyy-format">python get time stamp on file in mm/dd/yyyy format</a></p> <p>This is doing the half of what I want but I can't add hour and minute.</p> <pre><code>time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file))) </code></pre>
0
2016-07-30T04:11:16Z
38,670,284
<p>Just found it, I needed to add %H:%M like below:</p> <pre><code>time.strftime('%m-%d-%Y-%H:%M', time.gmtime(os.path.getmtime()) </code></pre>
0
2016-07-30T04:15:47Z
[ "python", "date", "unix-timestamp" ]
Raspberry pi:sudo is not working
38,670,270
<p>I have logged into raspberry pi via SSH. I m getting error while run any command with sudo in raspberry pi3. Eroor is like sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set.So i dont know how to set it and this error is about what? If root user require than plz tell me what is root user and how to logged into root user in raspberry pi3 via SSH?plz help me.Thanks in advance.</p>
0
2016-07-30T04:11:37Z
38,724,812
<p>Login with root </p> <pre><code>su - </code></pre> <p>and </p> <pre><code>chown root:root /usr/bin/sudo &amp;&amp; chmod 4755 /usr/bin/sudo </code></pre>
0
2016-08-02T15:33:54Z
[ "python", "windows", "putty", "raspberry-pi3" ]
Are Boto3 Resources and Clients Equivalent? When Use One or Other?
38,670,372
<p>Boto3 Mavens,</p> <p>What is the functional difference, if any, between Clients and Resources?</p> <p>Are they functionally equivalent?</p> <p>Under what conditions would you elect to invoke a Boto3 Resource vs. a Client (and vice-versa)?</p> <p>Although I've endeavored to answer this question by RTM...regrets, understanding the functional difference between the two eludes me.</p> <p>Your thoughts?</p> <p>Many, <em>many</em> thanks!</p> <p><em>Plane Wryter</em></p>
4
2016-07-30T04:36:28Z
38,707,084
<p>Resources are just a resource-based abstraction over the clients. They can't do anything the clients can't do, but in many cases they are nicer to use. They actually have an embedded client that they use to make requests. The downside is that they don't always support 100% of the features of a service.</p>
2
2016-08-01T19:55:55Z
[ "python", "amazon-web-services", "boto3" ]
Unsuccessful attempts to post request for form submission
38,670,424
<p>I am working on my first project using python to submit a form and retrieve weather data from <a href="http://www.weather.gov" rel="nofollow">http://www.weather.gov</a></p> <p>I am brand new to HTTP form submission and as such it is highly possible I am going about this all wrong. I've read that mechanize and/or selenium are more efficient for this type of job, but I am limited to these modules by my school's server.</p> <pre><code>import requests r = requests.get('http://www.weather.gov') location = raw_input("Enter zipcode: ") payload = {'key1' : location} q = requests.post('http://forecast.weather.gov/', data = payload) print q.text </code></pre> <p>My attempts to search a given zipcode have been unsuccessful, I am not reaching the local weather for the given zipcode.</p> <p><strong>Note:</strong> I have also tried this form submission using urllib &amp; urllib2 without success. </p> <pre><code>import urllib import urllib2 location = raw_input("Enter Zip Code here: ") url = 'http://forecast.weather.gov/' values = {'inputstring' : location} data = urllib.urlencode(values) req = urllib2.Request(url, data = data) response = urllib2.urlopen(req) html = response.read() print html </code></pre> <p>Form as seen from inspecting the page:</p> <pre><code>&lt;form name="getForecast" id="getForecast" action="http://forecast.weather.gov/zipcity.php" method="get"&gt; &lt;label for="inputstring"&gt;Local forecast by &lt;br&gt;"City, St" or ZIP code&lt;/label&gt; &lt;input id="inputstring" name="inputstring" type="text" value="Enter location ..." onclick="this.value=''" autocomplete="off"&gt; &lt;input name="btnSearch" id="btnSearch" type="submit" value="Go"&gt; &lt;div id="txtError"&gt; &lt;div id="errorNoResults" style="display:none;"&gt;Sorry, the location you searched for was not found. Please try another search.&lt;/div&gt; &lt;div id="errorMultipleResults" style="display:none"&gt;Multiple locations were found. Please select one of the following:&lt;/div&gt; &lt;div id="errorChoices" style="display:none"&gt;&lt;/div&gt; &lt;input id="btnCloseError" type="button" value="Close" style="display:none"&gt; &lt;/div&gt; &lt;div id="txtHelp"&gt;&lt;a style="text-decoration: underline;" href="javascript:void(window.open('http://weather.gov/ForecastSearchHelp.html','locsearchhelp','status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1,height=500,width=530').focus());"&gt;Location Help&lt;/a&gt;&lt;/div&gt; &lt;/form&gt; &lt;input id="inputstring" name="inputstring" type="text" value="Enter location ..." onclick="this.value=''" autocomplete="off"&gt; </code></pre>
1
2016-07-30T04:47:41Z
38,670,513
<p>Post to the URL <a href="http://forecast.weather.gov/zipcity.php" rel="nofollow">http://forecast.weather.gov/zipcity.php</a> That is where the php script lies for receiving post data from the form.</p>
0
2016-07-30T05:02:36Z
[ "python", "forms", "python-requests", "urllib2", "urllib" ]
How to set angularjs input value using selenium(python)
38,670,502
<p>In the target webpage, there is an angularjs input element:</p> <pre><code>&lt;input type="text" class="form-control ng-pristine ng-valid ng-valid-maxlength ng-touched" placeholder="Role name" ng-model="selectedRole.roleName" maxlength="50"&gt; </code></pre> <p><a href="http://i.stack.imgur.com/3RcFa.jpg" rel="nofollow">enter image description here</a> And i can locate the element using selenium(python) by using <code>(By.CSS_SELECTOR,'input[ng-model="selectedRole.roleName"]')</code>, but cannot set its value, can anybody help on this, thanks in advance!</p>
1
2016-07-30T05:00:58Z
38,670,571
<p>Once you've located the <code>input</code> element, just <em>send the keys</em> to it:</p> <pre><code>role_name = driver.find_element_by_css_selector('input[ng-model="selectedRole.roleName"]') role_name.send_keys("test") </code></pre>
0
2016-07-30T05:14:12Z
[ "python", "angularjs", "selenium" ]
How to set angularjs input value using selenium(python)
38,670,502
<p>In the target webpage, there is an angularjs input element:</p> <pre><code>&lt;input type="text" class="form-control ng-pristine ng-valid ng-valid-maxlength ng-touched" placeholder="Role name" ng-model="selectedRole.roleName" maxlength="50"&gt; </code></pre> <p><a href="http://i.stack.imgur.com/3RcFa.jpg" rel="nofollow">enter image description here</a> And i can locate the element using selenium(python) by using <code>(By.CSS_SELECTOR,'input[ng-model="selectedRole.roleName"]')</code>, but cannot set its value, can anybody help on this, thanks in advance!</p>
1
2016-07-30T05:00:58Z
38,671,308
<p>I think you need to wait before send_keys using <code>WebDriverWait</code> until element to be visible as below :</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait wait = WebDriverWait(driver, 20) role_name = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,'input[ng-model="selectedRole.roleName"]'))) #now go for set value role_name.send_keys("alvin") </code></pre> <p>If you are still unable to set value try using <code>execute_script</code> as below :</p> <pre><code>driver.execute_script("arguments[0].value = 'alvin'", role_name) </code></pre> <p>Hope it helps...:)</p>
0
2016-07-30T07:05:42Z
[ "python", "angularjs", "selenium" ]
How to set angularjs input value using selenium(python)
38,670,502
<p>In the target webpage, there is an angularjs input element:</p> <pre><code>&lt;input type="text" class="form-control ng-pristine ng-valid ng-valid-maxlength ng-touched" placeholder="Role name" ng-model="selectedRole.roleName" maxlength="50"&gt; </code></pre> <p><a href="http://i.stack.imgur.com/3RcFa.jpg" rel="nofollow">enter image description here</a> And i can locate the element using selenium(python) by using <code>(By.CSS_SELECTOR,'input[ng-model="selectedRole.roleName"]')</code>, but cannot set its value, can anybody help on this, thanks in advance!</p>
1
2016-07-30T05:00:58Z
39,207,980
<p>You can simply access and set value using the below code.</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver.find_element_by_xpath("//input[@ng-model = 'selectedRole.roleName']") WebDriverWait(browser, 60).until(EC.presence_of_element_located((By.XPATH, "//input[@ng-model = 'selectedRole.roleName']"))).send_keys('Your Value') </code></pre>
0
2016-08-29T13:51:00Z
[ "python", "angularjs", "selenium" ]
How to add comment box and post form to django rest framework
38,670,510
<p>I created a site by following a django rest framework tutorial(<a href="http://192.241.153.25:8000" rel="nofollow">http://192.241.153.25:8000</a>)</p> <p>and i finished hooking up login part and posts, but i have no clue in what way how i can put a posting form and comment box for the individual post.</p> <p>here is what i have tried though</p> <p>html</p> <pre><code>&lt;form id="post_form" method="post" action=""&gt; &lt;input type="text" name="title" placeholder="Username"&gt; &lt;input type="text" name="content" placeholder="content"&gt; &lt;button class="ladda-button button-primary login_button" ng-click="vm.submit()"/&gt;&lt;span class="ladda-label"&gt;submit&lt;/span&gt;&lt;/button&gt; &lt;/form&gt; </code></pre> <p>jquery</p> <pre><code> $('#post_form').on('submit', function(e) { e.preventDefault() $.ajax({ type:"POST", url: '/api/posts/create/', data:$('#post_form').serialize(), error: function(response){ alert('Not authorized.'); // Or something in a message DIV }, success: function(response){ console.log(response); $('.login_bar').html(response) $('.login_bar').html(response) $('#logout_form').toggleClass(show) // do something with response } }); }); </code></pre> <p>and here is my API.</p> <p><a href="http://192.241.153.25:8000/api/posts/create/" rel="nofollow">http://192.241.153.25:8000/api/posts/create/</a></p> <p>could anyone help me out here?</p>
0
2016-07-30T05:02:26Z
38,670,928
<p>This may work for you: views.py :-</p> <pre><code>def adComment(request): print request if request.method == 'POST': form = CommentForm(request.POST) #Validate your data with form. if form.is_valid(): instance = form.save(commit=False) instance.title = form.cleaned_data['username'] instance.comments = form.cleaned_data['content'] instance.save() #Will save your data if valid. data = {'success':True,'msg':"Store comment's data successfully"} return Response(data) else: data = {'success':False,'msg':'Error in storing comments'} return Response(data) </code></pre> <p>forms.py</p> <pre><code>from django.forms import ModelForm from models import commentData class CommentForm(ModelForm): class Meta: model = commentData #Your model name created to store comment's data fields = [ "username", "content", ] </code></pre>
0
2016-07-30T06:13:25Z
[ "jquery", "python", "angularjs", "django" ]
How to add comment box and post form to django rest framework
38,670,510
<p>I created a site by following a django rest framework tutorial(<a href="http://192.241.153.25:8000" rel="nofollow">http://192.241.153.25:8000</a>)</p> <p>and i finished hooking up login part and posts, but i have no clue in what way how i can put a posting form and comment box for the individual post.</p> <p>here is what i have tried though</p> <p>html</p> <pre><code>&lt;form id="post_form" method="post" action=""&gt; &lt;input type="text" name="title" placeholder="Username"&gt; &lt;input type="text" name="content" placeholder="content"&gt; &lt;button class="ladda-button button-primary login_button" ng-click="vm.submit()"/&gt;&lt;span class="ladda-label"&gt;submit&lt;/span&gt;&lt;/button&gt; &lt;/form&gt; </code></pre> <p>jquery</p> <pre><code> $('#post_form').on('submit', function(e) { e.preventDefault() $.ajax({ type:"POST", url: '/api/posts/create/', data:$('#post_form').serialize(), error: function(response){ alert('Not authorized.'); // Or something in a message DIV }, success: function(response){ console.log(response); $('.login_bar').html(response) $('.login_bar').html(response) $('#logout_form').toggleClass(show) // do something with response } }); }); </code></pre> <p>and here is my API.</p> <p><a href="http://192.241.153.25:8000/api/posts/create/" rel="nofollow">http://192.241.153.25:8000/api/posts/create/</a></p> <p>could anyone help me out here?</p>
0
2016-07-30T05:02:26Z
38,672,202
<p>Look at this exapmle:</p> <p>models.py</p> <pre><code>class Post(models.Model): title = models.CharField(max_length=500) body = models.TextField() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post) text = models.TextField() author = models.CharField(max_length=100) def __str__(self): return "[%s] %s" % (self.author, self.text) </code></pre> <p>serializers.py</p> <pre><code>from .models import Post, Comment from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('text', 'author', 'post') class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title', 'body', 'comment_set') </code></pre> <p>views.py</p> <pre><code>from rest_framework import viewsets from rest_framework.permissions import AllowAny from .models import Post, Comment from .serializers import CommentSerializer, PostSerializer class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer permission_classes = [AllowAny] queryset = Post.objects.all() class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer permission_classes = [AllowAny] queryset = Comment.objects.all() </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls import url, include from rest_framework import routers from .views import PostViewSet, CommentViewSet router = routers.DefaultRouter() router.register(r'posts', PostViewSet) router.register(r'comments', CommentViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] </code></pre> <p><strong>Sending a POST request in JSON format to <code>http://127.0.0.1/comments/</code> with the following content</strong>:</p> <pre><code>{"author":"Jerry", "text": "Nice post!", "post": 1} </code></pre> <p>creates a new comment for post with id = 1 in this case</p>
0
2016-07-30T09:04:59Z
[ "jquery", "python", "angularjs", "django" ]
Python: how to save the output to a text file?
38,670,522
<p>1. I tried with -o werwe wer wer wer we 2.and >>text.txtrr rrrrrrrrrrrrrrrrrrrrrrrr</p> <pre><code> # -*- coding: iso-8859-15 import sys import requests import os if len(sys.argv) &gt;= 2: os.system('clear') print "Please wait.."`enter code here` P1 = str(sys.argv[1]) url = "http://example.com/index.php" data= { 'getp1':'%s'%(P1) } r = requests.get(url,params=data) -o text.txt os.system('clear') print r.content else: print "[ERROR] Este programa nerrcesita un parámetro"; </code></pre>
-2
2016-07-30T05:04:15Z
38,671,178
<p>First, this isn't a well-put question. You don't state what your error is, or what you expected to happen. But, there are some obvious things in your code that we can fix. </p> <p>You seem to be mixing up shell commands and python code, after you've taken in sys.argv. </p> <pre><code>r = requests.get(url,params=data) -o text.txt </code></pre> <p>Is not valid python code - it looks like you're trying to use commandline syntax there. </p> <p>I would suggest something like:</p> <pre><code>r = requests.get(url,params=data) f = open('text.txt', 'w' ) f.write(r.content) f.close() </code></pre> <p>It's also worth noting that given you're downloading a PHP file contents, you probably want the r.text function, rather than r.content, <a href="http://docs.python-requests.org/en/master/user/quickstart/#response-content" rel="nofollow">which is for non-text responses (like images). you should also set the encoding.</a> </p>
0
2016-07-30T06:47:59Z
[ "python", "save", "output" ]
Split a pandas column of dictionaries into multiple columns
38,670,535
<p>I have the following csv with first row as header:</p> <pre><code>id,data a,"{'1': 0.7778, '3': 0.5882, '2': 0.9524, '4': 0.5556}" b,"{'1': 0.7778, '3': 0.5, '2': 0.7059, '4': 0.2222}" c,"{'1': 0.8182, '3': 0.2609, '2': 0.5882}" </code></pre> <p>I need to get to something like this</p> <pre><code>id 1 2 3 4 a 0.7778 0.9524 0.5882 0.5556 b 0.7778 0.7059 0.5 0.2222 c 0.8182 0.5882 0.2609 NaN </code></pre> <p>where the keys of the dictionary are the columns. </p> <p>How can I do this using pandas?</p>
5
2016-07-30T05:06:05Z
38,670,637
<p>You can do this with Python's <a href="https://docs.python.org/2/library/ast.html"><code>ast</code></a> module:</p> <pre><code>import ast import pandas as pd df = pd.read_csv('/path/to/your.csv') dict_df = pd.DataFrame([ast.literal_eval(i) for i in df.data.values]) &gt;&gt;&gt; dict_df 1 2 3 4 0 0.7778 0.9524 0.5882 0.5556 1 0.7778 0.7059 0.5000 0.2222 2 0.8182 0.5882 0.2609 NaN df = df.drop('data',axis=1) final_df = pd.concat([df,dict_df],axis=1) &gt;&gt;&gt; final_df id 1 2 3 4 0 a 0.7778 0.9524 0.5882 0.5556 1 b 0.7778 0.7059 0.5000 0.2222 2 c 0.8182 0.5882 0.2609 NaN </code></pre>
5
2016-07-30T05:27:29Z
[ "python", "pandas" ]
i want to write python file out put to xls or xlxs file
38,670,621
<p>I want to write username and output (taksh) in xls file. i want to do it for 1000 to 5000 users. i am new to Python and work as PBX engineer.</p> <p>my code and out put is below:</p> <pre><code>import requests import xml.etree.ElementTree as ET # this statement performs a GET on the specified url response = requests.get('https://10.10.10.10:8443/cucm-uds/users?last=XXXXXX',verify=False, auth=('XXXXXX', 'XXXXXX')) # print the json that is returned print (response.text) print('**********************') #doc= print (response.text) root = ET.fromstring(response.text) for child in root: doc=print(child.tag) for user in root.findall('user'): name=user.find('userName').text print(name) </code></pre> <p>output of file:</p> <pre><code>Warning (from warnings module): File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 821 InsecureRequestWarning) InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html Devices = &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;users uri="https://10.10.10.10:8443/cucm-uds/users" version="10.5.2" start="0" requestedCount="64" returnedCount="1" totalCount="1"&gt; &lt;user uri="https://10.10.10.10:8443/cucm-uds/user/taksh"&gt; &lt;id&gt;d96a9ee4-1992-4a37-b6dd-6c0702792e08&lt;/id&gt; &lt;userName&gt;taksh&lt;/userName&gt; &lt;firstName&gt;taksh&lt;/firstName&gt; &lt;lastName&gt;XXXXXX&lt;/lastName&gt; &lt;middleName&gt;&lt;/middleName&gt; &lt;nickName&gt;&lt;/nickName&gt; &lt;phoneNumber&gt;11111&lt;/phoneNumber&gt; &lt;homeNumber&gt;&lt;/homeNumber&gt; &lt;mobileNumber&gt;+1-111-111-1111&lt;/mobileNumber&gt; &lt;/user&gt; &lt;/users&gt; user userName taksh </code></pre>
-4
2016-07-30T05:24:12Z
38,670,663
<p>you could check python pandas library</p> <p>you dataframe will looks something simillar to this:</p> <pre><code>df1 = pd.DataFrame( data={ "user":data1,"name":data2} ) </code></pre> <p>where data1,data2 are the list containing the result after parsing. create a data frame by parsing the file .</p> <pre><code>&gt;&gt;&gt; writer = ExcelWriter('output.xlsx') &gt;&gt;&gt; df1.to_excel(writer,'Sheet1') &gt;&gt;&gt; df2.to_excel(writer,'Sheet2') &gt;&gt;&gt; writer.save() </code></pre> <p>which will get you the excel sheet</p> <p>for parsing a xml documnet please go through this link</p> <p><a href="http://stackoverflow.com/questions/20141939/how-can-i-get-element-from-xml-file-with-attribute-having-specific-value">xml parsing</a></p>
0
2016-07-30T05:33:25Z
[ "python" ]
Regex uppercase certain letters
38,670,704
<p>I would like to use regex to uppercase the letter c in certain circumstances (e.g.) if the C is for Celsius. My regex so far:</p> <pre><code>((?!\s)[c](?=\s)|(?!\d)[c](?=\d)|[c](?=-)) </code></pre> <p>Example text:</p> <pre><code>Some plastic insert c lids were cracked, temperature was between 8c and 8.8c. </code></pre> <p>I want to capitalize all the solitary c's and the c's after the numbers. Any pointers would be helpful.</p>
-2
2016-07-30T05:40:14Z
38,670,811
<p>You need <code>(?&lt;=...)</code> instead of <code>(?!...)</code>, the former stands for <em>look behind</em> while the latter stands for <em>negative look ahead</em>, if you want to replace <code>c</code> after space or digits, then you need to use <em>look behind</em> constraint:</p> <pre><code>str1 = "Some plastic insert c lids were cracked, temperature was between 8c and 8.8c." import re re.sub(r"(?&lt;=\s)c(?=\s)|(?&lt;=\d)c", "C", str1) # 'Some plastic insert C lids were cracked, temperature was between 8C and 8.8C.' </code></pre> <p>Depending on how you define solitary, a word boundary might be better suited:</p> <pre><code>re.sub(r"\bc\b|(?&lt;=\d)c", "C", str1) # 'Some plastic insert C lids were cracked, temperature was between 8C and 8.8C.' </code></pre> <p><em>Update</em> for the case in the comment:</p> <pre><code>str2 = "Ensure that noodles soaked in water are kept at or 4 c. Noodles are moved to walk in cooler. * Ensure that perishable food is chilled rapidly as * A) temperature from 60 c-20 C must fall within two hrs" re.sub(r"\bc\b|(?&lt;=\d)c", "C", str2) # 'Ensure that noodles soaked in water are kept at or 4 C. Noodles are moved to walk in cooler. * Ensure that perishable food is chilled rapidly as * A) temperature from 60 C-20 C must fall within two hrs' </code></pre>
0
2016-07-30T05:54:04Z
[ "python", "regex" ]
Looping through user input and adding it to a list of unknown length
38,670,710
<p>The code ask the user 5 questions and they will answer it and then those 5 answers will be one element of a new list of unknown length as <p>What I mean is I don't know how many horses the user will bet on one day. If the user bets 6 horses in one day then the new list will have have 6 elements with each element being a list of horse,stake,odds,result,book. </p> <p>So I am looking for a code which will keep adding to the new list until the user says "No" to the question "Would you like to add a selection?"</p> <pre><code>while True: add_selection =raw_input("Would you like to add a selection?") if add_selection == "Yes": selection = raw_input('Horse: ') print selection stake = float(raw_input('Stake: ')) print stake odds = float(raw_input('Odds: ')) print odds result = ["Win", "Lose", "Refund"] result = (raw_input('Result: ')) if result == "Win": print stake * odds elif result == "Lose": print 0 elif result == "Refund": print stake book = raw_input('Book: ') print book list=[selection,stake,odds,result,book] print list elif add_selection == "No": return 0 </code></pre> <p>Sorry if this is too much but I tired to work it out all day using google and browsing this website but I don't know how to do it. </p>
0
2016-07-30T05:41:09Z
38,670,771
<p>You add it all to some final list?</p> <pre><code>final_list = [] while True: add_selection =raw_input("Would you like to add a selection?").lower() if add_selection == "yes": selection = raw_input('Horse: ') print selection stake = float(raw_input('Stake: ')) print stake odds = float(raw_input('Odds: ')) print odds result = (raw_input('Result: ')) if result == "Win": print stake * odds elif result == "Lose": print 0 elif result == "Refund": print stake book = raw_input('Book: ') print book final_list.append([selection,stake,odds,result,book]) print final_list else: break </code></pre>
0
2016-07-30T05:49:21Z
[ "python", "list", "loops" ]
Looping through user input and adding it to a list of unknown length
38,670,710
<p>The code ask the user 5 questions and they will answer it and then those 5 answers will be one element of a new list of unknown length as <p>What I mean is I don't know how many horses the user will bet on one day. If the user bets 6 horses in one day then the new list will have have 6 elements with each element being a list of horse,stake,odds,result,book. </p> <p>So I am looking for a code which will keep adding to the new list until the user says "No" to the question "Would you like to add a selection?"</p> <pre><code>while True: add_selection =raw_input("Would you like to add a selection?") if add_selection == "Yes": selection = raw_input('Horse: ') print selection stake = float(raw_input('Stake: ')) print stake odds = float(raw_input('Odds: ')) print odds result = ["Win", "Lose", "Refund"] result = (raw_input('Result: ')) if result == "Win": print stake * odds elif result == "Lose": print 0 elif result == "Refund": print stake book = raw_input('Book: ') print book list=[selection,stake,odds,result,book] print list elif add_selection == "No": return 0 </code></pre> <p>Sorry if this is too much but I tired to work it out all day using google and browsing this website but I don't know how to do it. </p>
0
2016-07-30T05:41:09Z
38,670,875
<p>Create a list outside the scope of the loop then append to it based on user input. When they enter "No", leave the loop with <code>break</code> if you want to stay in the function, <code>return</code> if you want to leave the function.</p> <p>You need to declare <code>inputs</code> before the loop in order to access it outside of the loop. Otherwise, it won't be "in scope" anymore and accessible to code. Instead of just printing inputs, you'll probably want to return it to whatever function is calling your menu.</p> <pre><code>inputs = [] while True: add_selection =raw_input("Would you like to add a selection?") if add_selection == "Yes": selection = raw_input('Horse: ') print selection stake = float(raw_input('Stake: ')) print stake odds = float(raw_input('Odds: ')) print odds result = ["Win", "Lose", "Refund"] result = (raw_input('Result: ')) if result == "Win": print stake * odds elif result == "Lose": print 0 elif result == "Refund": print stake book = raw_input('Book: ') print book list=[selection,stake,odds,result,book] print list inputs.append(list) elif add_selection == "No": break print inputs </code></pre> <p><a href="https://ideone.com/s9fHXo" rel="nofollow">https://ideone.com/s9fHXo</a></p>
0
2016-07-30T06:04:55Z
[ "python", "list", "loops" ]
Python dictionary.get() default return not working
38,670,755
<p>I'm trying to create a dictionary from string to list of strings. So I thought I would use dict.get()'s default value keyword argument as such:</p> <pre><code>read_failures = {} for filename in files: try: // open file except Exception as e: error = type(e).__name__ read_failures[error] = read_failures.get(error, []).append(filename) </code></pre> <p>So by the end I want read_failures to look something like: </p> <pre><code>{'UnicodeDecodeError':['234.txt', '237.txt', '593.txt'], 'FileNotFoundError': ['987.txt']} </code></pre> <p>I have to use the get() command because I get a KeyError otherwise and this should technically work. If I do this in the interpreter line by line it works. But for some reason, in the script, the read_failures.get(error, []) method is returning None as default instead of the empty list I've specified. Is there perhaps a version of Python where the default get return wasn't a thing?</p> <p>Thanks!</p>
0
2016-07-30T05:47:35Z
38,670,837
<p>So this</p> <pre><code>read_failures[error] = read_failures.get(error, []).append(filename) </code></pre> <p>sets the value of read_failures[error] to None because the .append method returns a None. Simple fix is to change this to:</p> <pre><code>read_failures[error] = read_failures.get(error, []) + [filename] </code></pre> <p>Thank you user2357112!</p>
0
2016-07-30T05:58:17Z
[ "python" ]
Python dictionary.get() default return not working
38,670,755
<p>I'm trying to create a dictionary from string to list of strings. So I thought I would use dict.get()'s default value keyword argument as such:</p> <pre><code>read_failures = {} for filename in files: try: // open file except Exception as e: error = type(e).__name__ read_failures[error] = read_failures.get(error, []).append(filename) </code></pre> <p>So by the end I want read_failures to look something like: </p> <pre><code>{'UnicodeDecodeError':['234.txt', '237.txt', '593.txt'], 'FileNotFoundError': ['987.txt']} </code></pre> <p>I have to use the get() command because I get a KeyError otherwise and this should technically work. If I do this in the interpreter line by line it works. But for some reason, in the script, the read_failures.get(error, []) method is returning None as default instead of the empty list I've specified. Is there perhaps a version of Python where the default get return wasn't a thing?</p> <p>Thanks!</p>
0
2016-07-30T05:47:35Z
38,670,949
<p>As other comments and answers have pointed out, your issue is that <code>list.append</code> returns <code>None</code>, and so you can't assign the result of your call back to the dictionary. However, if the list is already in the dictionary, you don't need to reassign it, since <code>append</code> will modify it in place.</p> <p>So the question is, how can you add a new list to the dictionary only if there isn't one there already? A crude fix would be to use a separate <code>if</code> statement:</p> <pre><code>if error not in read_failures: read_failures[error] = [] read_failures[error].append(filename) </code></pre> <p>But this requires up to three lookups of the key in the dictionary, and we can do better. The <code>dict</code> class has a method named <code>setdefault</code> that checks if a given key is in the dictionary. If not, it will assign a given default value to the key. And in any case, the value in the dictionary will be returned. So, we can do the whole thing in one line:</p> <pre><code>read_failures.setdefault(error, []).append(filename) </code></pre> <p>Another alternative solution would be to use a <code>defaultdict</code> object (from the <code>collections</code> module in the standard library) instead of a normal dictionary. The <code>defaultdict</code> constructor takes a <code>factory</code> argument that will be called to create a default value any time a key is requested that doesn't exist yet.</p> <p>So another implementation would be:</p> <pre><code>from collections import defaultdict read_failures = defaultdict(list) for filename in files: try: // open file except Exception as e: error = type(e).__name__ read_failures[error].append(filename) </code></pre>
2
2016-07-30T06:15:57Z
[ "python" ]
python call function in get method of dictionary instead default value
38,670,816
<p>Need some help in order to understand some things in Python and <code>get</code> dictionary method. </p> <p>Let's suppose that we have some list of dictionaries and we need to make some data transformation (e.g. get all names from all dictionaries by key <code>'name'</code>). Also I what to call some specific function <code>func(data)</code> if key <code>'name'</code> was not found in specific dict.</p> <pre><code>def func(data): # do smth with data that doesn't contain 'name' key in dict return some_data def retrieve_data(value): return ', '.join([v.get('name', func(v)) for v in value]) </code></pre> <p>This approach works rather well, but as far a I can see function <code>func</code> (from <code>retrieve_data</code>) <strong>call each time</strong>, even key <code>'name'</code> is present in dictionary.</p>
0
2016-07-30T05:54:36Z
38,670,847
<p>If you want to avoid calling <code>func</code> if the dictionary contains the value, you can use this:</p> <pre><code>def retrieve_data(value): return ', '.join([v['name'] if 'name' in v else func(v) for v in value]) </code></pre> <p>The reason <code>func</code> is called each time in your example is because it gets evaluated before <code>get</code> even gets called. </p>
2
2016-07-30T06:00:33Z
[ "python", "dictionary" ]
Make numpy matrix with insufficient length of data
38,670,880
<p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p> <p>Eg:</p> <pre><code>data = [0,4,1,3,2,5,9,6,7,8] &gt;&gt;&gt; output array([[ 0, 4, 1, 3], [ 2, 5, 9, 6], [ 7, 8, -1, -1]]) </code></pre> <p>What I thought of doing is </p> <pre><code>data += [-1]*(row*col - len(data)) output = np.array(data).reshape((row, col)) </code></pre> <p>Is there a simpler method that allows me to achieve the same result without having to modify the original data or sending in <code>data + [-1]*remaining</code> to the <code>np.array</code> function?</p>
3
2016-07-30T06:06:26Z
38,670,965
<p>I'm sure there are various ways of doing this. My first inclination is to make a <code>output</code> array filled with the 'fill', and copy the <code>data</code> to it. Since the fill is 'ragged', not a full column or row, I'd start out 1d and reshape to the final shape.</p> <pre><code>In [730]: row,col = 3,4 In [731]: data = [0,4,1,3,2,5,9,6,7,8] In [732]: output=np.zeros(row*col,dtype=int)-1 In [733]: output[:len(data)]=data In [734]: output = output.reshape(3,4) In [735]: output Out[735]: array([[ 0, 4, 1, 3], [ 2, 5, 9, 6], [ 7, 8, -1, -1]]) </code></pre> <p>Regardless of whether <code>data</code> starts as a list or a 1d array, it will have to be copied to <code>output</code>. With a change in the total number of characters we can't just reshape it.</p> <p>This isn't that different from your approach of adding the extra values via <code>[-1]*n</code>.</p> <p>There is a <code>pad</code> function, but it works on whole columns or rows, and internally is quite complex because it's written for general cases.</p>
3
2016-07-30T06:18:41Z
[ "python", "python-3.x", "numpy" ]
Make numpy matrix with insufficient length of data
38,670,880
<p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p> <p>Eg:</p> <pre><code>data = [0,4,1,3,2,5,9,6,7,8] &gt;&gt;&gt; output array([[ 0, 4, 1, 3], [ 2, 5, 9, 6], [ 7, 8, -1, -1]]) </code></pre> <p>What I thought of doing is </p> <pre><code>data += [-1]*(row*col - len(data)) output = np.array(data).reshape((row, col)) </code></pre> <p>Is there a simpler method that allows me to achieve the same result without having to modify the original data or sending in <code>data + [-1]*remaining</code> to the <code>np.array</code> function?</p>
3
2016-07-30T06:06:26Z
38,670,966
<p>Here is one option using <code>numpy.pad</code>, pad the data with -1 at the end of array and then reshape it:</p> <pre><code>import numpy as np data = [0,4,1,3,2,5,9,6,7,8] row, col = 3, 4 np.pad(data, (0, row * col - len(data)), 'constant', constant_values = -1).reshape(row, col) # array([[ 0, 4, 1, 3], # [ 2, 5, 9, 6], # [ 7, 8, -1, -1]]) </code></pre>
1
2016-07-30T06:18:47Z
[ "python", "python-3.x", "numpy" ]
Make numpy matrix with insufficient length of data
38,670,880
<p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p> <p>Eg:</p> <pre><code>data = [0,4,1,3,2,5,9,6,7,8] &gt;&gt;&gt; output array([[ 0, 4, 1, 3], [ 2, 5, 9, 6], [ 7, 8, -1, -1]]) </code></pre> <p>What I thought of doing is </p> <pre><code>data += [-1]*(row*col - len(data)) output = np.array(data).reshape((row, col)) </code></pre> <p>Is there a simpler method that allows me to achieve the same result without having to modify the original data or sending in <code>data + [-1]*remaining</code> to the <code>np.array</code> function?</p>
3
2016-07-30T06:06:26Z
38,670,981
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html" rel="nofollow"><code>np.ndarray.flat</code></a> to index into the flattened version of the array.</p> <pre><code>data = [0, 4, 1, 3, 2, 5, 9, 6, 7, 8] default_value = -1 desired_shape = (3, 4) output = default_value * np.ones(desired_shape) output.flat[:len(data)] = data # output is now: # array([[ 0., 4., 1., 3.], # [ 2., 5., 9., 6.], # [ 7., 8., -1., -1.]]) </code></pre> <p>As hpaulj says, the extra copy is really hard to avoid.</p> <p>If you are reading <code>data</code> from a file somehow, you could read it into the flattened array directly, either using <code>flat</code>, or by reshaping the array afterward. Then the data gets directly loaded into the array with the desired shape.</p>
3
2016-07-30T06:20:12Z
[ "python", "python-3.x", "numpy" ]
Make numpy matrix with insufficient length of data
38,670,880
<p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p> <p>Eg:</p> <pre><code>data = [0,4,1,3,2,5,9,6,7,8] &gt;&gt;&gt; output array([[ 0, 4, 1, 3], [ 2, 5, 9, 6], [ 7, 8, -1, -1]]) </code></pre> <p>What I thought of doing is </p> <pre><code>data += [-1]*(row*col - len(data)) output = np.array(data).reshape((row, col)) </code></pre> <p>Is there a simpler method that allows me to achieve the same result without having to modify the original data or sending in <code>data + [-1]*remaining</code> to the <code>np.array</code> function?</p>
3
2016-07-30T06:06:26Z
38,671,684
<p>I checked the solutions given based on speed. The tests was done using IPython 4.2.0 with Python 3.5.2|Anaconda 4.1.1 (64-bit). The data array starts with 100,000 elements. The new dimentions are 150,000 x 150,000.</p> <h3>M. Klugerford's solution (icreasing the data and reshaping):</h3> <pre><code>%timeit data = [x for x in range(100000)]; col=15000; row=15000; data+= [-1]*(row*col-len(data)); output = np.array(data).reshape((row, col)) </code></pre> <blockquote> <p>1 loop, best of 3: 38.8 s per loop</p> </blockquote> <h3>Psidom's solution (using np.pad):</h3> <pre><code> %timeit import numpy as np; data = [x for x in range(100000)]; col=15000; row=15000; np.pad(data, (0, row * col - len(data)), 'constant', constant_values = -1).reshape(row, col) </code></pre> <blockquote> <p>1 loop, best of 3: 20.4 s per loop</p> </blockquote> <h3>Praveen's solution (using np.ndarray.flat):</h3> <pre><code>%timeit import numpy as np; data = [x for x in range(100000)]; col=15000; row=15000; output = -1 * np.ones((col, row)); output.flat[:len(data)] = data </code></pre> <blockquote> <p>1 loop, best of 3: 12.2 s per loop</p> </blockquote> <h3>hpaulj's solution (create output first; coping later and <strong>best solution so far!!</strong>):</h3> <pre><code>%timeit import numpy as np; data = [x for x in range(100000)]; col=15000; row=15000; output=np.zeros(row*col,dtype=int)-1; output[:len(data)]=data; output = output.reshape(col, row) </code></pre> <blockquote> <p>1 loop, best of 3: 6.28 s per loop</p> </blockquote>
3
2016-07-30T07:55:04Z
[ "python", "python-3.x", "numpy" ]
Datetime picker and modal conflict angular ui bootstrap
38,670,916
<p>I have a problem, in one form, I have to create an angular pop up form so I use this tutorial <a href="https://angular-ui.github.io/bootstrap/#/modal" rel="nofollow">modal</a> and it worked well however my other field which is the date time picker got affected.</p> <p>this is my code where I use modal:</p> <pre><code>&lt;script src="{% static "ui-bootstrap-tpls-0.13.3.js" %}"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8"&gt; angular.module('actinbox.web').controller('ModalDemoCtrl', function ($scope, $modal) { $scope.delivery={ linktext: "{{form.delivery.value}}", hyperlink: "{{form.delivery.value}}" }; $scope.animationsEnabled = true; $scope.open = function () { var modalInstance = $modal.open({ animation: $scope.animationsEnabled, templateUrl: 'taskDelivery', controller: 'ModalInstanceCtrl', size: 'sm', resolve: { linktext: function () { return $scope.linktext; },hyperlink: function () { return $scope.hyperlink; } } }); modalInstance.result.then(function (delivery) { $scope.delivery= { linktext: delivery.linktext, hyperlink: delivery.hyperlink }; }); }; $scope.toggleAnimation = function () { $scope.animationsEnabled = !$scope.animationsEnabled; }; }); angular.module('actinbox.web').controller('ModalInstanceCtrl', function ($scope, $modalInstance) { $scope.delivery = { linktext: "{{form.delivery.value}}", hyperlink: "{{form.delivery.value}}" }; $scope.ok = function () { $modalInstance.close({ linktext:$scope.delivery.linktext, hyperlink:$scope.delivery.hyperlink }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }); &lt;/script&gt; &lt;script type="text/ng-template" id="taskDelivery"&gt; &lt;div class="modal-header"&gt; &lt;h3 class="modal-title"&gt;Insert Link Here&lt;/h3&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; Link Text: &lt;input type="text" ng-model="delivery.linktext"&gt; &lt;br&gt; Hyper Link: &lt;input type="text" ng-model="delivery.hyperlink"&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button class="btn-cancel" type="button" ng-click="ok()"&gt;OK&lt;/button&gt; &lt;button class="btn-save" type="button" ng-click="cancel()"&gt;Cancel&lt;/button&gt; &lt;/div&gt; &lt;/script&gt; &lt;div ng-controller="ModalDemoCtrl"&gt; &lt;div class="profileform"&gt; &lt;div class="profile-detail"&gt; &lt;label for="{{ field.id_for_label }}"&gt;{{ field.label_tag }}&lt;/label&gt; &lt;div class="errormessage"&gt; {% if field.errors %} {{ field.errors }}&lt;i class="fa fa-exclamation-circle"&gt;&lt;/i&gt; {% endif %} &lt;/div&gt; &lt;input type="text" value="{$ delivery.linktext $}" name="{{field.name}}" style="width:100px;" disabled&gt; &lt;input type="hidden" value="{$ delivery.linktext $}" name="{{field.name}}" style="width:100px;"&gt; &lt;input type="text" value="{$ delivery.hyperlink $}" name="linknathis" style="width:200px;" disabled&gt; &lt;button type="button" ng-click="open()"&gt;Set Delivery&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is already working.. but my datetimepicker does not work but it does if I delete <code>&lt;script src="{% static "ui-bootstrap-tpls-0.13.3.js" %}"&gt;&lt;/script&gt;</code> </p> <p>This is my datetimepicker script:</p> <pre><code>&lt;script type="text/javascript" charset="utf-8"&gt; angular.module('actinbox.web').controller('DateTimepicker_{{ field.id_for_label }}', function($scope) { // Set Javascript's Date Object value $scope.selectedDateTime = new Date('{{field.value|date:"Y/m/d H:i:s"}}'); }); &lt;/script&gt; &lt;div class="profileform" ng-controller="DateTimepicker_{{ field.id_for_label }}"&gt; &lt;div class="profile-detail"&gt; &lt;div class="errormessage" style="margin-top:-10px;"&gt; {% if field.errors %} {{ field.errors }}&lt;i class="fa fa-exclamation-circle"&gt;&lt;/i&gt; {% endif %} &lt;/div&gt; &lt;label for="{{ field.id_for_label }}"&gt;{{ field.label_tag }}&lt;/label&gt; &lt;!--Hidden field for transfer date &amp; time--&gt; &lt;input type ="hidden" id="{{field.id_for_label}}" name="{{field.html_name}}" value="{$selectedDateTime|date:'yyyy-MM-dd HH:mm:ss'$}"&gt; &lt;!--Field for select date--&gt; &lt;input style="width: 100px; padding-left: 5px;" type="text" ng-model="selectedDateTime" data-date-format="yyyy-MM-dd" data-autoclose="1" bs-datepicker&gt; &lt;!--Field for select time--&gt; &lt;input style="width: 100px; padding-left: 5px;" type="text" ng-model="selectedDateTime" data-time-format="HH:mm" data-autoclose="1" data-length="1" bs-timepicker&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Do you think I am having conflicts here? </p> <pre><code>&lt;link rel="stylesheet" href="{% static "font-awesome-4.5.0/css/font-awesome.min.css" %}"&gt; &lt;link rel="stylesheet" href="{% static "bootstrap-3.3.5-dist/css/bootstrap.min.css" %}"&gt; &lt;link rel="stylesheet" href="{% static "bootstrap-additions-0.3.1/bootstrap-additions.min.css" %}"&gt; &lt;script src="{% static "angularjs-1.4.3/angular.min.js" %}"&gt;&lt;/script&gt; &lt;script src="{% static "angularjs-1.4.3/angular-animate.min.js" %}"&gt;&lt;/script&gt; &lt;script src="{% static "angularjs-1.4.3/angular-sanitize.min.js" %}"&gt;&lt;/script&gt; &lt;script src="{% static "angular-strap-2.3.1-dist/angular-strap.js" %}"&gt;&lt;/script&gt; &lt;script src="{% static "angular-strap-2.3.1-dist/angular-strap.tpl.js" %}"&gt;&lt;/script&gt; &lt;script src="{% static "ui-bootstrap-custom-tpls-0.13.3.js" %}"&gt;&lt;/script&gt; &lt;script src="{% static "ui-bootstrap-tpls-0.13.3.js" %}"&gt;&lt;/script&gt; </code></pre>
0
2016-07-30T06:11:57Z
38,671,244
<p>I see 2 problems with your approach:</p> <ol> <li><p>Using the multiple versions of a library will not work if it uses the same namespacing, which is the case. So either check, if the date-picker works with the latest ui-boostrap version es well. Or downgrade your code to the ui-bootstrap version that is required by the datepicker.</p></li> <li><p>I might be wrong, but angular.module('actinbox.web').controller('DateTimepicker_{{ field.id_for_label }}' will b executed after angular bootstrap. Since angular, by default, does not support the lazy loading of modules. I do not think this will work. Try to test it by adding a console.log output to the controller and see if it ever works.</p></li> </ol>
0
2016-07-30T06:55:57Z
[ "python", "angularjs", "django" ]
How to test if a class had explicietly defined a __gt__?
38,671,212
<p>Is there a way to test whether a costume class had explicitly defined an attribute like <code>__gt__</code>? To put things in context consider these two classes:</p> <pre><code>class myclass1: def __init__(self, val): self.val = val def __gt__(self, other): if type(other) is int: return self.val &gt; other else: return self.val &gt; other.val class myclass2: def __init__(self, val): self.val = val </code></pre> <p>Since I've defined an inequality attribute only for <code>myclass1</code> and not for <code>myclass2</code> calling </p> <pre><code>x1 = myclass1(5); x2 = myclass2(2) x1 &gt; x2 x2 &lt; x1 </code></pre> <p>will use <code>myclass1.__gt__</code> in both cases. Had I defined <code>myclass2.__lt__</code>, the last line would have invoked it. But I didn't. So <code>x1</code>'s <code>__gt__</code> takes hold in both calls. I think I understand this (but comments are welcomed).</p> <p>So my question: Is there a way to know which inequalities had been explicitly defined for a custom class? Because</p> <pre><code>hasattr(x2, '__gt__') </code></pre> <p>returns <code>True</code> anyway.</p>
1
2016-07-30T06:51:53Z
38,671,258
<p>You can check inside the <code>__dict__</code> for each class:</p> <pre><code>'__gt__' in x2.__class__.__dict__ Out[23]: False '__gt__' in x1.__class__.__dict__ Out[24]: True </code></pre> <p>Or, using built-ins in order to not rely on dunders:</p> <pre><code>'__gt__' in vars(type(x1)) Out[31]: True '__gt__' in vars(type(x2)) Out[32]: False </code></pre>
2
2016-07-30T06:57:30Z
[ "python", "python-3.x" ]
Send email from python webapp2 Google App Engine
38,671,257
<p>i am trying to send an email from my application. The code run successfully with out error. But it do not send the email. It show this message on Console. </p> <pre><code>You are not currently sending out real email. If you have sendmail installed you can use it by using the server with --enable_sendmail </code></pre> <p>The sample code provided by the google is:</p> <pre><code>message = mail.EmailMessage( sender="shaizi9687@gmail.com", subject="Your account has been approved") message.to = "ABC &lt;shahzebakram@hotmail.com&gt;" message.body = """Dear Albert: Your example.com account has been approved. You can now visit http://www.example.com/ and sign in using your Google Account to access new features. Please let us know if you have any questions. The example.com Team """ message.send() </code></pre>
2
2016-07-30T06:57:27Z
38,674,023
<p>That's because the dev_appserver by default doesn't send out real mails.</p> <p>Email sending <strong>will work when you push to a live server</strong>, for eg:</p> <pre><code>appcfg update /path/to/app/ </code></pre> <p>But like the error message points out, you'll have to use the <code>--enable_sendmail</code> flag if you have sendmail installed on your system or use smtp flags, for eg:</p> <pre><code>dev_appserver /path/to/app/ --enable_sendmail=yes </code></pre> <p>or another eg using gmail as smtp provider</p> <pre><code>dev_appserver /path/to/app --smtp_host=smtp.gmail.com --smtp_port=465 \ --smtp_user=user@gmail.com --smtp_password=password </code></pre> <p>More explanation here: <a href="https://cloud.google.com/appengine/docs/python/mail/" rel="nofollow">https://cloud.google.com/appengine/docs/python/mail/</a></p> <blockquote> <p><strong>Mail and the development server</strong></p> <p>The development server can be configured to send email messages directly from your computer when you test a feature of your app that sends messages. You can configure the development server to use an SMTP server of your choice. Alternatively, you can tell the development server to use Sendmail, if Sendmail is installed on your computer and set up for sending email.</p> <p>If you do not configure an SMTP server or enable Sendmail, when your app calls the Mail service, the development server will log the contents of the message. The message will not actually be sent.</p> </blockquote>
0
2016-07-30T12:34:02Z
[ "python", "email", "google-app-engine", "webapp2" ]
How to write a python script to print names of all folders and subfolders in a directory?
38,671,269
<p>im fairly new to python.i know how to list directories etc but how to i get only the name of folder and its subfolders?</p> <p>Thanks</p>
-8
2016-07-30T06:59:04Z
38,671,473
<pre><code>import os for root, dirs, files in os.walk(".", topdown=False): for name in files: print(os.path.join(root, name)) for name in dirs: print(os.path.join(root, name)) </code></pre>
1
2016-07-30T07:25:47Z
[ "python", "folders" ]
Does PyMySQL support Prepared Statements?
38,671,286
<p>Does PyMySQL support prepared statements? I am trying to connect to MySQL from a python module.</p> <p>I have checked documentation at <a href="http://pymysql.readthedocs.io" rel="nofollow" title="PyMySQL Documentation">http://pymysql.readthedocs.io</a> and didn't find anything useful.</p> <p>No luck on skimming the source code either.</p>
0
2016-07-30T07:02:27Z
38,671,547
<p>Yes it does. Please check the example below. <pre><code>// Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } // prepare and bind $stmt = $conn-&gt;prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); $stmt-&gt;bind_param("sss", $firstname, $lastname, $email); // set parameters and execute $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt-&gt;execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt-&gt;execute(); $firstname = "Julie"; $lastname = "Dooley"; $email = "julie@example.com"; $stmt-&gt;execute(); echo "New records created successfully"; $stmt-&gt;close(); $conn-&gt;close(); ?&gt; </code></pre> <p>Code lines to explain from the example above:</p> <pre><code>"INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)" </code></pre> <p>In this SQL, used insert a question mark (?) where we want to substitute in an integer, string, double or blob value.</p> <p>Then, have a look at the bind_param() function:</p> <pre><code>$stmt-&gt;bind_param("sss", $firstname, $lastname, $email); </code></pre> <p>This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.</p> <p>The argument may be one of four types:</p> <pre><code>i - integer d - double s - string b - BLOB </code></pre>
0
2016-07-30T07:36:35Z
[ "python", "pymysql" ]
Pandas dataframe: Getting row indices from criteria 1, sorted by criteria 2
38,671,386
<p>I have data frames with the following structure:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) Col1 Col2 Col3 Col4 R1 4 10 100 AAA R2 5 20 50 BBB R3 6 30 -30 AAA R4 7 40 -50 CCC </code></pre> <p>I know how to get the row indices from the rows in which <code>Col2</code> lies between 10 and 40:</p> <pre><code>indeces = (df.Col2 &gt; 10) &amp; (df.Col2 &lt; 40) </code></pre> <p>However, how could I, for example, get those indices sorted by the values in <code>Col4</code>?</p>
2
2016-07-30T07:15:32Z
38,671,561
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>:</p> <pre><code>df[indeces].sort_values(['Col4']) Col1 Col2 Col3 Col4 R3 6 30 -30 AAA R2 5 20 50 BBB </code></pre>
2
2016-07-30T07:39:26Z
[ "python", "pandas", "numpy", "dataframe" ]
TutorialsPoint - Flask – SQLAlchemy not working
38,671,408
<p>I did all that was stated on tutorial point (<strong>just copied and pasted</strong>), but when I tried to add a student entry,i.e. ‘Add Student’ it gives</p> <p>Bad Request The browser (or proxy) sent a request that this server could not understand.</p> <p>Please advise if there is anything wrong with the tutorial.</p> <p>It failed at this line within def new(), in app.py:</p> <pre><code> student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) </code></pre> <p>Whoever is flagging this down. Note that it is the tutorial that is filled with <strong>typos and wrong indentations</strong>. I am only a student. Shut this down and I will learn nothing.</p> <p>Ref: <a href="http://www.tutorialspoint.com/flask/flask_sqlalchemy.htm" rel="nofollow">http://www.tutorialspoint.com/flask/flask_sqlalchemy.htm</a></p> <pre><code>from flask import Flask, request, flash, url_for, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3' app.config['SECRET_KEY'] = "random string" db = SQLAlchemy(app) class Students(db.Model): id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr,pin): self.name = name self.city = city self.addr = addr self.pin = pin @app.route('/') def show_all(): return render_template('show_all.html', Students = Students.query.all() ) @app.route('/new', methods = ['GET', 'POST']) def new(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr']: flash('Please enter all the fields', 'error') else: print "1"; student = Students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) print "1"; db.session.add(student) print "1"; db.session.commit() print "1"; flash('Record was successfully added') print "=======&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"; return redirect(url_for('show_all')) return render_template('new.html') if __name__ == '__main__': db.create_all() app.run(debug = True) </code></pre>
-2
2016-07-30T07:17:49Z
38,671,583
<p>The tutorial has an indentation problem in the student class. The constructor code should be indented one level so it becomes a method of the student class.</p> <p>Corrected code: (note the indent of "def <strong>init</strong>(self, name, city, addr,pin):" and the code below)</p> <pre><code>class students(db.Model): id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr,pin): self.name = name self.city = city self.addr = addr self.pin = pin </code></pre> <p>The reason is, if that indent is not there, python will not see this function as a constructor of the student class. So the constructor with the matching number of arguments is not found, resulting in the error.</p>
3
2016-07-30T07:41:54Z
[ "python", "sqlite", "flask", "sqlalchemy" ]
TutorialsPoint - Flask – SQLAlchemy not working
38,671,408
<p>I did all that was stated on tutorial point (<strong>just copied and pasted</strong>), but when I tried to add a student entry,i.e. ‘Add Student’ it gives</p> <p>Bad Request The browser (or proxy) sent a request that this server could not understand.</p> <p>Please advise if there is anything wrong with the tutorial.</p> <p>It failed at this line within def new(), in app.py:</p> <pre><code> student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) </code></pre> <p>Whoever is flagging this down. Note that it is the tutorial that is filled with <strong>typos and wrong indentations</strong>. I am only a student. Shut this down and I will learn nothing.</p> <p>Ref: <a href="http://www.tutorialspoint.com/flask/flask_sqlalchemy.htm" rel="nofollow">http://www.tutorialspoint.com/flask/flask_sqlalchemy.htm</a></p> <pre><code>from flask import Flask, request, flash, url_for, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3' app.config['SECRET_KEY'] = "random string" db = SQLAlchemy(app) class Students(db.Model): id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr,pin): self.name = name self.city = city self.addr = addr self.pin = pin @app.route('/') def show_all(): return render_template('show_all.html', Students = Students.query.all() ) @app.route('/new', methods = ['GET', 'POST']) def new(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr']: flash('Please enter all the fields', 'error') else: print "1"; student = Students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) print "1"; db.session.add(student) print "1"; db.session.commit() print "1"; flash('Record was successfully added') print "=======&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"; return redirect(url_for('show_all')) return render_template('new.html') if __name__ == '__main__': db.create_all() app.run(debug = True) </code></pre>
-2
2016-07-30T07:17:49Z
38,671,942
<p>It's not following the <a href="https://www.python.org/dev/peps/pep-0008/#class-names" rel="nofollow">class naming</a> convention. The student class should use <a href="https://en.wikipedia.org/wiki/CamelCase" rel="nofollow">Camel case</a>. Try this:</p> <pre><code>student = Students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) </code></pre> <p>The SQLAlchemy model should also follow the same, Students not students.</p> <pre><code>class Students(db.Model): id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) </code></pre> <p><strong>Edit</strong><br> Given Iron Fist's <a href="http://stackoverflow.com/questions/38671408/tutorialspoint-flask-sqlalchemy-not-working/38671942?noredirect=1#comment64724357_38671408">comment</a> that the same code is running okay for him, its very likely that there is a mistake or typo in your code for creating a new student object. Even if you have copy pasted the code, an error may occur when typing the code assuming you did not use CTRL-V or when pasting it. According to the Flask docs:</p> <blockquote> <p>What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. You can catch it like a standard KeyError but if you don’t do that, a HTTP 400 Bad Request error page is shown instead. So for many situations you don’t have to deal with that problem.</p> </blockquote> <p>Therefore if @IronFist ran the same code without a problem, but for you its returning a bad response error which as explained above is as a result of a missing key in the form, then its most likely a mistake on the code you are running. Also read <a href="http://stackoverflow.com/questions/14105452/what-is-the-cause-of-the-bad-request-error-when-submitting-form-in-flask-applica">this</a> and <a href="http://stackoverflow.com/questions/8552675/form-sending-error-flask">this</a> they are similar to your question.</p>
0
2016-07-30T08:26:01Z
[ "python", "sqlite", "flask", "sqlalchemy" ]
Pandas idxmax() not working as expected
38,671,448
<p>Suppose I have the following DataFrame <code>Q_df</code>:</p> <pre><code> (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2) (0, 0) 0.000 0.00 0.0 0.64 0.000 0.0 0.512 0.000 0.0 (0, 1) 0.000 0.00 0.8 0.00 0.512 0.0 0.000 0.512 0.0 (0, 2) 0.000 0.64 0.0 0.00 0.000 0.8 0.000 0.000 1.0 (1, 0) 0.512 0.00 0.0 0.00 0.000 0.8 0.512 0.000 0.0 (1, 1) 0.000 0.64 0.0 0.00 0.000 0.0 0.000 0.512 0.0 (1, 2) 0.000 0.00 0.8 0.64 0.000 0.0 0.000 0.000 1.0 (2, 0) 0.512 0.00 0.0 0.64 0.000 0.0 0.000 0.512 0.0 (2, 1) 0.000 0.64 0.0 0.00 0.512 0.0 0.512 0.000 0.0 (2, 2) 0.000 0.00 0.8 0.00 0.000 0.8 0.000 0.000 0.0 </code></pre> <p>which is generated using the following code:</p> <pre><code>import numpy as np import pandas as pd states = list(itertools.product(range(3), repeat=2)) Q = np.array([[0.000,0.000,0.000,0.640,0.000,0.000,0.512,0.000,0.000], [0.000,0.000,0.800,0.000,0.512,0.000,0.000,0.512,0.000], [0.000,0.640,0.000,0.000,0.000,0.800,0.000,0.000,1.000], [0.512,0.000,0.000,0.000,0.000,0.800,0.512,0.000,0.000], [0.000,0.640,0.000,0.000,0.000,0.000,0.000,0.512,0.000], [0.000,0.000,0.800,0.640,0.000,0.000,0.000,0.000,1.000], [0.512,0.000,0.000,0.640,0.000,0.000,0.000,0.512,0.000], [0.000,0.640,0.000,0.000,0.512,0.000,0.512,0.000,0.000], [0.000,0.000,0.800,0.000,0.000,0.800,0.000,0.000,0.000]]) Q_df = pd.DataFrame(index=states, columns=states, data=Q) </code></pre> <p>For each row of Q, I would like to get the column name corresponding to the maximum value in the row. If I try</p> <pre><code>policy = Q_df.idxmax() </code></pre> <p>then the resulting Series looks like this:</p> <pre><code>(0, 0) (1, 0) (0, 1) (0, 2) (0, 2) (0, 1) (1, 0) (0, 0) (1, 1) (0, 1) (1, 2) (0, 2) (2, 0) (0, 0) (2, 1) (0, 1) (2, 2) (0, 2) </code></pre> <p>The first row looks OK: the maximum element of the first row is <code>0.64</code> and occurs in column <code>(1,0)</code>. So does the second. For the third row, however, the maximum element is <code>0.8</code> and occurs in column <code>(1,2)</code>, so I would expect the corresponding value in <code>policy</code> to be <code>(1,2)</code>, not <code>(0,1)</code>.</p> <p>Any idea what is going wrong here?</p>
0
2016-07-30T07:22:20Z
38,671,506
<p>IIUC, you can use <code>axis=1</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow"><code>idxmax</code></a>:</p> <pre><code>policy = Q_df.idxmax(axis=1) (0, 0) (1, 0) (0, 1) (0, 2) (0, 2) (2, 2) (1, 0) (1, 2) (1, 1) (0, 1) (1, 2) (2, 2) (2, 0) (1, 0) (2, 1) (0, 1) (2, 2) (0, 2) dtype: object </code></pre>
1
2016-07-30T07:29:07Z
[ "python", "pandas" ]
How to install NS-3 simulator correctly using cygwin on windows 7
38,671,465
<p>I need to run NS-3 simulator on my windows 7 so I installed cygwin and with devel, python and utils packages. I got a problem when I run <code>./build.py</code> command as the following : </p> <pre><code>Traceback (most recent call last): File "./build.py", line 10, in &lt;module&gt; from util import run_command, fatal, CommandError File "/home/user-PC/ns-allinone-3.25/util.py", line 3, in &lt;module&gt; import subprocess File "/usr/lib/python2.7/subprocess.py", line 430, in &lt;module&gt; import pickle File "/usr/lib/python2.7/pickle.py", line 1266, in &lt;module&gt; import binascii as _binascii ImportError: No such file or directory </code></pre> <p>Note that I changed directory to the directory that contains the file of build.py and other files of ns-3 in the directory of <code>{system root}/cygwin/home/user-PC</code>. </p> <p>in my ns-3.25 folder, I have the following files:</p> <p>AUTHORS , doc, Makefile, scratch, testpy.supp, VERSION, waf-tools bindings, examples, README, src, utils, waf, wscript CHANGES.html, LICENSE, RELEASE_NOTES, test.py, utils.py, waf.bat, wutils.py.</p> <p>While in the main folder of this release of ns-3, I have the following including the folder of ns-3.25:</p> <p>bake, constants.pyc, pybindgen-0.17.0.post49+ng0e4e3bc, util.pyc, build.py, netanim-3.107, README, constants.py, ns-3.25, util.py.</p> <p>I tried this command <code>python -v build.py |&amp; tee build.log</code> and got the following: </p> <pre><code>user@user-PC /home/user-PC/ns-allinone-3.25 $ python -v build.py |&amp; tee build.log # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/lib/python2.7/site.pyc matches /usr/lib/python2.7/site.py import site # precompiled from /usr/lib/python2.7/site.pyc # /usr/lib/python2.7/os.pyc matches /usr/lib/python2.7/os.py import os # precompiled from /usr/lib/python2.7/os.pyc import errno # builtin import posix # builtin # /usr/lib/python2.7/posixpath.pyc matches /usr/lib/python2.7/posixpath.py import posixpath # precompiled from /usr/lib/python2.7/posixpath.pyc # /usr/lib/python2.7/stat.pyc matches /usr/lib/python2.7/stat.py import stat # precompiled from /usr/lib/python2.7/stat.pyc # /usr/lib/python2.7/genericpath.pyc matches /usr/lib/python2.7/genericpath.py import genericpath # precompiled from /usr/lib/python2.7/genericpath.pyc # /usr/lib/python2.7/warnings.pyc matches /usr/lib/python2.7/warnings.py import warnings # precompiled from /usr/lib/python2.7/warnings.pyc # /usr/lib/python2.7/linecache.pyc matches /usr/lib/python2.7/linecache.py import linecache # precompiled from /usr/lib/python2.7/linecache.pyc # /usr/lib/python2.7/types.pyc matches /usr/lib/python2.7/types.py import types # precompiled from /usr/lib/python2.7/types.pyc # /usr/lib/python2.7/UserDict.pyc matches /usr/lib/python2.7/UserDict.py import UserDict # precompiled from /usr/lib/python2.7/UserDict.pyc # /usr/lib/python2.7/_abcoll.pyc matches /usr/lib/python2.7/_abcoll.py import _abcoll # precompiled from /usr/lib/python2.7/_abcoll.pyc # /usr/lib/python2.7/abc.pyc matches /usr/lib/python2.7/abc.py import abc # precompiled from /usr/lib/python2.7/abc.pyc # /usr/lib/python2.7/_weakrefset.pyc matches /usr/lib/python2.7/_weakrefset.py import _weakrefset # precompiled from /usr/lib/python2.7/_weakrefset.pyc import _weakref # builtin # /usr/lib/python2.7/copy_reg.pyc matches /usr/lib/python2.7/copy_reg.py import copy_reg # precompiled from /usr/lib/python2.7/copy_reg.pyc # /usr/lib/python2.7/traceback.pyc matches /usr/lib/python2.7/traceback.py import traceback # precompiled from /usr/lib/python2.7/traceback.pyc # /usr/lib/python2.7/sysconfig.pyc matches /usr/lib/python2.7/sysconfig.py import sysconfig # precompiled from /usr/lib/python2.7/sysconfig.pyc # /usr/lib/python2.7/re.pyc matches /usr/lib/python2.7/re.py import re # precompiled from /usr/lib/python2.7/re.pyc # /usr/lib/python2.7/sre_compile.pyc matches /usr/lib/python2.7/sre_compile.py import sre_compile # precompiled from /usr/lib/python2.7/sre_compile.pyc import _sre # builtin # /usr/lib/python2.7/sre_parse.pyc matches /usr/lib/python2.7/sre_parse.py import sre_parse # precompiled from /usr/lib/python2.7/sre_parse.pyc # /usr/lib/python2.7/sre_constants.pyc matches /usr/lib/python2.7/sre_constants.py import sre_constants # precompiled from /usr/lib/python2.7/sre_constants.pyc dlopen("/usr/lib/python2.7/lib-dynload/_locale.dll", 2); import _locale # dynamically loaded from /usr/lib/python2.7/lib-dynload/_locale.dll # /usr/lib/python2.7/_sysconfigdata.pyc matches /usr/lib/python2.7/_sysconfigdata.py import _sysconfigdata # precompiled from /usr/lib/python2.7/_sysconfigdata.pyc # zipimport: found 90 names in /usr/lib/python2.7/site-packages/paramiko-1.16.0-py2.7.egg # zipimport: found 29 names in /usr/lib/python2.7/site-packages/ecdsa-0.13-py2.7.egg import encodings # directory /usr/lib/python2.7/encodings # /usr/lib/python2.7/encodings/__init__.pyc matches /usr/lib/python2.7/encodings/__init__.py import encodings # precompiled from /usr/lib/python2.7/encodings/__init__.pyc # /usr/lib/python2.7/codecs.pyc matches /usr/lib/python2.7/codecs.py import codecs # precompiled from /usr/lib/python2.7/codecs.pyc import _codecs # builtin # /usr/lib/python2.7/encodings/aliases.pyc matches /usr/lib/python2.7/encodings/aliases.py import encodings.aliases # precompiled from /usr/lib/python2.7/encodings/aliases.pyc # /usr/lib/python2.7/encodings/utf_8.pyc matches /usr/lib/python2.7/encodings/utf_8.py import encodings.utf_8 # precompiled from /usr/lib/python2.7/encodings/utf_8.pyc Python 2.7.10 (default, Jun 1 2015, 18:05:38) [GCC 4.9.2] on cygwin Type "help", "copyright", "credits" or "license" for more information. # /usr/lib/python2.7/__future__.pyc matches /usr/lib/python2.7/__future__.py import __future__ # precompiled from /usr/lib/python2.7/__future__.pyc # /usr/lib/python2.7/optparse.pyc matches /usr/lib/python2.7/optparse.py import optparse # precompiled from /usr/lib/python2.7/optparse.pyc # /usr/lib/python2.7/textwrap.pyc matches /usr/lib/python2.7/textwrap.py import textwrap # precompiled from /usr/lib/python2.7/textwrap.pyc # /usr/lib/python2.7/string.pyc matches /usr/lib/python2.7/string.py import string # precompiled from /usr/lib/python2.7/string.pyc dlopen("/usr/lib/python2.7/lib-dynload/strop.dll", 2); import strop # dynamically loaded from /usr/lib/python2.7/lib-dynload/strop.dll # /usr/lib/python2.7/gettext.pyc matches /usr/lib/python2.7/gettext.py import gettext # precompiled from /usr/lib/python2.7/gettext.pyc # /usr/lib/python2.7/locale.pyc matches /usr/lib/python2.7/locale.py import locale # precompiled from /usr/lib/python2.7/locale.pyc dlopen("/usr/lib/python2.7/lib-dynload/operator.dll", 2); import operator # dynamically loaded from /usr/lib/python2.7/lib-dynload/operator.dll # /usr/lib/python2.7/functools.pyc matches /usr/lib/python2.7/functools.py import functools # precompiled from /usr/lib/python2.7/functools.pyc dlopen("/usr/lib/python2.7/lib-dynload/_functools.dll", 2); import _functools # dynamically loaded from /usr/lib/python2.7/lib-dynload/_functools.dll # /usr/lib/python2.7/copy.pyc matches /usr/lib/python2.7/copy.py import copy # precompiled from /usr/lib/python2.7/copy.pyc # /usr/lib/python2.7/weakref.pyc matches /usr/lib/python2.7/weakref.py import weakref # precompiled from /usr/lib/python2.7/weakref.pyc # /usr/lib/python2.7/struct.pyc matches /usr/lib/python2.7/struct.py import struct # precompiled from /usr/lib/python2.7/struct.pyc dlopen("/usr/lib/python2.7/lib-dynload/_struct.dll", 2); import _struct # dynamically loaded from /usr/lib/python2.7/lib-dynload/_struct.dll import xml # directory /usr/lib/python2.7/xml # /usr/lib/python2.7/xml/__init__.pyc matches /usr/lib/python2.7/xml/__init__.py import xml # precompiled from /usr/lib/python2.7/xml/__init__.pyc import xml.dom # directory /usr/lib/python2.7/xml/dom # /usr/lib/python2.7/xml/dom/__init__.pyc matches /usr/lib/python2.7/xml/dom/__init__.py import xml.dom # precompiled from /usr/lib/python2.7/xml/dom/__init__.pyc # /usr/lib/python2.7/xml/dom/domreg.pyc matches /usr/lib/python2.7/xml/dom/domreg.py import xml.dom.domreg # precompiled from /usr/lib/python2.7/xml/dom/domreg.pyc # /usr/lib/python2.7/xml/dom/minicompat.pyc matches /usr/lib/python2.7/xml/dom/minicompat.py import xml.dom.minicompat # precompiled from /usr/lib/python2.7/xml/dom/minicompat.pyc # /usr/lib/python2.7/xml/dom/minidom.pyc matches /usr/lib/python2.7/xml/dom/minidom.py import xml.dom.minidom # precompiled from /usr/lib/python2.7/xml/dom/minidom.pyc # /usr/lib/python2.7/xml/dom/xmlbuilder.pyc matches /usr/lib/python2.7/xml/dom/xmlbuilder.py import xml.dom.xmlbuilder # precompiled from /usr/lib/python2.7/xml/dom/xmlbuilder.pyc # /usr/lib/python2.7/xml/dom/NodeFilter.pyc matches /usr/lib/python2.7/xml/dom/NodeFilter.py import xml.dom.NodeFilter # precompiled from /usr/lib/python2.7/xml/dom/NodeFilter.pyc # /usr/lib/python2.7/shlex.pyc matches /usr/lib/python2.7/shlex.py import shlex # precompiled from /usr/lib/python2.7/shlex.pyc # /usr/lib/python2.7/collections.pyc matches /usr/lib/python2.7/collections.py import collections # precompiled from /usr/lib/python2.7/collections.pyc dlopen("/usr/lib/python2.7/lib-dynload/_collections.dll", 2); import _collections # dynamically loaded from /usr/lib/python2.7/lib-dynload/_collections.dll # /usr/lib/python2.7/keyword.pyc matches /usr/lib/python2.7/keyword.py import keyword # precompiled from /usr/lib/python2.7/keyword.pyc # /usr/lib/python2.7/heapq.pyc matches /usr/lib/python2.7/heapq.py import heapq # precompiled from /usr/lib/python2.7/heapq.pyc dlopen("/usr/lib/python2.7/lib-dynload/itertools.dll", 2); import itertools # dynamically loaded from /usr/lib/python2.7/lib-dynload/itertools.dll dlopen("/usr/lib/python2.7/lib-dynload/_heapq.dll", 2); import _heapq # dynamically loaded from /usr/lib/python2.7/lib-dynload/_heapq.dll import thread # builtin dlopen("/usr/lib/python2.7/lib-dynload/cStringIO.dll", 2); import cStringIO # dynamically loaded from /usr/lib/python2.7/lib-dynload/cStringIO.dll # /home/user-PC/ns-allinone-3.25/constants.pyc matches /home/user-PC/ns-allinone-3.25/constants.py import constants # precompiled from /home/user-PC/ns-allinone-3.25/constants.pyc # /home/user-PC/ns-allinone-3.25/util.pyc matches /home/user-PC/ns-allinone-3.25/util.py import util # precompiled from /home/user-PC/ns-allinone-3.25/util.pyc # /usr/lib/python2.7/subprocess.pyc matches /usr/lib/python2.7/subprocess.py import subprocess # precompiled from /usr/lib/python2.7/subprocess.pyc import gc # builtin dlopen("/usr/lib/python2.7/lib-dynload/time.dll", 2); import time # dynamically loaded from /usr/lib/python2.7/lib-dynload/time.dll dlopen("/usr/lib/python2.7/lib-dynload/select.dll", 2); import select # dynamically loaded from /usr/lib/python2.7/lib-dynload/select.dll dlopen("/usr/lib/python2.7/lib-dynload/fcntl.dll", 2); import fcntl # dynamically loaded from /usr/lib/python2.7/lib-dynload/fcntl.dll # /usr/lib/python2.7/pickle.pyc matches /usr/lib/python2.7/pickle.py import pickle # precompiled from /usr/lib/python2.7/pickle.pyc import marshal # builtin dlopen("/usr/lib/python2.7/lib-dynload/binascii.dll", 2); Traceback (most recent call last): File "build.py", line 10, in &lt;module&gt; from util import run_command, fatal, CommandError File "/home/user-PC/ns-allinone-3.25/util.py", line 3, in &lt;module&gt; import subprocess File "/usr/lib/python2.7/subprocess.py", line 430, in &lt;module&gt; import pickle File "/usr/lib/python2.7/pickle.py", line 1266, in &lt;module&gt; import binascii as _binascii ImportError: No such file or directory # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type # clear sys.last_value # clear sys.last_traceback # clear sys.path_hooks # clear sys.path_importer_cache # clear sys.meta_path # clear sys.flags # clear sys.float_info # restore sys.stdin # restore sys.stdout # restore sys.stderr # cleanup __main__ # cleanup[1] cStringIO # cleanup[1] __future__ # cleanup[1] site # cleanup[1] sysconfig # cleanup[1] thread # cleanup[1] gc # cleanup[1] select # cleanup[1] abc # cleanup[1] _weakrefset # cleanup[1] gettext # cleanup[1] sre_constants # cleanup[1] constants # cleanup[1] _codecs # cleanup[1] zope # cleanup[1] collections # cleanup[1] _struct # cleanup[1] _heapq # cleanup[1] _warnings # cleanup[1] shlex # cleanup[1] fcntl # cleanup[1] zipimport # cleanup[1] _sysconfigdata # cleanup[1] optparse # cleanup[1] struct # cleanup[1] textwrap # cleanup[1] _collections # cleanup[1] strop # cleanup[1] _functools # cleanup[1] keyword # cleanup[1] signal # cleanup[1] traceback # cleanup[1] marshal # cleanup[1] itertools # cleanup[1] posix # cleanup[1] exceptions # cleanup[1] _weakref # cleanup[1] heapq # cleanup[1] locale # cleanup[1] functools # cleanup[1] encodings # cleanup[1] operator # cleanup[1] string # cleanup[1] encodings.utf_8 # cleanup[1] codecs # cleanup[1] encodings.aliases # cleanup[1] re # cleanup[1] _locale # cleanup[1] sre_compile # cleanup[1] _sre # cleanup[1] sre_parse # cleanup[2] copy_reg # cleanup[2] xml.dom # cleanup[2] xml.dom.NodeFilter # cleanup[2] xml # cleanup[2] posixpath # cleanup[2] errno # cleanup[2] _abcoll # cleanup[2] xml.dom.minicompat # cleanup[2] types # cleanup[2] genericpath # cleanup[2] stat # cleanup[2] warnings # cleanup[2] UserDict # cleanup[2] xml.dom.domreg # cleanup[2] copy # cleanup[2] os.path # cleanup[2] xml.dom.minidom # cleanup[2] weakref # cleanup[2] linecache # cleanup[2] time # cleanup[2] xml.dom.xmlbuilder # cleanup[2] os # cleanup sys # cleanup __builtin__ # cleanup ints: 726 unfreed ints # cleanup floats </code></pre> <p>Also I tried with bake and got the following: </p> <pre><code>user@user-PC /home/user-PC/ns-allinone-3.25/bake/bake $ ./Bake.py build ./Bake.py: line 26: $' \n Bake.py\n\n This is the main Bake file, it stores all the classes related to the\n basic Bake operation. The class Bake is responsible to identify and \n execute the defined options \n': command not found C:/cygwin64/bin/import.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory ./Bake.py: line 29: try:: command not found ./Bake.py: line 30: from: command not found ./Bake.py: line 31: except: command not found ./Bake.py: line 32: from: command not found C:/cygwin64/bin/import.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory C:/cygwin64/bin/import.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory C:/cygwin64/bin/import.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory C:/cygwin64/bin/import.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory C:/cygwin64/bin/import.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory C:/cygwin64/bin/import.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory ./Bake.py: line 39: from: command not found ./Bake.py: line 40: from: command not found ./Bake.py: line 41: from: command not found ./Bake.py: line 42: from: command not found ./Bake.py: line 43: from: command not found ./Bake.py: line 44: from: command not found ./Bake.py: line 45: from: command not found ./Bake.py: line 46: from: command not found ./Bake.py: line 47: from: command not found ./Bake.py: line 48: from: command not found ./Bake.py: line 50: syntax error near unexpected token `(' ./Bake.py: line 50: `def signal_handler(signal, frame):' </code></pre> <p><a href="https://www.dropbox.com/s/kl13gjz5umr4nz0/file.txt?dl=0" rel="nofollow">Here</a> is the <code>cygcheck -c</code> output. How to get NS-3 installed successfully ?</p>
0
2016-07-30T07:24:43Z
38,678,867
<p>Following <a href="https://www.nsnam.org/docs/release/3.25/tutorial/singlehtml/index.html#building-ns3" rel="nofollow">https://www.nsnam.org/docs/release/3.25/tutorial/singlehtml/index.html#building-ns3</a></p> <p>seems to work. (first step 2357 files compiled, so a bit long)</p> <p>To debug your problem and save all the logging, so to better understand what is missing:</p> <pre><code>python -v build.py |&amp; tee build.log </code></pre>
0
2016-07-30T21:59:30Z
[ "python", "bash", "python-2.7", "cygwin", "ns-3" ]
How to split a statement based on dots ('.'), while excluding dots inside angular brackets(< . >) using regular expressions in python?
38,671,627
<p>I want to split statements by dots using regex in python, while excluding certain dots inside the angular brackets. eg: Original Statement :</p> <pre><code>'my name 54. is &lt;not23.&gt; worth mentioning. ok?' </code></pre> <p>I want to split it into following sentences:</p> <pre><code>Statement 1 : 'my name 54' Statement 2 : ' is &lt;not23.&gt; worth mentioning' Statement 3 : ' ok' </code></pre> <p>I have attempted </p> <pre><code>re.split(r'[^&lt;.&gt;]\.','my name 54. is &lt;not23.&gt; worth mentioning. ok?') </code></pre> <p>But, it's not ignoring dot inside &lt;>, so the result am getting is: </p> <pre><code>['my name 5', ' is &lt;not23', '&gt; worth mentioning', ' ok?'] </code></pre>
-1
2016-07-30T07:47:32Z
38,671,662
<p>Easy if you can user the newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><strong><code>regex</code> module</strong></a> (it provides the <code>(*SKIP)(*FAIL)</code> functionality):</p> <pre><code>import regex as re string = 'my name 54. is &lt;not23.&gt; worth mentioning. ok?' rx = re.compile(r"&lt;[^&gt;]*&gt;(*SKIP)(*FAIL)|\.") parts = rx.split(string) print(parts) # ['my name 54', ' is &lt;not23.&gt; worth mentioning', ' ok?'] </code></pre>
1
2016-07-30T07:51:51Z
[ "python", "regex" ]
How to split a statement based on dots ('.'), while excluding dots inside angular brackets(< . >) using regular expressions in python?
38,671,627
<p>I want to split statements by dots using regex in python, while excluding certain dots inside the angular brackets. eg: Original Statement :</p> <pre><code>'my name 54. is &lt;not23.&gt; worth mentioning. ok?' </code></pre> <p>I want to split it into following sentences:</p> <pre><code>Statement 1 : 'my name 54' Statement 2 : ' is &lt;not23.&gt; worth mentioning' Statement 3 : ' ok' </code></pre> <p>I have attempted </p> <pre><code>re.split(r'[^&lt;.&gt;]\.','my name 54. is &lt;not23.&gt; worth mentioning. ok?') </code></pre> <p>But, it's not ignoring dot inside &lt;>, so the result am getting is: </p> <pre><code>['my name 5', ' is &lt;not23', '&gt; worth mentioning', ' ok?'] </code></pre>
-1
2016-07-30T07:47:32Z
38,671,813
<p>Split on the following regex:</p> <pre><code>\.(?![^&lt;]*&gt;) </code></pre> <p><a href="https://regex101.com/r/uL1uI5/1" rel="nofollow">Live demo</a></p> <pre><code>import re str = 'my name 54. is &lt;not23.&gt; worth mentioning. ok?' regex = re.compile(r"\.(?![^&lt;]*&gt;)") arr = regex.split(str) print(arr) </code></pre>
1
2016-07-30T08:09:35Z
[ "python", "regex" ]
initialization of multiarray raised unreported exception python
38,671,630
<p>I am a new programmer who is picking up python. I recently am trying to learn about importing csv files using numpy. Here is my code:</p> <pre><code>import numpy as np x = np.loadtxt("abcd.py", delimiter = True, unpack = True) print(x) </code></pre> <p>The idle returns me with:</p> <pre><code>&gt;&gt; True &gt;&gt; Traceback (most recent call last): &gt;&gt; File "C:/Python34/Scripts/a.py", line 1, in &lt;module&gt; import numpy as np &gt;&gt; File "C:\Python34\lib\site-packages\numpy\__init__.py", line 180, in &lt;module&gt; from . import add_newdocs &gt;&gt; File "C:\Python34\lib\site-packages\numpy\add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc &gt;&gt; File "C:\Python34\lib\site-packages\numpy\lib\__init__.py", line 8, in &lt;module&gt; from .type_check import * &gt;&gt; File "C:\Python34\lib\site-packages\numpy\lib\type_check.py", line 11, in &lt;module&gt; import numpy.core.numeric as _nx &gt;&gt; File "C:\Python34\lib\site-packages\numpy\core\__init__.py", line 14, in &lt;module&gt; from . import multiarray &gt;&gt; SystemError: initialization of multiarray raised unreported exception </code></pre> <p>Why do I get the this system error and how can I remedy it?</p>
1
2016-07-30T07:48:01Z
38,671,893
<p>As there is an error at the import line, your installation of numpy is broken in some way. My guess is that you have installed numpy for python2 but are using python3. You should remove numpy and attempt a complete re-install, taking care to pick the correct version.</p> <p>There are a few oddities in the code: You are apparently reading a python file, <code>abcd.py</code>, not a csv file. Typically you want to have your data in a csv file.</p> <p>The delimiter is a string, not a boolean, typically <code>delimiter=","</code> (<a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.loadtxt.html" rel="nofollow">Documentation</a>)</p> <pre><code>import numpy as np x = np.loadtxt("abcd.csv", delimiter = ",", unpack = True) </code></pre>
1
2016-07-30T08:20:11Z
[ "python", "numpy" ]
Early stopping and the sklearn neural_network.MLPClassifier
38,671,718
<p>I am using <a href="http://scikit-learn.org/dev/modules/generated/sklearn.neural_network.MLPClassifier.html" rel="nofollow"><code>sklearn.neural_network.MLPClassifier</code></a>. I am using the <code>early_stopping</code> feature, which evaluates performance for each iteration using a validation split (10% of the training data by default). </p> <p>However, my problem is multi-label. According to the API, validation uses subset accuracy, which is very harsh for multilabel problems. </p> <p><strong>Is it possible to define an alternative scoring function (ideally mlogloss) to be used in validation?</strong> Thanks.</p>
0
2016-07-30T07:58:15Z
38,732,224
<p>The solution is to use sknn rather than the sklearn implementation of MLP. That allows use to add our own valid_set and specify the loss function. Details <a href="http://scikit-neuralnetwork.readthedocs.io/en/latest/module_mlp.html#classifier" rel="nofollow">here</a>. </p>
0
2016-08-02T23:50:06Z
[ "python", "scikit-learn", "neural-network", "perceptron" ]
Get right data from dict inside list
38,671,722
<p>I'm trying to get a video URL from tweet, <code>A</code> was taken from tweepy. Because twitter doesn't tell which one is the highest quality video I assume that I have to compare highest 'bitrate' and store the 'url' that corresponds with it. This is what I have. </p> <p>Please bear with me, I'm new to this. </p> <pre><code>A = [{'content_type': 'application/x-mpegURL', 'url': 'https://video.twimg.com/ext_tw_video/758995712280412672/pu/pl/X_6gAm0z8TBBbEAR.m3u8'}, {'bitrate': 832000, 'content_type': 'video/mp4', 'url': 'https://video.twimg.com/ext_tw_video/758995754280412672/pu/vid/360x640/6nxKFKpdku-qAl__.mp4'}, {'content_type': 'application/dash+xml', 'url': 'https://video.twimg.com/ext_tw_video/758995715280412672/pu/pl/X_6gAm0z8TBBbEAR.mpd'}, {'bitrate': 320000, 'content_type': 'video/mp4', 'url': 'https://video.twimg.com/ext_tw_video/758995715280412672/pu/vid/180x320/VqRF6IcnmsLxZIil.mp4'}] for i, val in enumerate(A): if 'bitrate' in A[i]: print(A[i]['bitrate'], A[i]['url']) </code></pre> <p>This code produces </p> <pre><code>832000 https://video.twimg.com/ext_tw_video/758996713280412672/pu/vid/360x640/6nxKFKpdku-qAl__.mp4 320000 https://video.twimg.com/ext_tw_video/758997716280412672/pu/vid/180x320/VqRF6IcnmsLxZIil.mp4 </code></pre> <p>How do I store the ['url'] that corresponds with highest ['bitrate'] into a variable?</p>
-1
2016-07-30T07:58:50Z
38,671,764
<p>If you want to get dictionary (or url) with the highest bitrate:</p> <p>This compares the items of the list of dictionaries using <code>bitrate</code> key and returns dictionary with the highest <code>bitrate</code>. </p> <pre><code>max(A, key=lambda x:x['bitrate'])['url'] </code></pre> <p><strong>EDIT:</strong> According to your comment above, you can assign the url to variable of course. </p> <pre><code>variable = max(A, key=lambda x:x['bitrate'])['url'] </code></pre> <p><strong>EDIT1:</strong> According to your coment below - you believe right, you have to exclude such dictionaries from the list.</p> <p>This excludes dictionaries without 'bitrate' key:</p> <pre><code>[d for d in A if d.has_key('bitrate')] </code></pre> <p>So you have to switch A to the line above so the result would be:</p> <pre><code>variable = max([d for d in A if d.has_key('bitrate')],key=lambda x:x['bitrate']) </code></pre>
1
2016-07-30T08:04:09Z
[ "python", "data-structures", "data-dictionary" ]
Python Selenium:: Element is Currently Invisible
38,671,761
<p>So I am accessing <a href="https://steemit.com/steem/@ozchartart/usdsteem-btc-technical-analysis-2-the-only-way-for-me-to-move-on-is-to-chart-it-in-the-dawn" rel="nofollow">this</a> link and with help of <a href="http://stackoverflow.com/a/38632255/275002">this</a> friend, I am able to progress a bit. Now I am stuck. The issue is, when someone clicks on <code>Reply</code> and click <code>Post</code> button it says <code>Element is not currently visible and so may not be interacted with</code></p> <p>Code is given below:</p> <pre><code>import requests from bs4 import BeautifulSoup from gensim.summarization import summarize from selenium import webdriver from datetime import datetime from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.keys import Keys from time import sleep import sys import os import xmltodict from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import traceback import random driver = None driver = webdriver.Firefox() driver.maximize_window() url = 'https://steemit.com/steem/@ozchartart/usdsteem-btc-technical-analysis-2-the-only-way-for-me-to-move-on-is-to-chart-it-in-the-dawn' driver.get(url) sleep(5) f = driver.find_element_by_css_selector('.PostFull__reply') location = f.location["y"] - 100 driver.execute_script("window.scrollTo(0, %d);" % location) f.click() t = driver.find_element_by_tag_name('textarea') b = driver.find_element_by_tag_name('button') # b = WebDriverWait(driver, 20).until( # EC.presence_of_element_located((By.TAG_NAME, "button")) # ) # print(b) t.click() sleep(1) t.send_keys('awesome!!') sleep(2) driver.execute_script("arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1",b) driver.execute_script('document.getElementsByTagName("button")[0].click();') #if b.is_displayed(): b.click() except Exception as e: driver.save_screenshot('myscreen.png') print(str(e)) </code></pre>
1
2016-07-30T08:03:19Z
38,673,200
<p>Seems that you're trying to interract with another button. Try more specific selector:</p> <pre><code>driver.find_element_by_xpath('//button[text()="Post"]').click() </code></pre> <p>This works for me</p>
1
2016-07-30T11:05:55Z
[ "python", "selenium" ]
Sort python dictionary for keys, split it and create a JSON Array from it
38,671,766
<p>I have this huge JSON file, which contains more than 80000 lines, looking like that:</p> <pre><code>{u'hero_name': u'bristleback', u'gold_total': 17937, tick:24098} {u'hero_name': u'silencer', u'gold_total': 10847, tick:24198} {u'hero_name': u'silencer', u'gold_total': 11789, tick:25098} {u'hero_name': u'weaver', u'gold_total': 27084, tick:27098} </code></pre> <p>There are 10 different heroes with their gold data. I want to sort that data for the hero names, make a json list of the gold data, and then store it in a databse table looking like that, where gold_data should be like [{tick, gold}, {tick, gold}, ...]</p> <pre><code>id | hero_name | gold_data (json field) | ... </code></pre> <p>But seems like i am too stupid to sort that. I tried building a list out of it and using <code>sorted(gold_list, key=lambda s: s[0])</code> </p> <p>I am just not too comfortable with Python yet and I tried so many different things, but i have no idea how to sort,and then split this dictionary for the hero_names key so I can get that JSON object for gold_data</p>
-2
2016-07-30T08:04:20Z
38,672,645
<p>You need to use the <a href="https://docs.python.org/2/library/json.html" rel="nofollow">json</a> - there are other packages, but this one should do it.</p> <ol> <li>Load the JSON to a veriable using <code>open()</code></li> <li>Convert to <code>dict</code> using <code>json.loads()</code></li> </ol> <p>For example:</p> <pre><code>import json from pprint import pprint with open('data.json') as data_file: data = json.load(data_file) dct = json.loads(data) pprint(dct) </code></pre> <p>You CANNOT sort the dictionary though - you will have to convert the <code>dict</code> to <strong>array of tuples</strong> - <a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">please, refer here</a> and <a href="http://stackoverflow.com/questions/19110407/converting-json-objects-in-to-dictionary-in-python">here</a> and <a href="http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python">here</a></p>
0
2016-07-30T10:01:08Z
[ "python", "json", "sorting", "dictionary" ]
MultiIndex from irregular tuple of tuples
38,671,810
<p>I have the following tuples</p> <pre><code>tups = zip(list('AAAABBBB'), zip(list('aabbaabb'), list('cdcdcdcd'))) tups [('A', ('a', 'c')), ('A', ('a', 'd')), ('A', ('b', 'c')), ('A', ('b', 'd')), ('B', ('a', 'c')), ('B', ('a', 'd')), ('B', ('b', 'c')), ('B', ('b', 'd'))] </code></pre> <p>I'd like to create a pandas MultiIndex from them</p> <pre><code>df = pd.DataFrame(np.arange(32).reshape(4, 8), columns=pd.MultiIndex.from_tuples(tups)) </code></pre> <p>But I get tuples in a second level. How do I get all three levels?</p> <pre><code>print df A B (a, c) (a, d) (b, c) (b, d) (a, c) (a, d) (b, c) (b, d) 0 0 1 2 3 4 5 6 7 1 8 9 10 11 12 13 14 15 2 16 17 18 19 20 21 22 23 3 24 25 26 27 28 29 30 31 </code></pre>
2
2016-07-30T08:09:21Z
38,671,820
<p>You'll have to flatten your tuples. I did it as follows</p> <pre><code>new_tups = [(a, b, c) for a, (b, c) in tups] df = pd.DataFrame(np.arange(32).reshape(4, 8), columns=pd.MultiIndex.from_tuples(new_tups)) </code></pre> <p><a href="http://i.stack.imgur.com/7DM6m.png" rel="nofollow"><img src="http://i.stack.imgur.com/7DM6m.png" alt="enter image description here"></a></p>
2
2016-07-30T08:10:18Z
[ "python", "pandas", "multi-index" ]
Python manual call to descriptor ignored
38,671,838
<pre><code>class B(object): def meth(self): pass class C(B): pass b = B() c = C() print c.meth.__get__(b, B) </code></pre> <p>gives me:</p> <pre><code>&lt;bound method C.meth of &lt;__main__.C object at 0x10a892910&gt;&gt; </code></pre> <p>but I expect something like:</p> <pre><code>&lt;bound method B.meth of &lt;__main__.B object at 0x?????????&gt;&gt; </code></pre> <p>Why is my manual call to <code>c.meth.__get__</code> ignored? Python behaves as if I wrote <code>print c.meth</code>, and that lookup is automatically transformed to <code>print c.meth.__get__(c, C)</code></p>
0
2016-07-30T08:12:10Z
38,672,210
<p>The object you get when you lookup <code>c.meth</code> is a descriptor, but perhaps not the descriptor you were expecting. Rather, it's the <em>result</em> of a descriptor call (which just happens to be another kind of descriptor). Specifically, <code>c.meth</code> is an <code>instancemethod</code> object. It's what you get when a function (e.g. <code>B.__dict__["meth"]</code>) gets invoked as a descriptor (e.g. <code>B.__dict__["meth"].__get__(c, C)</code>, which I suspect is the descriptor call you actually wanted to try for yourself).</p> <p>The behavior of an <code>instancemethod</code> object when used as a descriptor is a bit odd. Unbound methods will bind if the class passed to <code>__get__</code> is a subclass of the method's original class, otherwise the unbound method will be returned as is. Already bound methods will never be rebound.</p> <p>You're trying to bind an already bound method, which doesn't work. Specifically, <code>c.meth.__get__(b, B)</code> returns the same <code>instancemethod</code> object you had as <code>c.meth</code>. The extra <code>__get__</code> call is deliberately treated as a no-op.</p> <p>You can see the implementation of the <code>__get__</code> method on bound methods in the cpython source code <a href="https://hg.python.org/cpython/file/2.7/Objects/classobject.c#l2607" rel="nofollow">here</a>. It's not very long, so I'll reproduce it:</p> <pre><code>static PyObject * instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) { /* Don't rebind an already bound method, or an unbound method of a class that's not a base class of cls. */ if (PyMethod_GET_SELF(meth) != NULL) { /* Already bound */ Py_INCREF(meth); return meth; } /* No, it is an unbound method */ if (PyMethod_GET_CLASS(meth) != NULL &amp;&amp; cls != NULL) { /* Do subclass test. If it fails, return meth unchanged. */ int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth)); if (ok &lt; 0) return NULL; if (!ok) { Py_INCREF(meth); return meth; } } /* Bind it to obj */ return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls); } </code></pre>
1
2016-07-30T09:06:00Z
[ "python", "python-2.7", "inheritance", "methods", "descriptor" ]
How to apply loop to extract contents from "DIV" tag while using Beautiful soup?
38,671,845
<p>i have recently found a very neat way of web scrapping using bs4 that has a really nice organized structure to it. let us say this is our html code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="a"&gt; &lt;div class="b"&gt; &lt;a href="www.yelloaes.com"&gt;'hi'&lt;/a&gt; &lt;/div&gt; &lt;div class ="c"&gt; &lt;p&gt;&lt;a href="www.bb.com"&gt;'hi again'&lt;/a&gt;&lt;/p&gt; &lt;div class="d"&gt; &lt;p&gt;'well this final'&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="a"&gt; &lt;div class="b"&gt; &lt;a href="www.yelloaes1.com"&gt;'hi1'&lt;/a&gt; &lt;/div&gt; &lt;div class ="c"&gt; &lt;p&gt;&lt;a href="www.bb1.com"&gt;'hi again1'&lt;/a&gt;&lt;/p&gt; &lt;div class="d"&gt; &lt;p&gt;'well this final1'&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>now i am assuming <code>&lt;div class="a"&gt;</code> is our parent tag and we will suck info out of this tag, now that means i have to loop through this to extract info from all the page .</p> <p>but because i was having a hard time understanding BeautifulSoup i did a test run with a python code to extract the info from the first iteration of this <code>&lt;div class= "a"&gt;</code></p> <p>my code is like this :</p> <pre><code>soup = BeautifulSoup(r.text) find_hi = soup.find('div',{'class':'a'}).div.text find_hi-again =soup.find('div',{'class':'a'}).find_all('div')[1].p.text find_final =soup.find('div',{'class':'a'}).find('div',{'class':'d'}).text print(find_hi , find_hi-again , find_final) #output comes as (it worked !!!) hi , hi again , this is final </code></pre> <p>Note: I really want to stick with this one so please no completely new ways of scrapping. now i <strong>can't seem to loop on all the page</strong> . i tried this for looping but does not show the result i want to see:</p> <pre><code>soup = BeautifulSoup(r.text) #To have a list of all div tags having this class scrapping = soup.find_all('div',{'class':'a'}) for i in scrapping: find_hi = i.div.text find_hi-again =i.find_all('div')[1].p.text find_final =i.find('div',{'class':'d'}).text print(find_hi , find_hi-again , find_final) </code></pre> <p>please help in looping ?</p>
0
2016-07-30T08:13:27Z
38,672,452
<p>You code works fine for me, except for the syntax error: <code>find_hi-again</code> is not a valid variable name.</p> <pre><code>divs = soup.find_all('div',{'class':'a'}) for i in divs: find_hi = i.div.text.strip() find_hi_again = i.find_all('div')[1].p.text.strip() find_final = i.find('div',{'class':'d'}).text.strip() print(find_hi , find_hi_again , find_final) ## (u"'hi'", u"'hi again'", u"'well this final'") ## (u"'hi1'", u"'hi again1'", u"'well this final1'") </code></pre>
0
2016-07-30T09:34:33Z
[ "python", "loops", "tags", "beautifulsoup", "textwrangler" ]
Pandas: slicing a dataframe into multiple sheets of the same spreadsheet
38,672,018
<p>Say I have 3 dictionaries of the same length, which I combine into a unique <code>pandas</code> dataframe. Then I dump said dataframe into an Excel file. Example:</p> <pre><code>import pandas as pd from itertools import izip_longest d1={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} d2={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} d3={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} dict_list=[d1,d2,d3] stats_matrix=[ tuple('dict{}'.format(i+1) for i in range(len(dict_list))) ] + list( izip_longest(*([ v for k,v in sorted(d.items())] for d in dict_list)) ) stats_matrix.pop(0) mydf=pd.DataFrame(stats_matrix,index=None) mydf.columns = ['d1','d2','d3'] writer = pd.ExcelWriter('myfile.xlsx', engine='xlsxwriter') mydf.to_excel(writer, sheet_name='sole') writer.save() </code></pre> <p>This code produces an Excel file with a <em>unique</em> sheet:</p> <pre><code>&gt;Sheet1&lt; d1 d2 d3 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 </code></pre> <p><strong>My question:</strong> how can I slice this dataframe in such a way that the resulting Excel file has, say, 3 sheets, in which the headers are repeated and there are two rows of values in each sheet? </p> <p><strong>EDIT</strong></p> <p>In the example given here the dicts have 6 elements each. In my real case they have 25000, the index of the dataframe starting from <code>1</code>. So I want to slice this dataframe into 25 different sub-slices, each of which is dumped into a dedicated Excel sheet of the same main file.</p> <p>Intended result: <em>one</em> Excel file with <em>multiple</em> sheets. Headers are repeated.</p> <pre><code>&gt;Sheet1&lt; &gt;Sheet2&lt; &gt;Sheet3&lt; d1 d2 d3 d1 d2 d3 d1 d2 d3 1 1 1 3 3 3 5 5 5 2 2 2 4 4 4 6 6 6 </code></pre>
3
2016-07-30T08:40:53Z
38,672,135
<p>First prep your dataframe for writing like this:</p> <pre><code>prepdf = mydf.groupby(mydf.index // 2).apply(lambda df: df.reset_index(drop=True)) prepdf </code></pre> <p><a href="http://i.stack.imgur.com/eGDyZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/eGDyZ.png" alt="enter image description here"></a></p> <p>You can use this function to reset you index instead.</p> <pre><code>def multiindex_me(df, how_many_groups=3, group_names=None): m = np.arange(len(df)) reset = lambda df: df.reset_index(drop=True) new_df = df.groupby(m % how_many_groups).apply(reset) if group_names is not None: new_df.index.set_levels(group_names, level=0, inplace=True) return new_df </code></pre> <p>Use it like this:</p> <pre><code>new_df = multiindex_me(mydf) </code></pre> <p>Or:</p> <pre><code>new_df = multiindex_me(mydf, how_many_groups=4, group_names=['One', 'Two', 'Three', 'Four']) </code></pre> <p>Then write each cross section to a different sheet like this:</p> <pre><code>writer = pd.ExcelWriter('myfile.xlsx') for sheet in prepdf.index.levels[0]: sheet_name = 'super_{}'.format(sheet) prepdf.xs(sheet).to_excel(writer, sheet_name) writer.save() </code></pre>
3
2016-07-30T08:56:07Z
[ "python", "excel", "pandas", "dataframe", "slice" ]
Python super: calling a base class method which contains another base class method that is overriden by derived class
38,672,395
<pre class="lang-py prettyprint-override"><code>class A(object): def foo(self): print "A - foo" def foo2(self): print "foo2" self.foo() class B(A): def foo(self): print "B - foo" def foo2(self): super(B, self).foo2() B().foo2() </code></pre> <p>I was trying to get [senario1]:</p> <pre><code>foo2 A - foo </code></pre> <p>but got [senario2]:</p> <pre><code>foo2 B - foo </code></pre> <p>instead.</p> <p>I found <a href="http://stackoverflow.com/questions/25097205/python-super-base-class-method-calls-another-method">the explanation</a>, but I am wondering if there is a way that yields [senario1] without changing the name of method <code>foo</code> in class <code>A</code>? </p>
2
2016-07-30T09:27:35Z
38,672,477
<p>One way to do this is to call <code>foo</code> on <code>A</code> and pass <code>self</code> to it by hand: </p> <pre><code>class A(object): def foo(self): print("A - foo") def foo2(self): print("foo2") A.foo(self) class B(A): def foo(self): print("B - foo") def foo2(self): super(B, self).foo2() B().foo2() </code></pre> <p>This way you will always call <code>foo</code> on <code>A</code>. If this <code>foo</code> would call <code>self.foo()</code>, if would again call <code>B</code>s foo method.</p>
2
2016-07-30T09:38:34Z
[ "python" ]
Python super: calling a base class method which contains another base class method that is overriden by derived class
38,672,395
<pre class="lang-py prettyprint-override"><code>class A(object): def foo(self): print "A - foo" def foo2(self): print "foo2" self.foo() class B(A): def foo(self): print "B - foo" def foo2(self): super(B, self).foo2() B().foo2() </code></pre> <p>I was trying to get [senario1]:</p> <pre><code>foo2 A - foo </code></pre> <p>but got [senario2]:</p> <pre><code>foo2 B - foo </code></pre> <p>instead.</p> <p>I found <a href="http://stackoverflow.com/questions/25097205/python-super-base-class-method-calls-another-method">the explanation</a>, but I am wondering if there is a way that yields [senario1] without changing the name of method <code>foo</code> in class <code>A</code>? </p>
2
2016-07-30T09:27:35Z
38,672,625
<p>As Leon pointed out you could simply access the <code>foo</code> method inside the <code>A</code> class by hardcoding the explicit call via <code>A.foo</code> and passing instance object as argument, however as Rawing has stated it's not good solution. Actually it's example of wrong class design. Why?</p> <ol> <li><p>Imagine that in a larger project you would use explicit calls via <code>A.foo</code> in hundreds of places. Now, try to rename your <code>A</code> class to <code>MagicUnicorn</code> class.</p></li> <li><p>It's counter-intuitive. If you override the <code>foo</code> method from <code>A</code> in <code>B</code> then the <code>foo</code> from <code>A</code> is not needed in 99.9999% cases as there must be a reason to override it.</p></li> </ol> <p>A better solution rather than using explicit calls would be to rename the <code>foo</code> in <code>B</code> (as Rawing has said):</p> <pre><code>class A(object): def foo(self): print "A - foo" def foo2(self): print "foo2" self.foo() class B(A): def unicorn_foo(self): print "B - foo" def foo2(self): super(B, self).foo2() B().foo2() </code></pre>
1
2016-07-30T09:58:51Z
[ "python" ]
django rest framework how to define required fields per ViewSet action
38,672,401
<p>I am trying the tutorial from DRF and I found something confused. I have a User model which simply extends auth.User like this</p> <pre><code>class User(DefaultUser): """ Represents a registered User """ EMAIL_VALIDATOR_LENGTH = 6 email_validated = models.BooleanField(default=False) # using a 6-digit numbers for email validation email_validator = models.CharField( max_length=6, default=_get_random_email_validator(EMAIL_VALIDATOR_LENGTH), editable=False ) phone_number = models.CharField(validators=[phone_regex], blank=True, null=True, max_length=64) # country is required country = models.ForeignKey('Country', null=False, blank=False) # subdivision is optional subdivision = models.ForeignKey('Subdivision', null=True, blank=True) </code></pre> <p>Then I have my basic UserSerializer:</p> <pre><code>class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'password', 'email_validated', 'email_validator', 'country', 'subdivision', 'phone_number', 'last_login', 'is_superuser', 'username', 'first_name', 'last_name', 'is_staff', 'is_active', 'date_joined') </code></pre> <p>In my views.py, I have UserViewSet:</p> <pre><code>class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @detail_route(methods=['get', 'post'], url_path='validate-email') def validate_email(self, request, pk): user = self.get_object() serializer = UserSerializer(data=request.data) if serializer.is_valid(): user.is_active = True user.save() return Response({'status': 'email validated'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @detail_route(methods=['post'], url_path='set-password') def set_password(self, request, pk): pass @list_route() def test_list_route(self, request): pass </code></pre> <p>The issue is, in validate_email, I actually only need pk but when I test the API, it told me that username and email are also required. </p> <p>I then added following code to my UserSerializer</p> <pre><code> extra_kwargs = {'country': {'required': False}, 'password': {'required': False}, 'username': {'required': False}, } </code></pre> <p>Now the above issue is gone, but when I tried to create an User, I actually do want to require username and email. </p> <p>Is there a way that I can specify which fields are required per action? For example, for my set_password(), I want to require the password field.</p> <p>Thanks, </p>
0
2016-07-30T09:28:34Z
38,674,465
<p>Try to override serializer constructor to modify fields based on extra arguments. Didn't test that but it should work:</p> <pre><code>class UserSerializer(ModelSerializer): def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) require_password = kwargs.get('require_password', False) require_email = kwargs.get('require_email', False) if require_password: self.fields['password'].required = True if require_email: self.fields['email'].required = True </code></pre> <p>Then pass <code>require_password</code> or/and <code>require_email</code> arguments when you need:</p> <pre><code>serializer = UserSerializer(data=request.data, require_password=True, require_email=True) </code></pre>
0
2016-07-30T13:29:08Z
[ "python", "django", "django-rest-framework" ]
django rest framework how to define required fields per ViewSet action
38,672,401
<p>I am trying the tutorial from DRF and I found something confused. I have a User model which simply extends auth.User like this</p> <pre><code>class User(DefaultUser): """ Represents a registered User """ EMAIL_VALIDATOR_LENGTH = 6 email_validated = models.BooleanField(default=False) # using a 6-digit numbers for email validation email_validator = models.CharField( max_length=6, default=_get_random_email_validator(EMAIL_VALIDATOR_LENGTH), editable=False ) phone_number = models.CharField(validators=[phone_regex], blank=True, null=True, max_length=64) # country is required country = models.ForeignKey('Country', null=False, blank=False) # subdivision is optional subdivision = models.ForeignKey('Subdivision', null=True, blank=True) </code></pre> <p>Then I have my basic UserSerializer:</p> <pre><code>class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'password', 'email_validated', 'email_validator', 'country', 'subdivision', 'phone_number', 'last_login', 'is_superuser', 'username', 'first_name', 'last_name', 'is_staff', 'is_active', 'date_joined') </code></pre> <p>In my views.py, I have UserViewSet:</p> <pre><code>class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @detail_route(methods=['get', 'post'], url_path='validate-email') def validate_email(self, request, pk): user = self.get_object() serializer = UserSerializer(data=request.data) if serializer.is_valid(): user.is_active = True user.save() return Response({'status': 'email validated'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @detail_route(methods=['post'], url_path='set-password') def set_password(self, request, pk): pass @list_route() def test_list_route(self, request): pass </code></pre> <p>The issue is, in validate_email, I actually only need pk but when I test the API, it told me that username and email are also required. </p> <p>I then added following code to my UserSerializer</p> <pre><code> extra_kwargs = {'country': {'required': False}, 'password': {'required': False}, 'username': {'required': False}, } </code></pre> <p>Now the above issue is gone, but when I tried to create an User, I actually do want to require username and email. </p> <p>Is there a way that I can specify which fields are required per action? For example, for my set_password(), I want to require the password field.</p> <p>Thanks, </p>
0
2016-07-30T09:28:34Z
38,681,955
<p>I turned out to implement it myself, so I basically make all fields option but in actions, I added a decorator to ensure the request body has those specified keys in it. </p> <p>decorator:</p> <pre><code>class AssertInRequest(object): """ A decorator to decorate ViewSet actions, this decorator assumes the first positional argument is request, so you can apply this decorator any methods that the first positional argument is request. This decorator itself takes a list of strings as argument, and will check that the request.data.dict() actually contains these keys For example, if you have a action to set user password which you expect that in the request body should have 'password' provided, use this decorator for the method like @detail_route() @AssertInRequest(['password']) def set_password(self, request, pk): pass """ def __init__(self, keys): self.keys = [] for key in keys: if hasattr(key, 'upper'): self.keys.append(key.lower()) def __call__(self, func): def wrapped(*args, **kwargs): if self.keys: try: request = args[1] except IndexError: request = kwargs['request'] if request: json_data = get_json_data(request) for key in self.keys: if key not in json_data or not json_data[key]: return DefaultResponse( 'Invalid request body, missing required data [%s]' % key, status.HTTP_400_BAD_REQUEST) return func(*args, **kwargs) return wrapped </code></pre> <p>How to use it:</p> <pre><code> @detail_route(methods=['post'], url_path='set-password', permission_classes=(IsAuthenticated,)) @AssertInRequest(['password']) def set_password(self, request, pk): user = self.get_object() json_data = get_json_data(request) user.set_password(json_data['password']) user.save() return DefaultResponse(_('Successfully set password for user %s' % user.email), status.HTTP_200_OK) </code></pre> <p>I guess it is not elegant but probably enough for me for now.</p>
0
2016-07-31T07:59:19Z
[ "python", "django", "django-rest-framework" ]
Code works in Java but not Python?
38,672,495
<p>This code seems to work in Java, but when I convert it to Python, it exceeds the maximum recursion depth and exits.. Not sure what the difference is. They look like they function identically to me.</p> <p><strong>Java version:</strong></p> <pre><code>public String addCommas(String number) { if(number.length &lt; 4 { return number; } return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length); } </code></pre> <p><strong>Python version:</strong></p> <pre><code>def addCommas(number): number = str(number) if len(number) &lt; 4: return number else: return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:]) </code></pre> <p>Thanks in advance for any help!</p>
1
2016-07-30T09:42:38Z
38,672,538
<p>The difference is in the last line.</p> <pre><code> return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length); </code></pre> <p>This calls <code>addCommas</code> on the first substring only (which reduces the length of the string parameter for the next call by 3) and then appends a comma and the last three digits to its result.</p> <pre><code> return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:]) </code></pre> <p>This on the other hand first adds a comma and calls <code>addCommas</code> on the whole new string (which is even longer than the original, resulting in the infinite recursion loop).</p> <pre><code> return addCommas(number[:len(number) - 3]) + ',' + number[len(number) - 3:] </code></pre> <p>This would work as it only calls <code>addCommas</code> on the first substring and adds the commas to the result of <code>addCommas</code>, the same way the Java code does it.</p>
1
2016-07-30T09:48:01Z
[ "python", "recursion" ]
Code works in Java but not Python?
38,672,495
<p>This code seems to work in Java, but when I convert it to Python, it exceeds the maximum recursion depth and exits.. Not sure what the difference is. They look like they function identically to me.</p> <p><strong>Java version:</strong></p> <pre><code>public String addCommas(String number) { if(number.length &lt; 4 { return number; } return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length); } </code></pre> <p><strong>Python version:</strong></p> <pre><code>def addCommas(number): number = str(number) if len(number) &lt; 4: return number else: return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:]) </code></pre> <p>Thanks in advance for any help!</p>
1
2016-07-30T09:42:38Z
38,672,702
<p>The difference is in the last line </p> <p>Java : return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length);</p> <p>Python : return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:])</p> <p>are not same. If you observe in java you are calling addCommas and then appending comma and a string. Whereas in python you are only calling addCommas function.This will lead to infinite loop. Just do it same as in java. </p> <p>return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:])</p>
0
2016-07-30T10:08:44Z
[ "python", "recursion" ]
Why can't pdb access a variable containing an exception?
38,672,560
<p>Sometime, I can't identify when or what's causing it, pdb will not help you with code like:</p> <pre><code>try: foo() except Exception as e: import pdb; pdb.set_trace() </code></pre> <p>You end up with the usual prompt, but trying to access <code>e</code> will lead to:</p> <pre><code>(pdb) e *** NameError: name 'e' is not defined. </code></pre> <p>It's not all the time of course, and it happens on linux, windows, my machine, my colleague machine...</p>
1
2016-07-30T09:50:39Z
38,672,659
<p>In Python 3, the target of an <code>except .. as target</code> statement is cleared when the suite exits. From the <a href="https://docs.python.org/3/reference/compound_stmts.html#the-try-statement" rel="nofollow"><code>try</code> statement documentation</a>:</p> <blockquote> <p>When an exception has been assigned using as <code>target</code>, it is cleared at the end of the except clause. This is as if</p> <pre><code>except E as N: foo </code></pre> <p>was translated to</p> <pre><code>except E as N: try: foo finally: del N </code></pre> <p>This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.</p> </blockquote> <p>Calling <code>pdb.set_trace()</code> effectively exits the block, so the implicit <code>finally</code> suite above is executed.</p> <p>Bind the exception to a different name:</p> <pre><code>try: foo() except Exception as e: exception = e import pdb; pdb.set_trace() </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; try: ... foo() ... except Exception as e: ... exception = e ... import pdb; pdb.set_trace() ... --Return-- &gt; &lt;stdin&gt;(5)&lt;module&gt;()-&gt;None (Pdb) e *** NameError: name 'e' is not defined (Pdb) exception NameError("name 'foo' is not defined",) </code></pre>
3
2016-07-30T10:04:00Z
[ "python", "python-3.x", "debugging", "exception", "pdb" ]
Select all checkboxes in django template
38,672,675
<p>I am using the following code to 'select all' and 'clear' the checkboxes of my django form in the django template. </p> <pre><code> &lt;form id="inv_form" method="post" action="{% url 'inventory:create_inventory' %}"&gt; {% csrf_token %} {{ form.as_p }} &lt;input type="submit" name="submit" value="Create Inventory" /&gt; &lt;a href="{% url 'user:dashboard' %}"&gt;Cancel&lt;/a&gt; &lt;button onclick="select_all()"&gt;Select All&lt;/button&gt; &lt;button onclick="deselect_all()"&gt;Clear&lt;/button&gt; &lt;/form&gt; function select_all() { $('input[type=checkbox]').prop('checked', true); } function deselect_all() { $('input[type=checkbox]').prop('checked', false); } </code></pre> <p>The problem is the form is getting automatically posted if I press 'check all' button. Same in case of 'clear' button. </p> <p>So I tried adding preventDefault() to my form submit event.</p> <pre><code> $("#inv_form").submit(function(event){ event.preventDefault(); }); </code></pre> <p>Now the original problem has been solved, but the submit doesn't works even on clicking at all.</p> <p>How to make the check all button work without auto posting the django form </p>
0
2016-07-30T10:06:11Z
38,672,846
<p>You probably hate to unbind submit, then you can submit the form. </p> <pre><code>$('some_form').unbind('submit').submit() </code></pre> <p>This approach should cancel <code>prevenDefault</code> so you can submit the form.</p>
0
2016-07-30T10:25:19Z
[ "javascript", "python", "django", "django-forms", "django-templates" ]
Deploying django app with nginx and uwsgi, client can not connect to server
38,672,691
<p>I have been trying to solve this problem three entire days without solution. Now, I am under pressure at my work and I really need your help.</p> <p>I know that nginx is listen to correct port '20154' using netstat, also I have run the command nginx -t and its ok. The logs have no error because client can not reach the server.</p> <p>Maybe the problem is with uwsgi.init I don't know, so I put here my cons files and uwsgi init files</p> <p>I hope can solve this problem with your help and solve this learning more.</p> <p><strong>nginx.conf file:</strong></p> <pre><code>user user; worker_processes 1; pid /var/run/nginx.pid; events { worker_connections 768; multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; ## # nginx-naxsi config ## # Uncomment it if you installed nginx-naxsi ## #include /etc/nginx/naxsi_core.rules; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } </code></pre> <p><strong>nginx enabled sites</strong></p> <pre><code>upstream django { server unix:///home/ctag/env_Compass4D/Compass4D/Compass4D.sock; # for a file socket } server { listen 20154; location /assets/ { root /home/ctag/env_Compass4D/Compass4D/; } location /doc/ { alias /usr/share/doc/; #alias /home/ctag/Compass4D/env_Compass4D/Compass4D autoindex on; #allow 127.0.0.1; } location / { #uwsgi_pass unix:/home/ctag/env_Compass4D/Compass4D/Compass4D.sock; proxy_pass http://unix:/home/ctag/env_Compass4D/Compass4D/Compass4D.sock; #proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; uwsgi_pass django; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed } location /Compass4D { root /home/ctag/env_Compass4D/Compass4D/; } </code></pre> <p><strong>uwsgi.init</strong></p> <pre><code># Compass4D_uwsgi.ini file [uwsgi] # Configuraciones Django # ruta al directorio del proyecto (ruta completa) chdir = /home/ctag/env_Compass4D/Compass4D/ # Archivo wsgi de Django module = Compass4D.wsgi # master master = true # numero de procesos (trabajadores) processes = 5 # Ruta al socket socket = /home/ctag/env_Compass4D/Compass4D/Compass4D.sock # Permisos del socket chmod-socket = 666 # Loggeo para detectar fallo al startup #logto = /tmp/errlog # Al cerrar limpiar el ambiente vacuum = true </code></pre>
1
2016-07-30T10:07:50Z
38,673,406
<p>This is the new configuration that worked for me, you can see the changes, also the command that I had to use, thanks.</p> <p><strong>The new sites-enabled file:</strong></p> <pre><code>upstream django { server unix:///home/ctag/env_Compass4D/Compass4D/Compass4D.sock; # for a file socket } server { listen 80; ## listen for ipv4; this line is default and implied server_name ~^.*$; location /static/ { root /home/ctag/env_Compass4D/Compass4D/; } location /doc/ { alias /usr/share/doc/; autoindex on; } location / { #uwsgi_pass unix:/home/ctag/env_Compass4D/Compass4D/Compass4D.sock; proxy_pass http://unix:/home/ctag/env_Compass4D/Compass4D/Compass4D.sock; #proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; uwsgi_pass django; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed } location /Compass4D/ { root /home/ctag/env_Compass4D/Compass4D/; } </code></pre> <p><strong>The uWSGI command that I used to run server in background:</strong></p> <pre><code>uwsgi --ini env_Compass4D/Compass4D/Compass4D_uwsgi.ini &amp; </code></pre>
0
2016-07-30T11:26:21Z
[ "python", "django", "nginx", "uwsgi" ]
NaN in mapper - name 'nan' is not defined
38,672,695
<p>I do as below</p> <pre><code>mapper = {'a': 'b', 'c': nan, 'd': 'e', nan : nan} df['b'] = [ mapper[x] for x in df['a'] ] df['b'].value_counts() </code></pre> <p>and</p> <pre><code>NameError Traceback (most recent call last) &lt;ipython-input-48-3862b2347ce7&gt; in &lt;module&gt;() NameError: name 'nan' is not defined </code></pre> <p>What's wrong? Is a mistake in coding or in file? </p>
-3
2016-07-30T10:08:19Z
38,672,710
<p>You didn't define what the variable <code>nan</code> is, so Python raises a <code>NameError</code>. If you want to check whether a number is <code>NaN</code> (not a number), use <code>math.isnan(x)</code>, where <code>x</code> is a float.</p>
0
2016-07-30T10:09:45Z
[ "python", null ]
NaN in mapper - name 'nan' is not defined
38,672,695
<p>I do as below</p> <pre><code>mapper = {'a': 'b', 'c': nan, 'd': 'e', nan : nan} df['b'] = [ mapper[x] for x in df['a'] ] df['b'].value_counts() </code></pre> <p>and</p> <pre><code>NameError Traceback (most recent call last) &lt;ipython-input-48-3862b2347ce7&gt; in &lt;module&gt;() NameError: name 'nan' is not defined </code></pre> <p>What's wrong? Is a mistake in coding or in file? </p>
-3
2016-07-30T10:08:19Z
38,672,715
<p>Python does not have a built-in name <code>nan</code>, nor is there a keyword.</p> <p>It looks as if you forgot to import it; <code>numpy</code> defines such a name:</p> <pre><code>from numpy import nan </code></pre> <p>From the local name <code>df</code> I infer you are probably using pandas; pandas' documentation usually uses <code>np.nan</code>, where <code>np</code> is the <code>numpy</code> module imported with <code>import numpy as np</code>. See their <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow"><em>10 Minute to pandas</em> intro</a> for example.</p>
2
2016-07-30T10:10:00Z
[ "python", null ]
Write specific data in one cell depending on contents of another cell in Pandas
38,672,734
<p>I am a Pandas newbie and I have a csv file with about 50 different columns. Some of them contain a "-1" value and the last column I have named "Holder" to store the results of some comparisons I make on the other columns.</p> <p>Data is of the form</p> <pre><code>Row 1: Investments_Cash Holder 0 NaN Row 2: Investments_Cash Holder 0 NaN Row 3: Investments_Cash Holder -1 NaN </code></pre> <p>For the rows that contain "Investments_Cash" of -1, I want to set the corresponding "Holder" column value to "Found". How can I do this?</p> <p>I've tried</p> <pre><code>if df.Investments_Cash == -1: df.Holder = "Found" </code></pre> <p>but I get an error <code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</code></p>
2
2016-07-30T10:11:52Z
38,672,777
<pre><code>df.loc[df.Investments_Cash == -1, 'Holder'] = 'Found' </code></pre>
3
2016-07-30T10:17:20Z
[ "python", "pandas" ]
predict_proba(X) of RandomForestClassifier (sklearn) seems to be static?
38,672,779
<p>For all classes I want to retrieve the prediction-score/probability of a given sample. I'm using the RandomForestClassifier of sklearn. My code is running fine if I'm using <code>.predict()</code>. However to show the probabilites I'm using <code>.predict_proba(X)</code> and it returns always the same values, even then when <code>X</code> changes. Why is that so and how to fix it?</p> <p>I'm breaking down my code to the concerning parts:</p> <pre><code># ... code ... feature generation / gets the feature data if rf is None: rf = RandomForestClassifier(n_estimators=80) rf.fit(featureData, classes) else: prediction = rf.predict(featureData) # gets the right class / always different proba = rf.predict_proba(featureData) print proba # this prints always the same values for all my 40 classes </code></pre> <p>Interestingly <code>max(proba)</code> retrieves the class that <code>.predict()</code> returns in the very first run. Due to <code>.predict()</code> is working as expected I believe the error is at sklearn's side, i.e. I guess there is a flag that needs to be set.</p> <p>Has anyone an idea?</p>
1
2016-07-30T10:17:35Z
38,675,888
<p>I guess the problem is you are passing always the same argument to <code>predict_proba</code>. Here is my code to build a forest of trees from the iris dataset:</p> <pre><code>from sklearn import datasets from sklearn.ensemble import RandomForestClassifier iris = datasets.load_iris() X = iris.data y = iris.target rf = RandomForestClassifier(n_estimators=80) rf.fit(X, y) </code></pre> <p>When I call the methods <code>predict</code> and <code>predict_proba</code>, the class and class log-probability predictions for different arguments are also different, as one could reasonably expect.</p> <p>Sample run:</p> <pre><code>In [82]: a, b = X[:3], X[-3:] In [83]: a Out[83]: array([[ 5.1, 3.5, 1.4, 0.2], [ 4.9, 3. , 1.4, 0.2], [ 4.7, 3.2, 1.3, 0.2]]) In [84]: b Out[84]: array([[ 6.5, 3. , 5.2, 2. ], [ 6.2, 3.4, 5.4, 2.3], [ 5.9, 3. , 5.1, 1.8]]) In [85]: rf.predict(a) Out[85]: array([0, 0, 0]) In [86]: rf.predict(b) Out[86]: array([2, 2, 2]) In [87]: rf.predict_proba(a) Out[87]: array([[ 1., 0., 0.], [ 1., 0., 0.], [ 1., 0., 0.]]) In [88]: rf.predict_proba(b) Out[88]: array([[ 0. , 0. , 1. ], [ 0. , 0.0125, 0.9875], [ 0. , 0.0375, 0.9625]]) </code></pre>
1
2016-07-30T16:04:57Z
[ "python", "scikit-learn", "classification", "probability", "random-forest" ]
pyspark saveAsSequenceFile with pyspark.ml.linalg.Vectors
38,672,784
<p>I try to save a (huge) list of sparse vectors as a sequence file and I get errors. Below is a dummy code:</p> <pre class="lang-py prettyprint-override"><code>#used on pyspark shell from pyspark.ml.linalg import Vectors rdd = sc.parallelize([Vectors.sparse(5, {1:1,2:2}), Vectors.sparse(5, {3:3,4:4})]) rdd.zipWithIndex().saveAsSequenceFile("hdfs://master:9000/user/vec.rdd") </code></pre> <pre> 16/07/30 09:36:49 ERROR Executor: Exception in task 0.0 in stage 2.0 (TID 5) net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 16/07/30 09:36:49 WARN TaskSetManager: Lost task 0.0 in stage 2.0 (TID 5, localhost): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 16/07/30 09:36:49 ERROR TaskSetManager: Task 0 in stage 2.0 failed 1 times; aborting job Traceback (most recent call last): File "", line 1, in File "/home/ubuntu/spark/python/pyspark/rdd.py", line 1450, in saveAsSequenceFile path, compressionCodecClass) File "/home/ubuntu/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 933, in __call__ File "/home/ubuntu/spark/python/pyspark/sql/utils.py", line 63, in deco return f(*a, **kw) File "/home/ubuntu/spark/python/lib/py4j-0.10.1-src.zip/py4j/protocol.py", line 312, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.saveAsSequenceFile. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 2.0 failed 1 times, most recent failure: Lost task 0.0 in stage 2.0 (TID 5, localhost): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Driver stacktrace: at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1450) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1438) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1437) at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48) at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1437) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811) at scala.Option.foreach(Option.scala:257) at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:811) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1659) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1618) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1607) at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48) at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:632) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1871) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1884) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1897) at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1305) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112) at org.apache.spark.rdd.RDD.withScope(RDD.scala:358) at org.apache.spark.rdd.RDD.take(RDD.scala:1279) at org.apache.spark.api.python.SerDeUtil$.pythonToPairRDD(SerDeUtil.scala:233) at org.apache.spark.api.python.PythonRDD$.saveAsHadoopFile(PythonRDD.scala:797) at org.apache.spark.api.python.PythonRDD$.saveAsSequenceFile(PythonRDD.scala:772) at org.apache.spark.api.python.PythonRDD.saveAsSequenceFile(PythonRDD.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:211) at java.lang.Thread.run(Thread.java:745) Caused by: net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ... 1 more >>> 16/07/30 09:36:49 WARN TaskSetManager: Lost task 2.0 in stage 2.0 (TID 7, localhost): TaskKilled (killed intentionally) Traceback (most recent call last): File "/home/ubuntu/spark/python/pyspark/context.py", line 223, in signal_handler raise KeyboardInterrupt() KeyboardInterrupt >>> rdd.map(lambda x: (0, x)).saveAsSequenceFile("hdfs://master:9000/user/seq.rdd") 16/07/30 09:38:53 ERROR Executor: Exception in task 2.0 in stage 4.0 (TID 11) net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 16/07/30 09:38:53 WARN TaskSetManager: Lost task 2.0 in stage 4.0 (TID 11, localhost): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 16/07/30 09:38:53 ERROR TaskSetManager: Task 2 in stage 4.0 failed 1 times; aborting job 16/07/30 09:38:53 WARN TaskSetManager: Lost task 0.0 in stage 4.0 (TID 9, localhost): TaskKilled (killed intentionally) Traceback (most recent call last): File "", line 1, in File "/home/ubuntu/spark/python/pyspark/rdd.py", line 1450, in saveAsSequenceFile path, compressionCodecClass) File "/home/ubuntu/spark/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 933, in __call__ File "/home/ubuntu/spark/python/pyspark/sql/utils.py", line 63, in deco return f(*a, **kw) File "/home/ubuntu/spark/python/lib/py4j-0.10.1-src.zip/py4j/protocol.py", line 312, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.saveAsSequenceFile. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 4.0 failed 1 times, most recent failure: Lost task 2.0 in stage 4.0 (TID 11, localhost): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Driver stacktrace: at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1450) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1438) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1437) at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48) at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1437) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:811) at scala.Option.foreach(Option.scala:257) at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:811) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1659) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1618) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1607) at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48) at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:632) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1871) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1884) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1897) at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1305) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112) at org.apache.spark.rdd.RDD.withScope(RDD.scala:358) at org.apache.spark.rdd.RDD.take(RDD.scala:1279) at org.apache.spark.api.python.SerDeUtil$.pythonToPairRDD(SerDeUtil.scala:233) at org.apache.spark.api.python.PythonRDD$.saveAsHadoopFile(PythonRDD.scala:797) at org.apache.spark.api.python.PythonRDD$.saveAsSequenceFile(PythonRDD.scala:772) at org.apache.spark.api.python.PythonRDD.saveAsSequenceFile(PythonRDD.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:211) at java.lang.Thread.run(Thread.java:745) Caused by: net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for pyspark.ml.linalg.SparseVector) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:152) at org.apache.spark.api.python.SerDeUtil$$anonfun$pythonToJava$1$$anonfun$apply$1.apply(SerDeUtil.scala:151) at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434) at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440) at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:389) at scala.collection.Iterator$class.foreach(Iterator.scala:893) at scala.collection.AbstractIterator.foreach(Iterator.scala:1336) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:59) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:310) at scala.collection.AbstractIterator.to(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:302) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1336) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:289) at scala.collection.AbstractIterator.toArray(Iterator.scala:1336) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.rdd.RDD$$anonfun$take$1$$anonfun$29.apply(RDD.scala:1305) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1897) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70) at org.apache.spark.scheduler.Task.run(Task.scala:85) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ... 1 more </pre> <p>Does this problem lie in the hadoop-native library that isn't loaded? because simple types like Integers and Strings work. If it can't be done this way, is there any fast and compact way to serialize a large collection of sparse vectors?</p>
1
2016-07-30T10:18:26Z
38,673,358
<p>Native Hadoop libraries are not an issue here. The problem here is a <code>SparseVector</code> class itself. <code>ml</code> / <code>mllib</code> vectors heavily use native NumPy structures which cannot be handled by <code>Pyrolite</code> library.</p> <p>Arguably using sequence files in PySpark to handle anything else than built-in types is just a waste of time. Since custom objects are represented as <code>Map&lt;String, Object&gt;</code> and <code>dict</code> in Java and Python respectively you cannot even seamlessly retrieve saved Python objects. For example object of class <code>Foo</code>:</p> <pre><code>class Foo(object): def __init__(self, x): self.x = x foo = Foo(1) </code></pre> <p>becomes:</p> <pre><code>{'__class__': 'foo.Foo', 'x': 1} </code></pre> <p>in Python and something roughly equivalent to</p> <pre><code>import scala.collection.mutable.Map import scala.collection.JavaConverters.mapAsJavaMapConverter Map[String, Any]("__class__" -&gt; "foo.Foo", "x" -&gt; 1).asJava </code></pre> <p>on JVM.</p> <p>If you want to save <code>Vectors</code> in a reliable way you can for example use Parquet:</p> <pre><code>rdd.zipWithIndex().toDF().write.parquet(...) </code></pre>
1
2016-07-30T11:20:31Z
[ "python", "apache-spark", "pyspark" ]
keys of first data frame that appear in second one and flag that fact
38,672,867
<p>I have two Data Frames:</p> <pre><code>data = { 'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'], 'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV', 'CRV'], 'amount': [5, 5, 8, 6, 1, 5, 10, 6, 12, 11], 'id': [10, 10, 11, 11, 11, 10, 10, 11, 11, 10] } df1 = pd.DataFrame(data, columns = ['retailer_name', 'store_number', 'year', 'amount', 'id']) df1.set_index(['retailer_name', 'store_number', 'year'], inplace = True) </code></pre> <hr> <pre><code>retailer_name store_number year amount id Walmart 1944 11:23:19 5 10 1945 11:23:19 5 10 CRV 1946 11:24:19 8 11 1948 11:25:19 6 11 11:25:19 1 11 Walmart 1949 11:23:19 5 10 1947 11:23:19 10 10 CRV 1948 11:23:19 6 11 1949 11:23:19 12 11 1947 11:23:19 11 10 </code></pre> <p>And the second one:</p> <pre><code>data2 = { 'year': ['11:23:19', '11:23:19', '13:23:19'], 'store_number': [1944, 1947, 1978], 'retailer_name': ['Walmart', 'CRV', 'CRV12'], 'amount': [5, 11, 11] } df2 = pd.DataFrame(data2, columns = ['retailer_name', 'store_number', 'year', 'amount']) df2.set_index(['retailer_name', 'store_number', 'year'], inplace = True) </code></pre> <hr> <pre><code>retailer_name store_number year amount Walmart 1944 11:23:19 5 CRV 1947 11:23:19 11 CRV12 1978 13:23:19 11 </code></pre> <p>How can I check the keys of df2 that appear in df1, and flag <code>1</code> on those that do appear and <code>0</code> if not:</p> <pre><code>retailer_name store_number year amount flag Walmart 1944 11:23:19 5 1 CRV 1947 11:23:19 11 1 CRV12 1978 13:23:19 11 0 </code></pre>
0
2016-07-30T10:27:51Z
38,673,315
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.intersection.html" rel="nofollow">MultiIndex.intersection()</a> method if you make sure that both multiindexes have the same dtypes:</p> <pre><code>In [74]: df2['flag'] = 0 In [75]: df2.ix[df2.index.intersection(df.index), 'flag'] = 1 c:\envs\py35\lib\site-packages\IPython\terminal\ipapp.py:344: PerformanceWarning: indexing past lexsort depth may impact performance. self.shell.mainloop() In [76]: df2 Out[76]: amount flag retailer_name store_number year Walmart 1944 11:23:19 5 1 CRV 1947 11:23:19 11 1 CRV12 1978 13:23:19 11 0 </code></pre> <p>NOTE: it won't work with your sample DFs because column <code>store_number</code> has different dtypes: <code>string</code> in <code>df</code> and <code>int</code> in <code>df2</code></p>
1
2016-07-30T11:16:27Z
[ "python", "pandas", "dataframe" ]
Python 3.5 Windows cannot run Rodeo example?
38,672,891
<p>I just installed Python 3.5 on windows 10 and was trying to run the startup example from the IDE I choose (Rodeo). The example gives an error when trying to import ggplot. Specifically, at this call</p> <pre><code>from ggplot import ggplot, aes, geom_bar </code></pre> <p>which gives me:</p> <pre><code>ImportErrorTraceback (most recent call last) in () ----&gt; 1 from ggplot import ggplot, aes, geom_bar C:\Anaconda3\lib\site-packages\ggplot\__init__.py in () 17 18 ---&gt; 19 from .geoms import geom_area, geom_blank, geom_boxplot, geom_line, geom_point, geom_jitter, geom_histogram, geom_density, geom_hline, geom_vline, geom_bar, geom_abline, geom_tile, geom_rect, geom_bin2d, geom_step, geom_text, geom_path, geom_ribbon, geom_now_its_art, geom_violin, geom_errorbar, geom_polygon 20 from .stats import stat_smooth, stat_density 21 C:\Anaconda3\lib\site-packages\ggplot\geoms\__init__.py in () ----&gt; 1 from .geom_abline import geom_abline 2 from .geom_area import geom_area 3 from .geom_bar import geom_bar 4 from .geom_bin2d import geom_bin2d 5 from .geom_blank import geom_blank C:\Anaconda3\lib\site-packages\ggplot\geoms\geom_abline.py in () ----&gt; 1 from .geom import geom 2 3 class geom_abline(geom): 4 """ 5 Line specified by slope and intercept C:\Anaconda3\lib\site-packages\ggplot\geoms\geom.py in () 1 from __future__ import (absolute_import, division, print_function, 2 unicode_literals) ----&gt; 3 from ..ggplot import ggplot 4 from ..aes import aes 5 C:\Anaconda3\lib\site-packages\ggplot\ggplot.py in () 19 from . import discretemappers 20 from .utils import format_ticks ---&gt; 21 import StringIO 22 import urllib 23 import base64 ImportError: No module named 'StringIO' </code></pre> <p>So StringIO cannot be imported. I read <a href="http://stackoverflow.com/questions/11914472/stringio-in-python3">here</a> that StringIO doens't exist in that form anymore, but the fixes over there did not help me out. Any tips? What might be relevant (although I cannot judge that) is that I'm unable to update Scipy or ggplot via <code>pip install ggplot --upgrade</code>, but I thought/ read somewhere that this happens because I do not have a built in compiler on my windows machine. Many thanks in advance!</p>
0
2016-07-30T10:31:17Z
38,683,370
<p>Well, I found a solution myself. <code>pip install ggplot --upgrade</code> failed for me, but <code>conda install -c conda-forge ggplot</code> did the trick.</p>
0
2016-07-31T11:14:00Z
[ "python", "python-ggplot", "rodeo" ]
Changing the value of range during iteration in Python
38,672,963
<pre><code>&gt;&gt;&gt; k = 8 &gt;&gt;&gt; for i in range(k): print i k -= 3 print k </code></pre> <p>Above the is the code which prints numbers from <code>0-7</code> if I use just <code>print i</code> in the for loop.</p> <p>I want to understand the above code how it is working, and is there any way we can update the value of variable used in <code>range(variable)</code> so it iterates differently.</p> <p>Also why it always iterates up to the initial <code>k</code> value, why the value doesn't updated. </p> <p>I know it's a silly question, but all ideas and comments are welcome. </p>
0
2016-07-30T10:40:06Z
38,672,978
<p>The expression <code>range(k)</code> is evaluated just <em>once</em>, not on every iteration. You can't set <code>k</code> and expect the <code>range(k)</code> result to change, no. From the <a href="https://docs.python.org/2/reference/compound_stmts.html#the-for-statement" rel="nofollow"><code>for</code> statement documentation</a>:</p> <blockquote> <p>The expression list is evaluated once; it should yield an iterable object.</p> </blockquote> <p>You can use a <code>while</code> loop instead:</p> <pre><code>i = 0 k = 8 while i &lt; k: print i i += 1 k -= 3 </code></pre> <p>A <code>while</code> loop does re-evaluate the test each iteration. Referencing the <a href="https://docs.python.org/2/reference/compound_stmts.html#the-while-statement" rel="nofollow"><code>while</code> statement documentation</a>:</p> <blockquote> <p>This repeatedly tests the expression and, if it is true, executes the first suite</p> </blockquote>
2
2016-07-30T10:42:14Z
[ "python", "python-2.7", "loops", "range" ]
Changing the value of range during iteration in Python
38,672,963
<pre><code>&gt;&gt;&gt; k = 8 &gt;&gt;&gt; for i in range(k): print i k -= 3 print k </code></pre> <p>Above the is the code which prints numbers from <code>0-7</code> if I use just <code>print i</code> in the for loop.</p> <p>I want to understand the above code how it is working, and is there any way we can update the value of variable used in <code>range(variable)</code> so it iterates differently.</p> <p>Also why it always iterates up to the initial <code>k</code> value, why the value doesn't updated. </p> <p>I know it's a silly question, but all ideas and comments are welcome. </p>
0
2016-07-30T10:40:06Z
38,672,984
<p>You can't change the range after it's been generated. In Python 2, <code>range(k)</code> will make a list of integers from 0 to k, like this: <code>[0, 1, 2, 3, 4, 5, 6, 7]</code>. Changing <code>k</code> after the list has been made will do nothing.</p> <p>If you want to change the number to iterate to, you could use a while loop, like this:</p> <pre><code>k = 8 i = 0 while i &lt; k: print i k -= 3 i += 1 </code></pre>
1
2016-07-30T10:42:51Z
[ "python", "python-2.7", "loops", "range" ]
Changing the value of range during iteration in Python
38,672,963
<pre><code>&gt;&gt;&gt; k = 8 &gt;&gt;&gt; for i in range(k): print i k -= 3 print k </code></pre> <p>Above the is the code which prints numbers from <code>0-7</code> if I use just <code>print i</code> in the for loop.</p> <p>I want to understand the above code how it is working, and is there any way we can update the value of variable used in <code>range(variable)</code> so it iterates differently.</p> <p>Also why it always iterates up to the initial <code>k</code> value, why the value doesn't updated. </p> <p>I know it's a silly question, but all ideas and comments are welcome. </p>
0
2016-07-30T10:40:06Z
38,673,138
<p>If you do want to change k and affect the loop you need to make sure you are iterating over mutable object. For example:</p> <pre><code>k = list(range(8)) for i in k: print(i) k.pop() k.pop() k.pop() print(k) </code></pre> <p>Or alternatively:</p> <pre><code>k = list(range(8)) for i in k: print(i) k[:] = k[:-3] print(k) </code></pre> <p>Both will result with</p> <pre><code>0 [0, 1, 2, 3, 4] 1 [0, 1] </code></pre>
0
2016-07-30T10:59:39Z
[ "python", "python-2.7", "loops", "range" ]
How to do POST/GET request in python?
38,673,106
<p>I have a python server which parses a HTML page, the script runs fine. However I have an android application which will call this server by sending an argument i.e. a URL. </p> <p>I want the server to get the URL posted by the android application and parse the data of the HTML page.</p> <p>My queries are :- Which method should I use ? <strong>GET</strong> or <strong>POST</strong></p> <p>I have gone through tutorials and I think it is the POST method. </p> <p>Below is my script/server which I made. Kindly suggest me what edits should be done.</p> <pre><code>import cherrypy import ConfigParser import json import mimetypes import os from jinja2 import Environment, FileSystemLoader from bs4 import BeautifulSoup import requests import urlparse from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import SocketServer ######################################################################## details_array=[] small_details_array=[] price_cell_array=[] lst = [] URL_path class S(BaseHTTPRequestHandler): def do_GET(self): self._set_headers() URL_path = urlparse.urlparse(self.path) request_id = URL_path.path def do_POST(self): self._set_headers() URL_path = urlparse.urlparse(self.path) request_id = URL_path.path r = requests.get(URL_path)#the URL_path holds the URL data = r.text soup = BeautifulSoup(data,"html.parser") table = soup.find('table',{'class':'table'}) s="" targetFile=open("plist","w") detailtext = table.findAll('div',{'class':'detailtext'}) for det in detailtext: details_array.append(det.text) smalldetails = table.findAll('div',{'style':'padding-top:5px'}) for smallDet in smalldetails: small_details_array.append(smallDet.text); price_cells = table.findAll('td', {'class': 'pricecell'}) for price_cell in price_cells: price_cell_array.append(price_cell.text) for i in range(len(details_array)): d_arr = {} d_arr['detail']=details_array[i] temp = small_details_array[i].split('\n') d_arr['talktime'] = temp[1] d_arr['keyword']=temp[3] tempnew = price_cell_array[i].split('\n') d_arr['price'] = tempnew[1] d_arr['validity'] = tempnew[3] # global list lst.append(d_arr) t_arr={} t_arr['events'] = lst; print json.dumps(t_arr) targetFile.write("[TopUpList]"+"\n"+"events=") targetFile.write(json.dumps(t_arr)) targetFile.write('\n[culturalEvents]\nevents={"events": [{"venue": "bangalore", "name": "Culttest"}]}') targetFile.close() ######################################################################### class Server(): @cherrypy.expose def index(self): return "Seems Like You're Lost :D" @cherrypy.expose def eventsList(self,choice): message="Success, Event List Obtained" status_code=0; events=[] try: if choice.title() == "Cultural": events = cultural_event_list['events'] elif choice.title() == "Prodlisting": events = lists['events'] else: status_code=-1 message="Failed, No Such Event Type Enlisted" except: status_code=-1 message="Failed, Server Error! Error Occured while retreiving Event List" return json.dumps({'status_code':status_code,'message':message,'events':events}) @cherrypy.expose def eventsStatus(self,choice): message="Success, Event List Obtained" status_code=0; events=[] try: if choice.title() == "Cultural": events = cultural_event_list['events'] elif choice.title() == "Prodlisting": events = lists['events'] else: status_code=-1 message="Failed, No Such Event Type Enlisted" except: status_code=-1 message="Failed, Server Error! Error Occured while retreiving Event List" return json.dumps({'status_code':status_code,'message':message,'hash':json.dumps(events).__hash__()}) if __name__ == '__main__': ''' Setting up the Server with Specified Configuration''' ''' config = ConfigParser.RawConfigParser() config.read('server.conf') cherrypy.server.socket_host = config.get('server','host') cherrypy.server.socket_port = int(config.get('server','port')) cherrypy.server.socket_host = '127.0.0.1' cherrypy.server.socket_port = 5000 ''' list = ConfigParser.RawConfigParser() cherrypy.config.update({'server.socket_host': '0.0.0.0',}) cherrypy.config.update({'server.socket_port': int(os.environ.get('PORT', '5000')),}) list.read('plist')#the file from where it reads lists=json.loads(list.get('TopUpList','events')) cultural_event_list=json.loads(list.get('culturalEvents','events')) cherrypy.quickstart(Server()) </code></pre> <p>P.S. I think the android part needs a POST request to be sent to the python server, kindly correct me if I am wrong.</p>
0
2016-07-30T10:56:20Z
38,673,294
<p>GET - Requests data from a specified resource POST - Submits data to be processed to a specified resource</p> <p>So if you want to submit data, use POST</p> <p>See: <a href="http://www.w3schools.com/tags/ref_httpmethods.asp" rel="nofollow">http://www.w3schools.com/tags/ref_httpmethods.asp</a></p>
0
2016-07-30T11:14:44Z
[ "android", "python" ]
How to do POST/GET request in python?
38,673,106
<p>I have a python server which parses a HTML page, the script runs fine. However I have an android application which will call this server by sending an argument i.e. a URL. </p> <p>I want the server to get the URL posted by the android application and parse the data of the HTML page.</p> <p>My queries are :- Which method should I use ? <strong>GET</strong> or <strong>POST</strong></p> <p>I have gone through tutorials and I think it is the POST method. </p> <p>Below is my script/server which I made. Kindly suggest me what edits should be done.</p> <pre><code>import cherrypy import ConfigParser import json import mimetypes import os from jinja2 import Environment, FileSystemLoader from bs4 import BeautifulSoup import requests import urlparse from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import SocketServer ######################################################################## details_array=[] small_details_array=[] price_cell_array=[] lst = [] URL_path class S(BaseHTTPRequestHandler): def do_GET(self): self._set_headers() URL_path = urlparse.urlparse(self.path) request_id = URL_path.path def do_POST(self): self._set_headers() URL_path = urlparse.urlparse(self.path) request_id = URL_path.path r = requests.get(URL_path)#the URL_path holds the URL data = r.text soup = BeautifulSoup(data,"html.parser") table = soup.find('table',{'class':'table'}) s="" targetFile=open("plist","w") detailtext = table.findAll('div',{'class':'detailtext'}) for det in detailtext: details_array.append(det.text) smalldetails = table.findAll('div',{'style':'padding-top:5px'}) for smallDet in smalldetails: small_details_array.append(smallDet.text); price_cells = table.findAll('td', {'class': 'pricecell'}) for price_cell in price_cells: price_cell_array.append(price_cell.text) for i in range(len(details_array)): d_arr = {} d_arr['detail']=details_array[i] temp = small_details_array[i].split('\n') d_arr['talktime'] = temp[1] d_arr['keyword']=temp[3] tempnew = price_cell_array[i].split('\n') d_arr['price'] = tempnew[1] d_arr['validity'] = tempnew[3] # global list lst.append(d_arr) t_arr={} t_arr['events'] = lst; print json.dumps(t_arr) targetFile.write("[TopUpList]"+"\n"+"events=") targetFile.write(json.dumps(t_arr)) targetFile.write('\n[culturalEvents]\nevents={"events": [{"venue": "bangalore", "name": "Culttest"}]}') targetFile.close() ######################################################################### class Server(): @cherrypy.expose def index(self): return "Seems Like You're Lost :D" @cherrypy.expose def eventsList(self,choice): message="Success, Event List Obtained" status_code=0; events=[] try: if choice.title() == "Cultural": events = cultural_event_list['events'] elif choice.title() == "Prodlisting": events = lists['events'] else: status_code=-1 message="Failed, No Such Event Type Enlisted" except: status_code=-1 message="Failed, Server Error! Error Occured while retreiving Event List" return json.dumps({'status_code':status_code,'message':message,'events':events}) @cherrypy.expose def eventsStatus(self,choice): message="Success, Event List Obtained" status_code=0; events=[] try: if choice.title() == "Cultural": events = cultural_event_list['events'] elif choice.title() == "Prodlisting": events = lists['events'] else: status_code=-1 message="Failed, No Such Event Type Enlisted" except: status_code=-1 message="Failed, Server Error! Error Occured while retreiving Event List" return json.dumps({'status_code':status_code,'message':message,'hash':json.dumps(events).__hash__()}) if __name__ == '__main__': ''' Setting up the Server with Specified Configuration''' ''' config = ConfigParser.RawConfigParser() config.read('server.conf') cherrypy.server.socket_host = config.get('server','host') cherrypy.server.socket_port = int(config.get('server','port')) cherrypy.server.socket_host = '127.0.0.1' cherrypy.server.socket_port = 5000 ''' list = ConfigParser.RawConfigParser() cherrypy.config.update({'server.socket_host': '0.0.0.0',}) cherrypy.config.update({'server.socket_port': int(os.environ.get('PORT', '5000')),}) list.read('plist')#the file from where it reads lists=json.loads(list.get('TopUpList','events')) cultural_event_list=json.loads(list.get('culturalEvents','events')) cherrypy.quickstart(Server()) </code></pre> <p>P.S. I think the android part needs a POST request to be sent to the python server, kindly correct me if I am wrong.</p>
0
2016-07-30T10:56:20Z
38,673,303
<p>Based on conclusion that you just want to get some information without updating anything on server side I can tell that GET request will be enough and theoretically more idiomatically. </p> <p>So you just should make request with URL like www.yourdomain.com/?q=domaintocrawl.com and get parsed data in response.</p>
0
2016-07-30T11:15:27Z
[ "android", "python" ]
Django - Form validation not happening
38,673,171
<p>The following is my code for creating a form:</p> <pre><code>from django import forms class Register(forms.Form): username = forms.CharField(label='', max_length=64, required=True) firstname = forms.CharField(label='', max_length=64, required=True) surname = forms.CharField(label='sur name', max_length=64, required=True) email = forms.EmailField() </code></pre> <p>The code of my view.py is as follows:</p> <pre><code>from .forms import Register def register(request): form = Register() return render(request, 'app/register.html', {'form': form}) </code></pre> <p>It is displaying the form in the webpage but its not validating the username, firstname, and surname; whereas its validating the emailfield.</p> <p>I tried using the clean method, and my new forms.py is as follows:</p> <pre><code>from django import forms class Register(forms.Form): username = forms.CharField(label='', max_length=64, required=True) firstname = forms.CharField(label='', max_length=64, required=True) surname = forms.CharField(label='sur name', max_length=64, required=True) email = forms.EmailField() def clean_surname(self): data = self.cleaned_data['surname'] if not data: raise forms.ValidationError("This field is required") return data </code></pre> <p>What might be the problem? Am I doing something wrong. Please help me with this, I am new to Django.</p>
0
2016-07-30T11:02:48Z
38,673,218
<p>You're not passing post data into your form. It should look like this:</p> <pre><code>from .forms import Register def register(request): form = Register(request.POST or None) if request.method == 'POST' and form.is_valid(): # your action when form is valid else: return render(request, 'app/register.html', {'form': form}) </code></pre> <p><code>or None</code> after <code>request.POST</code> will ensure that empty POST dictionary won't be passed into your form, so validation won't be triggered on first load of page - when there is nothing submitted.</p> <p>Also, validation of email field probably comes from your browser, not from django. </p>
1
2016-07-30T11:08:01Z
[ "python", "django" ]
Django - Form validation not happening
38,673,171
<p>The following is my code for creating a form:</p> <pre><code>from django import forms class Register(forms.Form): username = forms.CharField(label='', max_length=64, required=True) firstname = forms.CharField(label='', max_length=64, required=True) surname = forms.CharField(label='sur name', max_length=64, required=True) email = forms.EmailField() </code></pre> <p>The code of my view.py is as follows:</p> <pre><code>from .forms import Register def register(request): form = Register() return render(request, 'app/register.html', {'form': form}) </code></pre> <p>It is displaying the form in the webpage but its not validating the username, firstname, and surname; whereas its validating the emailfield.</p> <p>I tried using the clean method, and my new forms.py is as follows:</p> <pre><code>from django import forms class Register(forms.Form): username = forms.CharField(label='', max_length=64, required=True) firstname = forms.CharField(label='', max_length=64, required=True) surname = forms.CharField(label='sur name', max_length=64, required=True) email = forms.EmailField() def clean_surname(self): data = self.cleaned_data['surname'] if not data: raise forms.ValidationError("This field is required") return data </code></pre> <p>What might be the problem? Am I doing something wrong. Please help me with this, I am new to Django.</p>
0
2016-07-30T11:02:48Z
38,673,364
<p>To validate the form you need to populate it with data from the POST request and check if it's valid. Your view should look like this:</p> <pre><code>from .forms import Register def register(request): if request.method == 'POST' # process form data # create form instance, populate it with data form = Register(request.POST) # check if the data is valid if form.is_valid(): # process/save the data # ... # then redirect to a new URL: return HttpResponseRedirect('/a/new/url/') else: # GET or other method, create a blank form form = Register() return render(request, 'app/register.html', {'form': form}) </code></pre> <p>more in the <a href="https://docs.djangoproject.com/en/1.9/topics/forms/#the-view" rel="nofollow">documentation</a>.</p>
3
2016-07-30T11:21:26Z
[ "python", "django" ]
django: How to avoid permission error on migration
38,673,195
<p>I am trying to deploy a django application on a virtual server running ubuntu 16.04.</p> <pre><code>python manage.py makemigrations </code></pre> <p>leads to the following traceback, after some models and fields have been created:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 12, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/sysadmin/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/sysadmin/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sysadmin/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/sysadmin/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/sysadmin/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 150, in handle self.write_migration_files(changes) File "/home/sysadmin/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 179, in write_migration_files with open(writer.path, "wb") as fh: IOError: [Errno 13] Permission denied: u'/home/sysadmin/public_html/aegee-stuttgart.org/aegeewww/migrations/0001_initial.py' </code></pre> <p>I also tried:</p> <pre><code>sudo python manage.py makemigrations </code></pre> <p>But since I am using a virtual environment, I get the following error, since django is not installed system wide:</p> <pre><code>ImportError: No module named django.core.management </code></pre> <p>How can I fix this error? The python path is recognized correctly and django is obviously installed in the venv. </p> <p>How do I have to set the permissions for the user?</p> <p>Thanks!</p>
1
2016-07-30T11:05:27Z
38,673,366
<p>You need grant access for user to migrations folder:</p> <pre><code>sudo chown &lt;your_username&gt; &lt;path_to_migrations_folder&gt; </code></pre>
1
2016-07-30T11:21:36Z
[ "python", "django", "virtualenv" ]
How to rearrange a multidimensional array
38,673,268
<p>So for various reasons that go outside of this post, I am writing a file that transfers data from one place to another. I have some of the data held in a series of multidimensional arrays</p> <p>lets pretend I have a 4 dimensional array with the following shape/dimensions: [x, y, z, n]</p> <p>How would I rearrange it into these dimensions: [n, z, y, x] OR [z, y, n, z]</p> <p>I am NOT looking for a short and quick answer or piece of code. I want to understand the answer so that for future I could do it on my own</p> <p>My idea: Flatten the array out with a series of nested for loops</p> <p><code>for n in [n, :,:,:] for x in [:, x, :,:]</code></p> <p>so on and so forth until I unravel the whole thing into a one dimensional array. But I am not sure how exactly I would get it back in the form I would like</p>
0
2016-07-30T11:12:32Z
38,673,348
<p>Transpose:</p> <pre><code>&gt;&gt;&gt; a = [[1,2,3],[4,5,6]] &gt;&gt;&gt; b = zip(*a) &gt;&gt;&gt; b [(1, 4), (2, 5), (3, 6)] </code></pre>
0
2016-07-30T11:19:29Z
[ "python", "arrays", "multidimensional-array" ]