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
How do I turn a repeated list element with delimiters into a list?
38,483,118
<p>I imported a CSV file that's basically a table with 5 headers and data sets with 5 elements. </p> <p>With this code I turned that data into a list of individuals with 5 bits of information (list within a list):</p> <pre><code>import csv readFile = open('Category.csv','r') categoryList = [] for row in csv.reader(readFile): categoryList.append(row) readFile.close() </code></pre> <p>Now I have a list of lists <code>[[a,b,c,d,e],[a,b,c,d,e],[a,b,c,d,e]...]</code></p> <p>However element 2 (<code>categoryList[i][2]</code>) or '<code>c</code>' in each list within the overall list is a string separated by a delimiter ('<code>:</code>') of variable length. How do I turn element 2 into a list itself? Basically making it look like this:</p> <pre><code>[[a,b,[1,2,3...],d,e][a,b,[1,2,3...],d,e][a,b,[1,2,3...],d,e]...] </code></pre> <p>I thought about looping through each list element and finding element 2, then use the <code>.split(':')</code> command to separate those values out. </p>
1
2016-07-20T13:46:50Z
38,483,249
<p>Not really clear about your structure but if c is a string seperated by : within then try </p> <blockquote> <p>list(c.split(':'))</p> </blockquote> <p>Let me know if it solved your problem </p>
0
2016-07-20T13:52:38Z
[ "python", "list", "csv" ]
How do I turn a repeated list element with delimiters into a list?
38,483,118
<p>I imported a CSV file that's basically a table with 5 headers and data sets with 5 elements. </p> <p>With this code I turned that data into a list of individuals with 5 bits of information (list within a list):</p> <pre><code>import csv readFile = open('Category.csv','r') categoryList = [] for row in csv.reader(readFile): categoryList.append(row) readFile.close() </code></pre> <p>Now I have a list of lists <code>[[a,b,c,d,e],[a,b,c,d,e],[a,b,c,d,e]...]</code></p> <p>However element 2 (<code>categoryList[i][2]</code>) or '<code>c</code>' in each list within the overall list is a string separated by a delimiter ('<code>:</code>') of variable length. How do I turn element 2 into a list itself? Basically making it look like this:</p> <pre><code>[[a,b,[1,2,3...],d,e][a,b,[1,2,3...],d,e][a,b,[1,2,3...],d,e]...] </code></pre> <p>I thought about looping through each list element and finding element 2, then use the <code>.split(':')</code> command to separate those values out. </p>
1
2016-07-20T13:46:50Z
38,483,286
<p>The solution you suggested is feasible. You just don't need to do it after you read the file. You can do it while taking it as a input in the first place.</p> <pre><code>for row in csv.reader(readFile): row[2] = row[2].split(":") # Split element 2 of each row before appending categoryList.append(row) </code></pre> <p><strong>Edit:</strong> I guess you know the purpose of split function. So I will explain <code>row[2]</code>.</p> <p>You have a data such as <code>[[a,b,c,d,e],[a,b,c,d,e],[a,b,c,d,e]...]</code> which means each <code>row</code> goes like <code>[a,b,c,d,e]</code>, <code>[a,b,c,d,e]</code>, <code>[a,b,c,d,e]</code>, So every row[2] corresponds to <code>c</code>. Using this way, you get to alter all <code>c</code>'s before you append and turn them in to <code>[[a,b,c,d,e],[a,b,c,d,e],[a,b,c,d,e]...]</code>.</p>
1
2016-07-20T13:54:08Z
[ "python", "list", "csv" ]
How do I turn a repeated list element with delimiters into a list?
38,483,118
<p>I imported a CSV file that's basically a table with 5 headers and data sets with 5 elements. </p> <p>With this code I turned that data into a list of individuals with 5 bits of information (list within a list):</p> <pre><code>import csv readFile = open('Category.csv','r') categoryList = [] for row in csv.reader(readFile): categoryList.append(row) readFile.close() </code></pre> <p>Now I have a list of lists <code>[[a,b,c,d,e],[a,b,c,d,e],[a,b,c,d,e]...]</code></p> <p>However element 2 (<code>categoryList[i][2]</code>) or '<code>c</code>' in each list within the overall list is a string separated by a delimiter ('<code>:</code>') of variable length. How do I turn element 2 into a list itself? Basically making it look like this:</p> <pre><code>[[a,b,[1,2,3...],d,e][a,b,[1,2,3...],d,e][a,b,[1,2,3...],d,e]...] </code></pre> <p>I thought about looping through each list element and finding element 2, then use the <code>.split(':')</code> command to separate those values out. </p>
1
2016-07-20T13:46:50Z
38,483,385
<p>Assume that you have a row like this:</p> <pre><code>row = ["foo", "bar", "1:2:3:4:5", "baz"] </code></pre> <p>To convert item <code>[2]</code> into a sublist, you can use</p> <pre><code>row[2] = row[2].split(":") # elements can be assigned to, yawn. </code></pre> <p>Now the row is <code>['foo', 'bar', ['1', '2', '3', '4', '5'], 'baz']</code></p> <p>To <em>graft</em> the split items to the "top level" of the row, you can use</p> <pre><code>row[2:3] = row[2].split(":") # slices can be assigned to, too, yay! </code></pre> <p>Now the row is <code>['foo', 'bar', '1', '2', '3', '4', '5', 'baz']</code></p> <p>This of course skips any defensive checks of the row data (can it at all be split?) that a real robust application should have.</p>
0
2016-07-20T13:58:32Z
[ "python", "list", "csv" ]
Import a list of words, dont wanna do it all over again in the code
38,483,121
<p>I don't want to post too much code, but I have code for an assignment done, the problem with my code is that every time I run a method called <code>findchildren</code>, it imports my list every time. So I tried to change my code, and my <code>findchildren</code> is working, it's currently looking like this:</p> <pre><code>from queue import Queue ordlista=[] fil=open("labb9text.txt") for line in fil.readlines(): ordlista.append(line.strip()) setlista=set() for a in ordlista: if a not in setlista: setlista.add(a) def findchildren(lista,parent): children=[] lparent=list(parent) lista.remove(parent) for word in lista: letters=list(word) count=0 i=0 for a in letters: if a==lparent[i]: count+=1 i+=1 else: i+=1 if count==2: if word not in children: children.append(word) if i&gt;2: break return children </code></pre> <p>my problem is that I have another method, which worked when I didn't have the parameter <code>lista</code> in <code>findchildren</code> (instead I imported the list over and over, which I dont wanna do, I want to import it once, in the beginning). Notice that when I call my method, I call it with <code>labb9.findchildren(labb9.ordlista,"fan")</code>. So my <code>findchildren</code> is working currently, the problem is the method right under:</p> <pre><code>def way(start,end): queue=Queue() queue.enqueue(start) visited=set() while not queue.isempty(): vertex=queue.get() if vertex==end: return True else: visited.add(vertex) s=findchildren(labb999.ordlista,start) for vertex in s: if vertex not in visited: queue.put(vertex) else: visited.add(vertex) return False </code></pre> <p>Notice that the <code>way</code>-method used to work when I imported my list to <code>findchildren</code> every time, now that I've changed it to a parameter in <code>findchildren</code>, it does not work. I'm getting the error:</p> <blockquote> <p>name "lista" is not defined.</p> </blockquote> <p>What am I doing wrong?</p>
1
2016-07-20T13:47:08Z
38,484,551
<p>Your goal is to find if there exists a path from <code>start</code> to <code>stop</code> where a path is described as words who have length two permutations overlapping.</p> <p>I think your code would be better organized as a graph and a function that operates on this graph. It would eliminate all of your problems: you can have a single copy of your word set associated with your graph object and can operate directly on that object with your function <code>way</code>.</p> <pre><code>from queue import Queue import itertools class Graph(object): def __init__(self, filename): # Creates a set, which removes duplicates automatically self.word_set = {word for word in open(filename, 'r').read().split()} def _len_2_permutations(self, word): # Create a list of length two permutations from a word return itertools.permutations(word, 2) def has_word_overlap(self, word1, word2): # If there are any overlapping length two permutations, the set will not be empty return len(set(self._len_2_permutations(word1)) &amp; set(self._len_2_permutations(word2))) &gt; 0 def find_children(self, start): # Children are those words who have overlapping length two perms return [word for word in self.word_set if self.has_word_overlap(start, word) and word != start] </code></pre> <p>Now we can define our BFS-like function:</p> <pre><code>def way(g, start, stop): queue = Queue() # Push start queue.put(start) visited = set() while not queue.empty(): # Get the top of the queue vertex = queue.get() # If it's our target, we're done if vertex == stop: return True # Otherwise, visit it visited.add(vertex) # Find its children s = g.find_children(vertex) # Push the unvisited children -- explore them later for vertex in s: if vertex not in visited: queue.put(vertex) return False </code></pre> <p>Now let's create a main:</p> <pre><code>if __name__ == "__main__": g = Graph("foo.txt") start = "fan" stop = "foo" print("There's a path from '{0}' to '{1}': {2}".format(start, stop, way(g, start, stop))) </code></pre> <p>This code isn't thoroughly tested, but it should get you on the right track.</p>
1
2016-07-20T15:21:22Z
[ "python" ]
Can't uninstall Django app
38,483,204
<p>I can't uninstall Django app. I've removed every occurence of the application in my code, removed all models and urls. Then, I removed parts of app from <code>settings.py</code> but it raises error when I remove them for <code>settings.py</code>.</p> <p>It has probably something to do with migrations but I don't get it since all migrations alre already migrated... </p> <p>Here is a traceback:</p> <pre><code>Unhandled exception in thread started by &lt;function wrapper at 0x038E6130&gt; Traceback (most recent call last): File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run self.check_migrations() File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 168, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\db\migrations\executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\db\migrations\loader.py", line 47, in __init__ self.build_graph() File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\db\migrations\loader.py", line 314, in build_graph parent = self.check_key(parent, key[0]) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\db\migrations\loader.py", line 176, in check_key raise ValueError("Dependency on unknown app: %s" % key[0]) ValueError: Dependency on unknown app: quiz </code></pre>
0
2016-07-20T13:50:42Z
38,483,842
<p>There was a problem with migrations files which contained uninstalled app's referencies. </p> <p>This is probably not a best way to do that but it worked:</p> <ol> <li>I backuped all migrations from all applications (to be able to do rollback)</li> <li>Removed all migrations</li> <li>makemigrations and migrate</li> <li>it works</li> </ol>
0
2016-07-20T14:19:11Z
[ "python", "django", "django-apps" ]
How can I replace 1s in a binary array with natural numbers, maintaining the position of 0s?
38,483,254
<p>I'm using Numpy and SciPy. I have two arrays, the first of which is binary, the second a consecutive range of natural numbers from <code>a</code> to <code>b</code> e.g.</p> <pre><code>mask = np.array([1, 1, 1, 1, 0, 0, 1, 0]) # length of 8, with 5 ones and 3 zeros vals = np.array([2, 3, 4, 5, 6, 7, 8, 9]) # length of 8, only first 5 values will be used in this case - corresponding to the 5 ones in the first array </code></pre> <p>I'd like to essentially replace the 1s in the first array with the values in the second (kept in order) e.g. the required result in this example scenario would be:</p> <pre><code>result = [2,3,4,5,0,0,6,0] </code></pre> <p>I've already tried different methods with NumPy masked arrays and the vectorise function. My current solution is below, but in order to maintain the state, I've had to introduce a global variable!</p> <pre><code>global count count = 0 def func(a,b): global count if a ==1: return b - count else: count +=1 return 0 v_func = np.vectorize(func) result = v_func(mask, vals) print result </code></pre> <p>Is there a more elegant way of doing this, (ideally using NumPy)?</p> <p>(Side note, the real arrays I'm working with are very large and so my solution needs to be sensitive to the amount of memory consumed - obviously I can convert to sparse arrays, but I've still hit memory errors a couple of times trying to find different solutions.)</p>
1
2016-07-20T13:52:52Z
38,483,322
<p>Here's one way:</p> <pre><code>In [15]: result = np.zeros_like(vals) In [16]: result[mask &gt; 0] = vals[:mask.sum()] In [17]: result Out[17]: array([2, 3, 4, 5, 0, 0, 6, 0]) </code></pre>
2
2016-07-20T13:55:34Z
[ "python", "arrays", "numpy", "scipy" ]
How can I replace 1s in a binary array with natural numbers, maintaining the position of 0s?
38,483,254
<p>I'm using Numpy and SciPy. I have two arrays, the first of which is binary, the second a consecutive range of natural numbers from <code>a</code> to <code>b</code> e.g.</p> <pre><code>mask = np.array([1, 1, 1, 1, 0, 0, 1, 0]) # length of 8, with 5 ones and 3 zeros vals = np.array([2, 3, 4, 5, 6, 7, 8, 9]) # length of 8, only first 5 values will be used in this case - corresponding to the 5 ones in the first array </code></pre> <p>I'd like to essentially replace the 1s in the first array with the values in the second (kept in order) e.g. the required result in this example scenario would be:</p> <pre><code>result = [2,3,4,5,0,0,6,0] </code></pre> <p>I've already tried different methods with NumPy masked arrays and the vectorise function. My current solution is below, but in order to maintain the state, I've had to introduce a global variable!</p> <pre><code>global count count = 0 def func(a,b): global count if a ==1: return b - count else: count +=1 return 0 v_func = np.vectorize(func) result = v_func(mask, vals) print result </code></pre> <p>Is there a more elegant way of doing this, (ideally using NumPy)?</p> <p>(Side note, the real arrays I'm working with are very large and so my solution needs to be sensitive to the amount of memory consumed - obviously I can convert to sparse arrays, but I've still hit memory errors a couple of times trying to find different solutions.)</p>
1
2016-07-20T13:52:52Z
38,483,401
<p>Here is a one liner, though I must say it is not an optimized way and not very elegant. But you can examine it for practice purposes. </p> <pre><code>a = [1, 1, 1, 1, 0, 0, 1, 0] b = [2, 3, 4, 5, 6, 7, 8, 9] c = [b[sum(a[:i])] if a[i] else 0 for i in range(len(a))] print c # Gives [2, 3, 4, 5, 0, 0, 6, 0] </code></pre>
2
2016-07-20T13:59:45Z
[ "python", "arrays", "numpy", "scipy" ]
Python - opposite of __contains__
38,483,274
<p><strong>GENERAL QUESTION</strong></p> <p>I was wondering if there exists a Python opposite to <code>__contains__</code> (i.e., something like <code>__notcontains__</code>).</p> <p><strong>MY EXAMPLE</strong></p> <p>I need it for the following piece of code:</p> <pre><code>df_1 = df[(df.id1 != id1_array) | (df.id2.apply(id2_array.__contains__)] df_2 = df[(df.id1 == id1_array) &amp; (df.id2.apply(id2_array.__notcontains__)] </code></pre> <p>In other words, in <code>df1</code> I want only observations for which <code>id1</code> <em>is not in</em> <code>id1_array1</code> <strong>or</strong> <code>id2</code> <em>is in</em> <code>id2_array</code>, while for <code>df2</code> I want only observations for which <code>id1</code> <em>is in</em> <code>id1_array</code> <strong>and</strong> <code>id2</code> <em>is not in</em> <code>id2_array</code>.</p> <p>Who can help me out here? Thanks in advance!</p>
2
2016-07-20T13:53:42Z
38,483,417
<p>EDIT: I didn't notice this was using panda's specifically. My answer may not be accurate. </p> <p>Generally, the magic functions (anything with __'s before and after) are not meant to be called directly. In this case, __contains__ is referenced by using the <code>in</code> keyword.</p> <pre><code>&gt;&gt;&gt; a = ['b'] &gt;&gt;&gt; 'b' in a True &gt;&gt;&gt; 'b' not in a False </code></pre>
2
2016-07-20T14:00:27Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Python - opposite of __contains__
38,483,274
<p><strong>GENERAL QUESTION</strong></p> <p>I was wondering if there exists a Python opposite to <code>__contains__</code> (i.e., something like <code>__notcontains__</code>).</p> <p><strong>MY EXAMPLE</strong></p> <p>I need it for the following piece of code:</p> <pre><code>df_1 = df[(df.id1 != id1_array) | (df.id2.apply(id2_array.__contains__)] df_2 = df[(df.id1 == id1_array) &amp; (df.id2.apply(id2_array.__notcontains__)] </code></pre> <p>In other words, in <code>df1</code> I want only observations for which <code>id1</code> <em>is not in</em> <code>id1_array1</code> <strong>or</strong> <code>id2</code> <em>is in</em> <code>id2_array</code>, while for <code>df2</code> I want only observations for which <code>id1</code> <em>is in</em> <code>id1_array</code> <strong>and</strong> <code>id2</code> <em>is not in</em> <code>id2_array</code>.</p> <p>Who can help me out here? Thanks in advance!</p>
2
2016-07-20T13:53:42Z
38,483,500
<p>To answer how to do this in pure pandas you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> and use the negation operator <code>~</code> to invert the boolean series:</p> <pre><code>df_1 = df[(df.id1 != id1_array) | (df.id2.isin(id2_array)] df_2 = df[(df.id1 == id1_array) &amp; (~df.id2.isin(id2_array)] </code></pre> <p>This will be faster than using <code>apply</code> on a larger dataset as <code>isin</code> is vectorised</p> <p>When using the comparison operators such as <code>==</code> and <code>!=</code> this will return <code>True/False</code> where the array values are same/different in the same position. If you are testing just for membership, i.e. does a list of values exist anywhere in the array then use <code>isin</code> this will also return a boolean series where matches are found, to invert the array use <code>~</code>.</p> <p>Also as a general rule, avoid using <code>apply</code> unless it's not possible, the reason is that <code>apply</code> is just syntactic sugar to execute a <code>for</code> loop on the df and this isn't vectorised. There are usually ways to achieve the same result without using <code>apply</code> if you dig hard enough.</p>
3
2016-07-20T14:03:44Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Python - opposite of __contains__
38,483,274
<p><strong>GENERAL QUESTION</strong></p> <p>I was wondering if there exists a Python opposite to <code>__contains__</code> (i.e., something like <code>__notcontains__</code>).</p> <p><strong>MY EXAMPLE</strong></p> <p>I need it for the following piece of code:</p> <pre><code>df_1 = df[(df.id1 != id1_array) | (df.id2.apply(id2_array.__contains__)] df_2 = df[(df.id1 == id1_array) &amp; (df.id2.apply(id2_array.__notcontains__)] </code></pre> <p>In other words, in <code>df1</code> I want only observations for which <code>id1</code> <em>is not in</em> <code>id1_array1</code> <strong>or</strong> <code>id2</code> <em>is in</em> <code>id2_array</code>, while for <code>df2</code> I want only observations for which <code>id1</code> <em>is in</em> <code>id1_array</code> <strong>and</strong> <code>id2</code> <em>is not in</em> <code>id2_array</code>.</p> <p>Who can help me out here? Thanks in advance!</p>
2
2016-07-20T13:53:42Z
38,483,503
<p>No there is no <code>__notcontains__</code> method or similar. When using <code>x not in y</code>, the method <code>__contains__</code> is actually used, as shown bellow:</p> <pre><code>class MyList(list): def __contains__(self, x): print("__contains__ is called") return super().__contains__(x) l = MyList([1, 2, 3]) 1 in l # __contains__ is called 1 not in l # __contains__ is called </code></pre>
2
2016-07-20T14:03:47Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Error: Failed to enable GUI event loop integration for 'qt' while importing pandas
38,483,517
<p>I use PyCharm Pro 2016.1.4 and pandas 18.1. I'm running into an issue whenever I import pandas. It happened after I updated PyCharm Pro (from 2016.1.3) and IPython 5.</p> <p>Here's what the console shows me when I start it and then import pandas: </p> <pre><code>C:\Anaconda2\python.exe "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\pydevconsole.py" 51602 51603 Python 2.7.12 |Anaconda 2.4.1 (64-bit)| (default, Jun 29 2016, 11:42:13) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 4.0.1 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object', use 'object??' for extra details. PyDev console: using IPython 4.0.1 import sys; print('Python %s on %s' % (sys.version, sys.platform)) sys.path.extend(['C:\\Abc\\Dev\\Code\\abc']) Python 2.7.12 |Anaconda 2.4.1 (64-bit)| (default, Jun 29 2016, 11:42:13) [MSC v.1500 32 bit (Intel)] on win32 In[2]: import pandas Backend Qt4Agg is interactive backend. Turning interactive mode on. Failed to enable GUI event loop integration for 'qt' Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\_pydev_bundle\pydev_console_utils.py", line 544, in do_enable_gui enable_gui(guiname) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\pydev_ipython\inputhook.py", line 509, in enable_gui return gui_hook(app) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\pydev_ipython\inputhook.py", line 194, in enable_qt4 from pydev_ipython.inputhookqt4 import create_inputhook_qt4 File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\pydev_ipython\inputhookqt4.py", line 25, in &lt;module&gt; from pydev_ipython.qt_for_kernel import QtCore, QtGui File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\pydev_ipython\qt_for_kernel.py", line 80, in &lt;module&gt; QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts) File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\pydev_ipython\qt_loaders.py", line 241, in load_qt result = loaders[api]() File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\pydev_ipython\qt_loaders.py", line 165, in import_pyqt4 import sip File "C:\Program Files (x86)\JetBrains\PyCharm 2016.1.4\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) ImportError: DLL load failed: %1 is not a valid Win32 application. </code></pre> <p>Any idea what's wrong? Thank you! </p>
0
2016-07-20T14:04:16Z
39,664,828
<p>It has to do with Qt DLL version conflicts. I was able to get it working by doing <code>conda update --all</code></p> <p>This seems to have fixed a missing dependancy: I see a copy of QtCore4.dll in C:\Anaconda3\Library\bin and C:\Anaconda3\Library\lib that weren't there before.</p> <p>Based on the research below, other people copy QtCore4.dll, QtGui4.dll to C:\Anaconda3\Lib\site-packages\PyQt4\bin, or they delete other path's from their environment</p> <p>Here is some background:</p> <p><a href="http://stackoverflow.com/questions/2738879/cannot-import-pyqt4-qtgui">Cannot import PyQt4.QtGui</a></p> <p><a href="http://stackoverflow.com/questions/34008610/ipython-jupyter-qtconsole-fails-to-start-in-anaconda-2-4-0">iPython/jupyter qtconsole fails to start in anaconda 2.4.0</a></p> <p><a href="http://stackoverflow.com/questions/4616834/pyqt4-need-to-move-dlls-to-package-root">PyQt4 Need to move DLLs to package root</a></p> <p><a href="https://github.com/ContinuumIO/anaconda-issues/issues/540" rel="nofollow">https://github.com/ContinuumIO/anaconda-issues/issues/540</a></p>
0
2016-09-23T15:47:50Z
[ "python", "qt", "pandas" ]
Python: opencv (cv2) image slicing not working?
38,483,554
<p>I've got an image loaded in grayscale via <code>img = cv2.imread("myimg.jpg", 0)</code>.</p> <p>Examining the value of <code>img</code> after loading, it's an <code>ndarray</code> that looks like this:</p> <pre><code>[[53,53,58,...,62,66,70], [52,52,57,...,68,68,90], ..., [80,80,80,...,91,92,91], [81,82,80,...,90,91,93]] </code></pre> <p>Trying to crop out a chunk of it using <code>cropped = img[top:bottom, left:right]</code> where <code>top</code>, <code>bottom</code>, <code>left</code> and <code>right</code> are all integers.</p> <p>However, cropped is winding up as an empty <code>ndarray</code>.</p> <p>Why would this be?</p>
0
2016-07-20T14:05:54Z
38,483,799
<p>You are trying to split your array while supplying top = 337 and bottom = 271. Numpy works the other way around. Try to split it like this: <code>img[bottom:top, left:right]</code> or just invert the values of <code>top</code> and <code>bottom</code> so that you have <code>img[a:b, c:d]</code> with <code>a &lt; b</code> and <code>c &lt; d</code>.</p>
0
2016-07-20T14:17:18Z
[ "python", "opencv", "numpy", "imread" ]
python socket server with java client - socket.error: [Errno 32] Broken pipe
38,483,555
<p>I'm trying to send commands to a rasberry pi using a python based socket server, where the server will get various string command, do something and then wait for the next command.</p> <p>I have a socket server written in python running on a raspberry pi:</p> <pre><code>import socket HOST = '' # Symbolic name meaning the local host PORT = 11113 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1] sys.exit() print 'Socket bind complete' def listen(): s.listen(1) print 'Socket now listening' # Accept the connection (conn, addr) = s.accept() print 'Server: got connection from client ' + addr[0] + ':' + str(addr[1]) while 1: data = conn.recv(1024) tokens = data.split(' ', 1) command = tokens[0].strip() print command # Send reply conn.send("Ack") break conn.close() # s.close() listen() print "connection closed" listen() </code></pre> <p>Java Client:</p> <pre><code>public class Client { public static void main(String... args) throws Exception { int portNum = 11113; Socket socket; socket = new Socket("192.168.1.20", portNum); DataOutputStream dout=new DataOutputStream(socket.getOutputStream()); dout.writeUTF("Hello"); dout.flush(); dout.close(); socket.close(); } } </code></pre> <p>Python Server starts ok and waits for a connection, when I run the client code the server outputs the <code>hello</code> text followed by a lot of whitespace and then </p> <p>edit: the white space is that <code>while 1</code> loop outputing the incoming data and then looping out of control until it crashes. I want to output the text and keep listing for more connections. </p> <p>edit 2: fixed python so it doesn't crash - i leave the loop and restart the listen process - which works. If this script can be improved please lmk - it doesn't look like it will scale.</p>
0
2016-07-20T14:05:56Z
38,483,793
<p><strong>errno.32 is: Broken pipe(the broken pipe error occurs if one end of the TCP socket closes connection(using disconnect) or gets killed and the other</strong></p> <p>In you java client, you send some data and close the socket right away which may cause the result.I am not familiar with java.But here is two things below you need to follow.</p> <p>1.remove sock.close() in java client.</p> <p>2.make your java client sleep for a while, but exit.</p>
1
2016-07-20T14:17:04Z
[ "java", "python", "sockets" ]
Fast way to select from numpy array without intermediate index array
38,483,570
<p>Given the following 2-column array, I want to select items from the second column that correspond to "edges" in the first column. This is just an example, as in reality my <code>a</code> has potentially millions of rows. So, ideally I'd like to do this as fast as possible, and without creating intermediate results.</p> <pre><code>import numpy as np a = np.array([[1,4],[1,2],[1,3],[2,6],[2,1],[2,8],[2,3],[2,1], [3,6],[3,7],[5,4],[5,9],[5,1],[5,3],[5,2],[8,2], [8,6],[8,8]]) </code></pre> <p>i.e. I want to find the result,</p> <pre><code>desired = np.array([4,6,6,4,2]) </code></pre> <p>which is entries in <code>a[:,1]</code> corresponding to where <code>a[:,0]</code> changes.</p> <p>One solution is,</p> <pre><code>b = a[(a[1:,0]-a[:-1,0]).nonzero()[0]+1, 1] </code></pre> <p>which gives <code>np.array([6,6,4,2])</code>, I could simply prepend the first item, no problem. However, this creates an intermediate array of the indexes of the first items. I could avoid the intermediate by using a list comprehension:</p> <pre><code>c = [a[i+1,1] for i,(x,y) in enumerate(zip(a[1:,0],a[:-1,0])) if x!=y] </code></pre> <p>This also gives <code>[6,6,4,2]</code>. Assuming a generator-based <code>zip</code> (true in Python 3), this doesn't need to create an intermediate representation and should be very memory efficient. However, the inner loop is not numpy, and it necessitates generating a list which must be subsequently turned back into a numpy array.</p> <p>Can you come up with a numpy-only version with the memory efficiency of <code>c</code> but the speed efficiency of <code>b</code>? Ideally only one pass over <code>a</code> is needed.</p> <p>(Note that measuring the speed won't help much here, unless <code>a</code> is very big, so I wouldn't bother with benchmarking this, I just want something that is theoretically fast and memory efficient. For example, you can assume rows in <code>a</code> are streamed from a file and are slow to access -- another reason to avoid the <code>b</code> solution, as it requires a second random-access pass over <code>a</code>.)</p> <p>Edit: a way to generate a large <code>a</code> matrix for testing:</p> <pre><code>from itertools import repeat N, M = 100000, 100 a = np.array(zip([x for y in zip(*repeat(np.arange(N),M)) for x in y ], np.random.random(N*M))) </code></pre>
2
2016-07-20T14:06:44Z
38,483,618
<p>I am afraid if you are looking to do this in a vectorized way, you can't avoid an intermediate array, as there's no built-in for it.</p> <p>Now, let's look for vectorized approaches other than <code>nonzero()</code>, which might be more performant. Going by the same idea of performing differentiation as with the original code of <code>(a[1:,0]-a[:-1,0])</code>, we can use boolean indexing after looking for non-zero differentiations that correspond to "edges" or shifts.</p> <p>Thus, we would have a vectorized approach like so -</p> <pre><code>a[np.append(True,np.diff(a[:,0])!=0),1] </code></pre> <p><strong>Runtime test</strong></p> <p>The original solution <code>a[(a[1:,0]-a[:-1,0]).nonzero()[0]+1,1]</code> would skip the first row. But, let's just say for the sake of timing purposes, it's a valid result. Here's the runtimes with it against the proposed solution in this post -</p> <pre><code>In [118]: from itertools import repeat ...: N, M = 100000, 2 ...: a = np.array(zip([x for y in zip(*repeat(np.arange(N),M))\ for x in y ], np.random.random(N*M))) ...: In [119]: %timeit a[(a[1:,0]-a[:-1,0]).nonzero()[0]+1,1] 100 loops, best of 3: 6.31 ms per loop In [120]: %timeit a[1:][np.diff(a[:,0])!=0,1] 100 loops, best of 3: 4.51 ms per loop </code></pre> <p>Now, let's say you want to include the first row too. The updated runtimes would look something like this -</p> <pre><code>In [123]: from itertools import repeat ...: N, M = 100000, 2 ...: a = np.array(zip([x for y in zip(*repeat(np.arange(N),M))\ for x in y ], np.random.random(N*M))) ...: In [124]: %timeit a[np.append(0,(a[1:,0]-a[:-1,0]).nonzero()[0]+1),1] 100 loops, best of 3: 6.8 ms per loop In [125]: %timeit a[np.append(True,np.diff(a[:,0])!=0),1] 100 loops, best of 3: 5 ms per loop </code></pre>
0
2016-07-20T14:08:39Z
[ "python", "arrays", "performance", "numpy" ]
Fast way to select from numpy array without intermediate index array
38,483,570
<p>Given the following 2-column array, I want to select items from the second column that correspond to "edges" in the first column. This is just an example, as in reality my <code>a</code> has potentially millions of rows. So, ideally I'd like to do this as fast as possible, and without creating intermediate results.</p> <pre><code>import numpy as np a = np.array([[1,4],[1,2],[1,3],[2,6],[2,1],[2,8],[2,3],[2,1], [3,6],[3,7],[5,4],[5,9],[5,1],[5,3],[5,2],[8,2], [8,6],[8,8]]) </code></pre> <p>i.e. I want to find the result,</p> <pre><code>desired = np.array([4,6,6,4,2]) </code></pre> <p>which is entries in <code>a[:,1]</code> corresponding to where <code>a[:,0]</code> changes.</p> <p>One solution is,</p> <pre><code>b = a[(a[1:,0]-a[:-1,0]).nonzero()[0]+1, 1] </code></pre> <p>which gives <code>np.array([6,6,4,2])</code>, I could simply prepend the first item, no problem. However, this creates an intermediate array of the indexes of the first items. I could avoid the intermediate by using a list comprehension:</p> <pre><code>c = [a[i+1,1] for i,(x,y) in enumerate(zip(a[1:,0],a[:-1,0])) if x!=y] </code></pre> <p>This also gives <code>[6,6,4,2]</code>. Assuming a generator-based <code>zip</code> (true in Python 3), this doesn't need to create an intermediate representation and should be very memory efficient. However, the inner loop is not numpy, and it necessitates generating a list which must be subsequently turned back into a numpy array.</p> <p>Can you come up with a numpy-only version with the memory efficiency of <code>c</code> but the speed efficiency of <code>b</code>? Ideally only one pass over <code>a</code> is needed.</p> <p>(Note that measuring the speed won't help much here, unless <code>a</code> is very big, so I wouldn't bother with benchmarking this, I just want something that is theoretically fast and memory efficient. For example, you can assume rows in <code>a</code> are streamed from a file and are slow to access -- another reason to avoid the <code>b</code> solution, as it requires a second random-access pass over <code>a</code>.)</p> <p>Edit: a way to generate a large <code>a</code> matrix for testing:</p> <pre><code>from itertools import repeat N, M = 100000, 100 a = np.array(zip([x for y in zip(*repeat(np.arange(N),M)) for x in y ], np.random.random(N*M))) </code></pre>
2
2016-07-20T14:06:44Z
38,484,412
<p>Ok actually I found a solution, just learned about <code>np.fromiter</code>, which can build a numpy array based on a generator:</p> <pre><code>d = np.fromiter((a[i+1,1] for i,(x,y) in enumerate(zip(a[1:,0],a[:-1,0])) if x!=y), int) </code></pre> <p>I think this does it, generates a numpy array without any intermediate arrays. However, the caveat is that it does not seem to be all that efficient! Forgetting what I said in the question about testing:</p> <pre><code>t = [lambda a: a[(a[1:,0]-a[:-1,0]).nonzero()[0]+1, 1], lambda a: np.array([a[i+1,1] for i,(x,y) in enumerate(zip(a[1:,0],a[:-1,0])) if x!=y]), lambda a: np.fromiter((a[i+1,1] for i,(x,y) in enumerate(zip(a[1:,0],a[:-1,0])) if x!=y), int)] from timeit import Timer [Timer(x(a)).timeit(number=10) for x in t] [0.16596235800034265, 1.811289312000099, 2.1662971739997374] </code></pre> <p>It seems the first solution is drastically faster! I assume this is because even though it generates intermediate data, it is able to perform the inner loop completely in numpy, while in the other it runs Python code for each item in the array.</p> <p>Like I said, this is why I'm not sure this kind of benchmarking makes sense here -- if accesses to <code>a</code> were much slower, the benchmark wouldn't be CPU-loaded. Thoughts?</p> <p>Not "accepting" this answer since I am hoping someone can come up with something faster.</p>
0
2016-07-20T14:43:18Z
[ "python", "arrays", "performance", "numpy" ]
Fast way to select from numpy array without intermediate index array
38,483,570
<p>Given the following 2-column array, I want to select items from the second column that correspond to "edges" in the first column. This is just an example, as in reality my <code>a</code> has potentially millions of rows. So, ideally I'd like to do this as fast as possible, and without creating intermediate results.</p> <pre><code>import numpy as np a = np.array([[1,4],[1,2],[1,3],[2,6],[2,1],[2,8],[2,3],[2,1], [3,6],[3,7],[5,4],[5,9],[5,1],[5,3],[5,2],[8,2], [8,6],[8,8]]) </code></pre> <p>i.e. I want to find the result,</p> <pre><code>desired = np.array([4,6,6,4,2]) </code></pre> <p>which is entries in <code>a[:,1]</code> corresponding to where <code>a[:,0]</code> changes.</p> <p>One solution is,</p> <pre><code>b = a[(a[1:,0]-a[:-1,0]).nonzero()[0]+1, 1] </code></pre> <p>which gives <code>np.array([6,6,4,2])</code>, I could simply prepend the first item, no problem. However, this creates an intermediate array of the indexes of the first items. I could avoid the intermediate by using a list comprehension:</p> <pre><code>c = [a[i+1,1] for i,(x,y) in enumerate(zip(a[1:,0],a[:-1,0])) if x!=y] </code></pre> <p>This also gives <code>[6,6,4,2]</code>. Assuming a generator-based <code>zip</code> (true in Python 3), this doesn't need to create an intermediate representation and should be very memory efficient. However, the inner loop is not numpy, and it necessitates generating a list which must be subsequently turned back into a numpy array.</p> <p>Can you come up with a numpy-only version with the memory efficiency of <code>c</code> but the speed efficiency of <code>b</code>? Ideally only one pass over <code>a</code> is needed.</p> <p>(Note that measuring the speed won't help much here, unless <code>a</code> is very big, so I wouldn't bother with benchmarking this, I just want something that is theoretically fast and memory efficient. For example, you can assume rows in <code>a</code> are streamed from a file and are slow to access -- another reason to avoid the <code>b</code> solution, as it requires a second random-access pass over <code>a</code>.)</p> <p>Edit: a way to generate a large <code>a</code> matrix for testing:</p> <pre><code>from itertools import repeat N, M = 100000, 100 a = np.array(zip([x for y in zip(*repeat(np.arange(N),M)) for x in y ], np.random.random(N*M))) </code></pre>
2
2016-07-20T14:06:44Z
38,485,931
<p>I think what you are looking for is called the convolution operation. The np.convolve function does this. Convolve function in most of the libraries is optimised not to include any loops and using cython and blas(I think its the same with numpy, although I haven't seen the code). It is evidently much faster than all the results in the above answers. Here is the code </p> <pre><code>import numpy as np kernel = np.array([1, -1]) %timeit a[np.where(np.convolve(a[:,0], kernel, mode='same'))][:,1] The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 10.4 µs per loop </code></pre> <p>Although it says that the intermediate results are cached and run times might be biased, it is still very very fast compared to using loops.</p>
0
2016-07-20T16:26:13Z
[ "python", "arrays", "performance", "numpy" ]
Fast way to select from numpy array without intermediate index array
38,483,570
<p>Given the following 2-column array, I want to select items from the second column that correspond to "edges" in the first column. This is just an example, as in reality my <code>a</code> has potentially millions of rows. So, ideally I'd like to do this as fast as possible, and without creating intermediate results.</p> <pre><code>import numpy as np a = np.array([[1,4],[1,2],[1,3],[2,6],[2,1],[2,8],[2,3],[2,1], [3,6],[3,7],[5,4],[5,9],[5,1],[5,3],[5,2],[8,2], [8,6],[8,8]]) </code></pre> <p>i.e. I want to find the result,</p> <pre><code>desired = np.array([4,6,6,4,2]) </code></pre> <p>which is entries in <code>a[:,1]</code> corresponding to where <code>a[:,0]</code> changes.</p> <p>One solution is,</p> <pre><code>b = a[(a[1:,0]-a[:-1,0]).nonzero()[0]+1, 1] </code></pre> <p>which gives <code>np.array([6,6,4,2])</code>, I could simply prepend the first item, no problem. However, this creates an intermediate array of the indexes of the first items. I could avoid the intermediate by using a list comprehension:</p> <pre><code>c = [a[i+1,1] for i,(x,y) in enumerate(zip(a[1:,0],a[:-1,0])) if x!=y] </code></pre> <p>This also gives <code>[6,6,4,2]</code>. Assuming a generator-based <code>zip</code> (true in Python 3), this doesn't need to create an intermediate representation and should be very memory efficient. However, the inner loop is not numpy, and it necessitates generating a list which must be subsequently turned back into a numpy array.</p> <p>Can you come up with a numpy-only version with the memory efficiency of <code>c</code> but the speed efficiency of <code>b</code>? Ideally only one pass over <code>a</code> is needed.</p> <p>(Note that measuring the speed won't help much here, unless <code>a</code> is very big, so I wouldn't bother with benchmarking this, I just want something that is theoretically fast and memory efficient. For example, you can assume rows in <code>a</code> are streamed from a file and are slow to access -- another reason to avoid the <code>b</code> solution, as it requires a second random-access pass over <code>a</code>.)</p> <p>Edit: a way to generate a large <code>a</code> matrix for testing:</p> <pre><code>from itertools import repeat N, M = 100000, 100 a = np.array(zip([x for y in zip(*repeat(np.arange(N),M)) for x in y ], np.random.random(N*M))) </code></pre>
2
2016-07-20T14:06:44Z
38,487,956
<p>If memory efficiency is your concern, that can be solved as such: The only intermediate of the same size-order as the input data can be made of type bool (a[1:,0] != a[:-1, 0]); and if your input data is int32, that is 8 times smaller than 'a' itself. You can count the nonzeros of that binary array to preallocate the output array as well; though that should not be very either significant if the output of the != is as sparse as your example suggests.</p>
0
2016-07-20T18:15:58Z
[ "python", "arrays", "performance", "numpy" ]
depth recognation with opencv2
38,483,591
<p>I cannot fetch a correct disparity map from a couple simple images, as shown below:</p> <h3>LEFT</h3> <p><a href="http://i.stack.imgur.com/TtLut.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/TtLut.jpg" alt="LEFT"></a></p> <h3>RIGHT</h3> <p><a href="http://i.stack.imgur.com/3pKvf.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/3pKvf.jpg" alt="RIGHT"></a></p> <h3>Disparity</h3> <p><a href="http://i.stack.imgur.com/XQaBj.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/XQaBj.jpg" alt="disparity"></a></p> <h3>The codes:</h3> <pre><code>import cv2 import numpy as np # frames buffer frames = [] # image categories cat_selected = 0 cat_list = ['open'] cat_calib = [np.load('LUMIA_CALIB.npy')] # load images def im_load(image, calib): frame = cv2.imread(image,0) if calib is not None: frame = cv2.undistort(cv2.resize(frame, (640, 480)), *calib[0]) x, y, w, h = calib[1] frame = frame[y : y + h, x : x + w] return frame for idx, im in enumerate(['left', 'right']): frames.append(im_load('images/%s/%s.jpg' %(cat_list[cat_selected], im), cat_calib[cat_selected])) cv2.namedWindow(im, cv2.cv.CV_WINDOW_NORMAL) cv2.imshow(im, frames[idx]) cv2.imwrite('%s.jpg' %im, frames[idx]) stereo = cv2.StereoBM(1, 16, 15) disparity = stereo.compute(frames[0], frames[1]) cv2.namedWindow('map', 0) cv2.imshow('map', cv2.convertScaleAbs(disparity)) cv2.imwrite('disparity.jpg', disparity) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <h1>Questions</h1> <ol> <li>What is wrong with the code and how can I fix it?</li> <li>What are the effects of the distance between cameras while computing depth?</li> <li>What is the unit of the members of the <code>disparity</code> matrix's values? </li> </ol> <hr> <p>P.S</p> <ol> <li>The codes computes the disparity map for <code>Tsukuba</code> set of images, alright though. </li> <li>I don't know if this is relevant or not but the distance between two cameras is 14.85 cm.</li> </ol>
0
2016-07-20T14:07:46Z
38,487,658
<h2>Question 1</h2> <p>You seem to have forgotten to rectify your images from a stereo calibration procedure.</p> <h2>Question 2</h2> <p>The distance between two cameras is called <em>Baseline</em>. In general, the bigger the baseline, the better the accuracy at a distance is, with a sacrifice on field of view. The opposite is true too.</p> <h2>Question 3</h2> <p>The disparity is probably in pixel if you're using Python (I'm no expert in the python API of OpenCV). In general, if you want the distance values from the triangulation (in real world unit), you'll want to use <code>reprojectImageTo3D</code> or its equivalent in Python. You will need to first calibrate your stereo rig using a chessboard (and knowing the size of the squares).</p>
0
2016-07-20T18:00:21Z
[ "python", "image", "opencv", "image-processing" ]
Django, apache-wsgi - server is serving /js and /css but cannot serve images
38,483,597
<p>Static catalog structure:</p> <pre><code>website --css --js --images --landinpage.png </code></pre> <p>Apache access log: </p> <pre><code>"GET /static/website/js/jquery.js HTTP/1.1" 200" "GET /static/website/images/landinpage.png HTTP/1.1" 404 </code></pre> <p></p> <p>HTML code:</p> <pre><code>&lt;code&gt; &lt;!-- Styles --&gt; &lt;link rel="stylesheet" type="text/css" href="/static/website/css/style.css"/&gt; &lt;style&gt; body { background: white url("/static/website/images/landinpage.png"); &lt;/code&gt; </code></pre> <p>I can see /static/website/css/style.css being loaded properly (hence 200 server response in apache logs), but when server tries to load /static/website/images/landinpage.png I am getting 404 response. I have verified file names and location </p>
0
2016-07-20T14:07:58Z
38,487,854
<p><strong>If static server apache2:</strong></p> <p>in <em>settings.py</em> add static dir</p> <pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'static') </code></pre> <p>collect static to dir</p> <pre><code>manage.py collectstatic </code></pre> <p>in apache conf add path</p> <pre><code>Alias /static/ /var/www/static/ </code></pre> <p><strong>If dev server.</strong> </p> <p>Template context processors <em>settings.py</em></p> <pre><code>'django.template.context_processors.static', </code></pre> <p><em>urls.py</em></p> <pre><code>from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) </code></pre>
0
2016-07-20T18:10:30Z
[ "python", "django", "apache", "mod-wsgi" ]
Append numpy array into an element
38,483,650
<p>I have a Numpy array of shape (5,5,3,2). I want to take the element (1,4) of that matrix, which is also a matrix of shape (3,2), and add an element to it -so it becomes a (4,2) array. The code I'm using is the following:</p> <pre><code>import numpy as np a = np.random.rand(5,5,3,2) a = np.array(a, dtype = object) #So I can have different size sub-matrices a[2][3] = np.append(a[2][3],[[1.0,1.0]],axis=0) #a[2][3] shape = (3,2) </code></pre> <p>I'm always obtaining the error: </p> <pre><code>ValueError: could not broadcast input array from shape (4,2) into shape (3,2) </code></pre> <p>I understand that the shape returned by the <code>np.append</code> function is not the same as the <code>a[2][3]</code> sub-array, but I thought that the <code>dtype=object</code> would solve my problem. However, I need to do this. Is there any way to go around this limitation? I also tried to use the <code>insert</code> function but I don't know how could I add the element in the place I want.</p>
1
2016-07-20T14:10:08Z
38,484,079
<p>The problem here, is that you try to assign to a[2][3] Make a new array instead.</p> <pre><code>new_array = np.append(a[2][3],np.array([[1.0,1.0]]),axis=0) </code></pre>
0
2016-07-20T14:29:24Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
Append numpy array into an element
38,483,650
<p>I have a Numpy array of shape (5,5,3,2). I want to take the element (1,4) of that matrix, which is also a matrix of shape (3,2), and add an element to it -so it becomes a (4,2) array. The code I'm using is the following:</p> <pre><code>import numpy as np a = np.random.rand(5,5,3,2) a = np.array(a, dtype = object) #So I can have different size sub-matrices a[2][3] = np.append(a[2][3],[[1.0,1.0]],axis=0) #a[2][3] shape = (3,2) </code></pre> <p>I'm always obtaining the error: </p> <pre><code>ValueError: could not broadcast input array from shape (4,2) into shape (3,2) </code></pre> <p>I understand that the shape returned by the <code>np.append</code> function is not the same as the <code>a[2][3]</code> sub-array, but I thought that the <code>dtype=object</code> would solve my problem. However, I need to do this. Is there any way to go around this limitation? I also tried to use the <code>insert</code> function but I don't know how could I add the element in the place I want.</p>
1
2016-07-20T14:10:08Z
38,484,492
<p>In an array of <code>object</code>, any element can be indeed an array (or any kind of object).</p> <pre><code>import numpy as np a = np.random.rand(5,5,3,2) a = np.array(a, dtype=object) # Assign an 1D array to the array element ``a[2][3][0][0]``: a[2][3][0][0] = np.arange(10) a[2][3][0][0][9] # 9 </code></pre> <p>However <code>a[2][3]</code> is not an array element, it is a whole array.</p> <pre><code>a[2][3].ndim # 2 </code></pre> <p>Therefore when you do <code>a[2][3] = (something)</code> you are using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting</a> instead of assigning an element: numpy tries to replace the content of the subarray <code>a[2][3]</code> and fails because of shape mismatch. The memory layout of numpy arrays does not allow to change the shape of subarrays.</p> <p><strong>Edit:</strong> Instead of using numpy arrays you could use nested lists. These nested lists can have arbitrary sizes. Note that the memory is higher and that the access time is higher compared to numpy array.</p> <pre><code>import numpy as np a = np.random.rand(5,5,3,2) a = np.array(a, dtype=object) b = np.append(a[2][3], [[1.0,1.0]],axis=0) a_list = a.tolist() a_list[2][3] = b.tolist() </code></pre>
1
2016-07-20T14:46:29Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
Append numpy array into an element
38,483,650
<p>I have a Numpy array of shape (5,5,3,2). I want to take the element (1,4) of that matrix, which is also a matrix of shape (3,2), and add an element to it -so it becomes a (4,2) array. The code I'm using is the following:</p> <pre><code>import numpy as np a = np.random.rand(5,5,3,2) a = np.array(a, dtype = object) #So I can have different size sub-matrices a[2][3] = np.append(a[2][3],[[1.0,1.0]],axis=0) #a[2][3] shape = (3,2) </code></pre> <p>I'm always obtaining the error: </p> <pre><code>ValueError: could not broadcast input array from shape (4,2) into shape (3,2) </code></pre> <p>I understand that the shape returned by the <code>np.append</code> function is not the same as the <code>a[2][3]</code> sub-array, but I thought that the <code>dtype=object</code> would solve my problem. However, I need to do this. Is there any way to go around this limitation? I also tried to use the <code>insert</code> function but I don't know how could I add the element in the place I want.</p>
1
2016-07-20T14:10:08Z
38,486,220
<p>Make sure you understand what you have produced. That requires checking the shape and dtype, and possibly looking at the values</p> <pre><code>In [29]: a = np.random.rand(5,5,3,2) In [30]: b=np.array(a, dtype=object) In [31]: a.shape Out[31]: (5, 5, 3, 2) # a is a 4d array In [32]: a.dtype Out[32]: dtype('float64') In [33]: b.shape Out[33]: (5, 5, 3, 2) # so is b In [34]: b.dtype Out[34]: dtype('O') In [35]: b[2,3].shape Out[35]: (3, 2) In [36]: c=np.append(b[2,3],[[1,1]],axis=0) In [37]: c.shape Out[37]: (4, 2) In [38]: c.dtype Out[38]: dtype('O') </code></pre> <p><code>b[2][3]</code> is also an array. <code>b[2,3]</code> is the proper numpy way of indexing 2 dimensions.</p> <p>I suspect you wanted <code>b</code> to be a <code>(5,5)</code> array containing arrays (as objects), and you think that you you can simply replace one of those with a <code>(4,2)</code> array. But the <code>b</code> constructor simply changes the <code>floats</code> of <code>a</code> to objects, without changing the shape (or 4d nature) of <code>b</code>.</p> <p>I could construct a (5,5) object array, and fill it with values from <code>a</code>. And then replace one of those values with a (4,2) array:</p> <pre><code>In [39]: B=np.empty((5,5),dtype=object) In [40]: for i in range(5): ...: for j in range(5): ...: B[i,j]=a[i,j,:,:] ...: In [41]: B.shape Out[41]: (5, 5) In [42]: B.dtype Out[42]: dtype('O') In [43]: B[2,3] Out[43]: array([[ 0.03827568, 0.63411023], [ 0.28938383, 0.7951006 ], [ 0.12217603, 0.304537 ]]) In [44]: B[2,3]=c In [46]: B[2,3].shape Out[46]: (4, 2) </code></pre> <p>This constructor for <code>B</code> is a bit crude. I've answered other questions about creating/filling object arrays, but I'm not going to take the time here to streamline this case. It's for illustration purposes only.</p>
1
2016-07-20T16:41:34Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
Making lists of the nth items of different lists in a dictionary
38,483,710
<p>I have embedded dictionaries within a list of lists such as this one :</p> <pre><code>X = \ [ [ {'the_geom': (999,999), 1: [111,112,113], 2: [121,122,123]}, {'the_geom': (998,998), 1: [211,212,213], 2:[221,222,223]} ], [ {'the_geom': (997,997), 1: [1111,1112,1113, 1114], 2: [1121,1122,1123, 1124]}, {'the_geom': (996,996), 1: [1211, 1212, 1213], 2: [2211,2212,2213]} ] ] </code></pre> <p>I'm looking for a function that would give me :</p> <pre><code>XX = \ [ [ {'the_geom': (999,999), 'values': [[111, 121], [112,122], [113, 123]]}, {'the_geom': (998,998), 'values': [[211,221], [212,222], [213,223]]} ], [ {'the_geom': (997,997), 'values': [[1111,1121],[1112,1122],[1113,1123],[1114,1124]]}, {'the_geom': (996,996), 'values': [[1211, 2211], [1212,2212],[1213,2213]]} ] ] </code></pre> <p>How do I do this?</p>
-1
2016-07-20T14:12:40Z
38,484,112
<p>You can do it this way:</p> <pre><code>new_x = [] for item in X: new_inner_item = [] for inner_item in item: new_inner_item.append({ 'the_geom': inner_item['the_geom'], 'values': [list(a) for a in zip(*[v for k,v in inner_item.items() if k != 'the_geom'])] }) new_x.append(new_inner_item) </code></pre>
1
2016-07-20T14:30:53Z
[ "python", "dictionary", "list-comprehension" ]
Making lists of the nth items of different lists in a dictionary
38,483,710
<p>I have embedded dictionaries within a list of lists such as this one :</p> <pre><code>X = \ [ [ {'the_geom': (999,999), 1: [111,112,113], 2: [121,122,123]}, {'the_geom': (998,998), 1: [211,212,213], 2:[221,222,223]} ], [ {'the_geom': (997,997), 1: [1111,1112,1113, 1114], 2: [1121,1122,1123, 1124]}, {'the_geom': (996,996), 1: [1211, 1212, 1213], 2: [2211,2212,2213]} ] ] </code></pre> <p>I'm looking for a function that would give me :</p> <pre><code>XX = \ [ [ {'the_geom': (999,999), 'values': [[111, 121], [112,122], [113, 123]]}, {'the_geom': (998,998), 'values': [[211,221], [212,222], [213,223]]} ], [ {'the_geom': (997,997), 'values': [[1111,1121],[1112,1122],[1113,1123],[1114,1124]]}, {'the_geom': (996,996), 'values': [[1211, 2211], [1212,2212],[1213,2213]]} ] ] </code></pre> <p>How do I do this?</p>
-1
2016-07-20T14:12:40Z
38,484,122
<p>It can be written in one line, but it is easier to understand when the formatting is parallel to the original question. It handles the case where there are multiple keys in the inner dict (eg. keys other than 1 and 2).</p> <pre><code>XX = \ [ [ { 'the_geom': col['the_geom'], 'values': list(zip(*[col[key] for key in col.keys() if key != 'the_geom'])) } for col in row] for row in X] </code></pre>
0
2016-07-20T14:31:07Z
[ "python", "dictionary", "list-comprehension" ]
Making lists of the nth items of different lists in a dictionary
38,483,710
<p>I have embedded dictionaries within a list of lists such as this one :</p> <pre><code>X = \ [ [ {'the_geom': (999,999), 1: [111,112,113], 2: [121,122,123]}, {'the_geom': (998,998), 1: [211,212,213], 2:[221,222,223]} ], [ {'the_geom': (997,997), 1: [1111,1112,1113, 1114], 2: [1121,1122,1123, 1124]}, {'the_geom': (996,996), 1: [1211, 1212, 1213], 2: [2211,2212,2213]} ] ] </code></pre> <p>I'm looking for a function that would give me :</p> <pre><code>XX = \ [ [ {'the_geom': (999,999), 'values': [[111, 121], [112,122], [113, 123]]}, {'the_geom': (998,998), 'values': [[211,221], [212,222], [213,223]]} ], [ {'the_geom': (997,997), 'values': [[1111,1121],[1112,1122],[1113,1123],[1114,1124]]}, {'the_geom': (996,996), 'values': [[1211, 2211], [1212,2212],[1213,2213]]} ] ] </code></pre> <p>How do I do this?</p>
-1
2016-07-20T14:12:40Z
38,484,355
<p>You can use zip together with list comprehension:</p> <pre><code>[ [ { 'the_geom':dict['the_geom'], 'values':zip(*[dict[i+1] for i in range(len(dict)-1)]) } for dict in list ] for list in X ] </code></pre>
0
2016-07-20T14:40:42Z
[ "python", "dictionary", "list-comprehension" ]
Making lists of the nth items of different lists in a dictionary
38,483,710
<p>I have embedded dictionaries within a list of lists such as this one :</p> <pre><code>X = \ [ [ {'the_geom': (999,999), 1: [111,112,113], 2: [121,122,123]}, {'the_geom': (998,998), 1: [211,212,213], 2:[221,222,223]} ], [ {'the_geom': (997,997), 1: [1111,1112,1113, 1114], 2: [1121,1122,1123, 1124]}, {'the_geom': (996,996), 1: [1211, 1212, 1213], 2: [2211,2212,2213]} ] ] </code></pre> <p>I'm looking for a function that would give me :</p> <pre><code>XX = \ [ [ {'the_geom': (999,999), 'values': [[111, 121], [112,122], [113, 123]]}, {'the_geom': (998,998), 'values': [[211,221], [212,222], [213,223]]} ], [ {'the_geom': (997,997), 'values': [[1111,1121],[1112,1122],[1113,1123],[1114,1124]]}, {'the_geom': (996,996), 'values': [[1211, 2211], [1212,2212],[1213,2213]]} ] ] </code></pre> <p>How do I do this?</p>
-1
2016-07-20T14:12:40Z
38,484,421
<p>Ugly variable names but it works:</p> <pre><code>XX=[] for x in X: xx=[] for i in x: ii={} ii['the_geom']=i['the_geom'] ii['values']=[] for indx in range(0,len(i[1])): pair=[] for j in range(1,len(i)): pair.append(i[j][indx]) ii['values'].append(pair) xx.append(ii) XX.append(xx) </code></pre>
0
2016-07-20T14:43:56Z
[ "python", "dictionary", "list-comprehension" ]
Making lists of the nth items of different lists in a dictionary
38,483,710
<p>I have embedded dictionaries within a list of lists such as this one :</p> <pre><code>X = \ [ [ {'the_geom': (999,999), 1: [111,112,113], 2: [121,122,123]}, {'the_geom': (998,998), 1: [211,212,213], 2:[221,222,223]} ], [ {'the_geom': (997,997), 1: [1111,1112,1113, 1114], 2: [1121,1122,1123, 1124]}, {'the_geom': (996,996), 1: [1211, 1212, 1213], 2: [2211,2212,2213]} ] ] </code></pre> <p>I'm looking for a function that would give me :</p> <pre><code>XX = \ [ [ {'the_geom': (999,999), 'values': [[111, 121], [112,122], [113, 123]]}, {'the_geom': (998,998), 'values': [[211,221], [212,222], [213,223]]} ], [ {'the_geom': (997,997), 'values': [[1111,1121],[1112,1122],[1113,1123],[1114,1124]]}, {'the_geom': (996,996), 'values': [[1211, 2211], [1212,2212],[1213,2213]]} ] ] </code></pre> <p>How do I do this?</p>
-1
2016-07-20T14:12:40Z
38,484,532
<pre><code>res1= [[{'the_geom':y['the_geom'],'values':[[y[1][i],y[2][i]] for i in range(3)]} for y in z] for z in X] </code></pre> <p>Output :</p> <pre><code>[[{'values': [[111, 121], [112, 122], [113, 123]], 'the_geom': (999, 999)}, {'values': [[211, 221], [212, 222], [213, 223]], 'the_geom': (998, 998)}], [{'values': [[1111, 1121], [1112, 1122], [1113, 1123]], 'the_geom': (997, 997)}, {'values': [[1211, 2211], [1212, 2212], [1213, 2213]], 'the_geom': (996, 996)}]] </code></pre>
0
2016-07-20T15:20:09Z
[ "python", "dictionary", "list-comprehension" ]
Python commandline parameter not raising error if argument is wrongly used
38,483,792
<p>I have the following Python code that has 1 command line optional parameter (<code>c</code>) that has an argument and 2 options (<code>a</code> and <code>b</code>) that do not have an argument:</p> <pre><code>import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"abc:",["csvfile="]) except getopt.GetoptError: print 'Error in usage - a does not require an argument' sys.exit(2) for opt, arg in opts: print "Raw input is: {}" .format(opt) if opt in ("-c", "--csvfile"): outputfile = arg print 'Output file is {}' .format(outputfile) elif opt == '-a': print 'Alpha' elif opt == '-b': print 'Beta' print 'User choice is {}' .format(opt.lstrip('-')) if __name__ == "__main__": main(sys.argv[1:]) </code></pre> <p>When I enter <code>python readwritestore.py -a</code> I get:</p> <pre><code>Raw input is: -a Alpha User choice is a </code></pre> <p>This is what I was hoping for if the commandline argument is <code>-a</code>. However, if I enter <code>python readwritestore.py -a csvfile_name</code>, then I get:</p> <pre><code>Raw input is: -a Alpha User choice is a </code></pre> <p>This is not what I intended for. In this function, <code>c</code> is the only option that rquires an argument. If I enter <code>a</code> with an argument, the code should give the error message that I set up</p> <pre><code>Error in usage - a does not require an argument </code></pre> <p>This does not happen for <code>a</code> or <code>b</code>. It is allowing the argument to be entered without raising an error.</p> <p>If the options that do not require an argument are entered with an argument, then I would like it to raise an error. <code>python readwritestore.py -a text</code> and <code>python readwritestore.py -b text</code> should raise the error <code>Error in usage - a does not require an argument</code>.</p> <p>Is there a way to specify this? Is <code>getopt()</code> the correct way to do this?</p> <p><strong>Additional Information:</strong></p> <p>I only want <code>python readwritestore.py -c text</code> to work with the argument. For the other 2 options, <code>a</code> and <code>b</code>, the code should raise the error.</p>
0
2016-07-20T14:17:04Z
38,484,082
<p>checking the size of sys.argv (the list of argument supplied when calling the script) can help you checking that : </p> <pre><code>import sys import getopt def main(argv): inputfile = '' outputfile = '' opts, args = getopt.getopt(argv, "abc:", ["csvfile="]) for opt, arg in opts: print "Raw input is:", opt if opt in ("-c", "--csvfile"): outputfile = arg print 'Output file is ', outputfile elif opt == '-a': if len(sys.argv)=2: print 'Alpha' else: print "incorect number of argument" elif opt == '-b': if len(sys.argv)=2: print 'Beta' else: print "incorect number of argument" print 'User choice is ', opt if __name__ == "__main__": main(sys.argv[1:]) </code></pre> <p>I know it's not what you asked (argparse) but here is how you could do it with argparse :</p> <pre><code>from argparse import * def main(): parser = ArgumentParser() parser.add_argument('-c', '--csvfile', help='do smth with cvsfile') parser.add_argument( '-a', '--Alpha', help='Alpha', action='store_true') parser.add_argument( '-b', '--Beta', help='beta smth', action='store_true') if args.csvfile: print 'Output file is {}' .format(args.csvfile) if args.Alpha: print 'Alpha' if args.Beta: print 'Beta' if __name__ == "__main__": main() </code></pre> <p>It will raise an error is to many argument are supplied. (also <code>python readwritestore.py -h</code> will display the help just like man in unix)</p>
1
2016-07-20T14:29:34Z
[ "python", "command-line", "arguments", "optional-parameters" ]
How to use datetime instance as a timestamp in postgresql?
38,483,817
<p>I want to create postgresql function (<code>CREATE FUNCTION</code>) with PL/Python.</p> <p>How do I convert from python <code>datetime</code> object to postgresql <code>timestamp</code> object in procedure?</p>
1
2016-07-20T14:18:01Z
38,486,628
<p>Tell the <code>prepare</code> method the type of the parameter value, a <code>timestamp</code>, then pass a <code>datetime</code> value to the <code>execute</code> method: </p> <pre><code>create or replace function pytest() returns timestamp as $$ from datetime import datetime plan = plpy.prepare('select $1 as my_datetime', ['timestamp']) rv = plpy.execute(plan, (datetime.now(),)) return rv[0]['my_datetime'] $$ language plpythonu; select pytest(); pytest ---------------------------- 2016-07-20 13:57:59.625991 </code></pre> <p><a href="https://www.postgresql.org/docs/current/static/plpython-database.html" rel="nofollow">Database Access from PL/Python</a></p>
0
2016-07-20T17:03:57Z
[ "python", "postgresql" ]
fatal: bad revision 'HEAD-1 on revert
38,483,908
<p>I want to revert my last commit on a public branch with the commit being pushed up. I wanted to use revert to show what I did wrong and I reverted it, but following <a href="https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations" rel="nofollow">https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations</a> git isn't taking the usual channels:</p> <pre><code> cchilders:~/work_projects/webapi (ckc/my-branch) $ git revert HEAD-1 fatal: bad revision 'HEAD-1' </code></pre> <p>Any help appreciated, thank you</p>
0
2016-07-20T14:22:10Z
38,485,375
<p>To consolidate the answer to this question: The reason why you've received an error is due to syntax error.</p> <p>The correct instruction would be</p> <pre><code>git revert HEAD~1 </code></pre> <p>instead</p> <pre><code>git revert HEAD-1 </code></pre>
1
2016-07-20T15:59:00Z
[ "python", "git" ]
Basic auth with Django not working
38,483,937
<p>I'm having trouble using basic auth with django, here's my config:</p> <pre><code>MIDDLEWARE_CLASSES = [ 'request_id.middleware.RequestIdMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', # &lt;&lt;&lt;&lt;&lt;=== 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.RemoteUserBackend', 'django.contrib.auth.backends.ModelBackend', ] </code></pre> <p>and my view:</p> <pre><code>def api_list_things(request, intake_id=None): if not request.user.is_authenticated(): return JsonResponse({'message': 'Not authenticated'}, status=403) return JsonResponse({'message': 'ok'}) </code></pre> <p>But when I do <code>curl -v http://user:pass@localhost:8000/api/list_things/</code> I get the unauthenticated error:</p> <pre><code>* Hostname was NOT found in DNS cache * Trying ::1... * connect to ::1 port 8000 failed: Connection refused * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8000 (#0) * Server auth using Basic with user 'd' &gt; GET /trs/api/intakes/ HTTP/1.1 &gt; Authorization: Basic dXNlcjpwYXNz &gt; User-Agent: curl/7.38.0 &gt; Host: localhost:8000 &gt; Accept: */* &gt; * HTTP 1.0, assume close after body &lt; HTTP/1.0 403 Forbidden &lt; Vary: Cookie &lt; X-Frame-Options: SAMEORIGIN &lt; Content-Type: application/json &lt; Connection: close &lt; Server: Werkzeug/0.11.10 Python/3.4.2 &lt; Date: Wed, 20 Jul 2016 14:16:32 GMT &lt; * Closing connection 0 {"message": "Not authenticated"}% </code></pre> <p>I don't see where I'm wrong, maybe somebody can help me ?</p>
0
2016-07-20T14:23:25Z
38,485,536
<p>Django <strong>does not</strong> support Basic HTTP auth by itself, what <code>django.contrib.auth.backends.RemoteUserBackend</code> actually does is described in the docs.</p> <blockquote> <p>With this setup, RemoteUserMiddleware will detect the username in request.META['REMOTE_USER'] and will authenticate and auto-login that user using the RemoteUserBackend.</p> </blockquote> <p>The <code>REMOTE_USER</code> env variable should be set by a web server sitting in front of Django (for eg. apache).</p> <p>If you just want to support the Authorization header, this custom authentication backend might help: <a href="https://www.djangosnippets.org/snippets/243/" rel="nofollow">https://www.djangosnippets.org/snippets/243/</a> (from <a href="http://stackoverflow.com/a/1087736/1268926">here</a>)</p>
2
2016-07-20T16:05:42Z
[ "python", "django", "basic-authentication", "http-basic-authentication" ]
ubuntu python cron job stops without error
38,483,943
<p>I have an amazon instance that is running my site. I recently tried to set up a cron job and it just stops without throwing any error or anything halfway through the task.</p> <p><code>crontab -l</code> shows</p> <pre><code>30 13 * * 1,2,3,4,5,6 /home/ubuntu/.virtualenvs/testprep/bin/python /home/ubuntu/web/testprep/manage.py daily &gt; /tmp/prepcron.log </code></pre> <p>Here is my python/django script:</p> <pre><code>class Command(BaseCommand): def handle(self, *args, **options): print("starting") date = datetime.now().date() print("date is", date) try: users = User.objects.filter(test="ACT", state__in=[User.WAITING, User.READY, User.SOLUTION]) except Exception as e: print(str(e)) print("number of users", users.count()) ... </code></pre> <p>And at 13:30 I get this in my logfile:</p> <pre><code>starting date is 2016-07-19 </code></pre> <p>And that's it! No error is thrown or caught. <code>Number of users</code> is never printed. The program just gives up halfway through. If I run that command by hand (literal copy and paste) then the script executes as expected, this only happens when I try to schedule it.</p> <p>Has anyone ever seen anything like this?</p>
0
2016-07-20T14:23:41Z
38,616,992
<p>Okay, the issue was actually in my django <code>settings.py</code> file. The database was just an <code>sqlite</code> database with a relative path. Apparently when running the code from a cron job, it needs an absolute path. So changing the code to this fixed the issue:</p> <pre><code>import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'database'), } } </code></pre>
0
2016-07-27T15:13:09Z
[ "python", "django", "cron" ]
Title using matplotlib and pandas - python
38,483,963
<p>Any idea why my script below places the title so far from the graphs/subplots? Is it possible to specify the font size of the title?</p> <pre><code>df = pandas.read_csv('data.csv', delimiter=',', index_col=0, parse_dates=[0], dayfirst=True, names=['Date','1','2','3','4', '5']) df.plot(subplots=True, marker='.',markersize=8, title ="Graph", fontsize = 10, color=['r','b','b','b', 'b'], figsize=(8, 18)) plt.savefig('capture.png') </code></pre> <p>Thanks a ton!</p>
-1
2016-07-20T14:24:26Z
38,484,158
<p>You'll have to use <code>matplotlib</code> to edit the font size, as pandas does not allow passing for font sizes or similar, unfortunately (afaik).</p> <p>try this:</p> <pre><code>ax = df.plot() ax.set_title('Graph', fontsize=20) # or size, alternatively </code></pre> <p>Essentially, <code>pandas.DataFrame.plot()</code> returns a matplotlib <code>axis</code> object, on which you then can call any methods associated with it.</p> <p>For more, check out <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">the matplotlib documentation</a>.</p>
1
2016-07-20T14:32:07Z
[ "python", "pandas", "matplotlib" ]
How to make a terminal console (terminal emulator) in PyQt5?
38,484,032
<p>I am building an application in Python, with a graphical user interface in PyQt5. I need to insert some sort of "Terminal Console" in the application. The user can start a batch file by clicking a button, and should see the output appear in a text field.</p> <p>At this moment, I use the following approach. When the user presses a button, the program will start the batch script (say "myBat.bat"). The standard output gets extracted and written to a QTextEdit widget.</p> <p><a href="http://i.stack.imgur.com/1oiAA.png" rel="nofollow"><img src="http://i.stack.imgur.com/1oiAA.png" alt="enter image description here"></a></p> <p>This works great, but there are two serious problems.</p> <hr> <p><strong>(PROBLEM 1) The output is shown at the end of the batch execution..</strong></p> <p>And that's sometimes really painful. Especially if the bat-file takes some time to execute, the user will get the impression that everything freezes.</p> <p><strong>(PROBLEM 2) The user cannot give commands..</strong></p> <p>Some bat-files require user input. I have no idea on how to do this.</p> <p><strong>(PROBLEM 3) When the batch file is finished, it's over..</strong></p> <p>Sometimes the user wants to keep giving commands to the terminal, even when the batch file has finished. For example a simple <code>dir</code> command, to list out the files in a directory. Anything should be possible.</p> <p>To summarise everything, I just need to make a functional terminal console inside my application.</p> <p>There is a guy who ported QTermWidget to PyQt4. This is the link: <a href="https://sourceforge.net/projects/qtermwidget/?source=typ_redirect" rel="nofollow">https://sourceforge.net/projects/qtermwidget/?source=typ_redirect</a> . Unfortunately his code is not compiled for Windows (I'm working on a Windows 10 machine). And his port is made for PyQt4. My entire application is written in PyQt5. There are reasons why I cannot go back to PyQt4.</p> <p>Another guy made this software: <a href="https://bitbucket.org/henning/pyqtermwidget/overview" rel="nofollow">https://bitbucket.org/henning/pyqtermwidget/overview</a> . Also very interesting, but no Windows support.</p> <hr> <p>Please help..</p> <p><strong>EDIT :</strong></p> <p>This is the code I'm currently running:</p> <pre><code> ############################################### ### This function gets called when the user ### ### pushes the button ### ############################################### def myBatFunction(self): # 1. Call the proper batch file p = Popen("C:\\..\\myFolder\\myBat.bat" , cwd=r"C:\\..\\myFolder", stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdout, stderr = p.communicate() p.wait() if p.returncode == 0: pass else: return # 2. Capture the standard out stream from the batch file msg = stdout.decode("utf-8") errMsg = stderr.decode("utf-8") self.myTextArea.setText(msg + errMsg) ############################################### </code></pre> <p><strong>EDIT :</strong> If you think this is a duplicate question, please verify first if the other question offers a solution to Windows 10 users, and works with PyQt5 :-)</p>
2
2016-07-20T14:27:44Z
38,540,008
<p>In your code <code>p.wait()</code> is the point of synchronization with the opened process. After that line the external process is finished. So you need to read <code>p.stout</code> in a loop <strong>before</strong> that line. Check the following example:</p> <pre><code>#!/usr/bin/env python2 from subprocess import Popen, PIPE p = Popen(["C:\\..\\myFolder\\myBat.bat"], stdout=PIPE, bufsize=1) with p.stdout: for line in iter(p.stdout.readline, b''): print line, p.wait() # wait for the subprocess to exit </code></pre> <p>Note that <code>bufsize</code> should be <code>1</code> to suppress buffering.</p>
1
2016-07-23T08:58:47Z
[ "python", "python-3.x", "batch-file", "pyqt5", "terminal-emulator" ]
get data from octave script execution using oct2py (python3)
38,484,116
<p>I'm trying to execute some <code>Matlab</code> scripts (not a function definition) from <code>Python 3</code> using <code>oct2py</code> module. </p> <p>Those scripts (a large amount) contains a very extended definition to read a specific ASCIII files (contained in the same directory). </p> <p>I do not know how to get the data read by Python with the Matlab (octave) scripts.</p> <p>Here what I am doing:</p> <pre><code>from oct2py import octave import numpy as np import os import pprint hom_dir='/path_to/files&amp;scripts_dir/' os.chdir(hom_dir) octave.addpath(/path_to/files&amp;scripts_dir/') out=octave. matlab_file # (matlab_file.m) </code></pre> <p>output:</p> <pre><code>Out[237]: &lt;function oct2py.core.Oct2Py._make_octave_command.&lt;locals&gt;.octave_command&gt;” pprint.pprint(out) &lt;function Oct2Py._make_octave_command.&lt;locals&gt;.octave_command at 0x7f2069d669d8&gt;” </code></pre> <p>No error is returned, but I do not know how to get the data (that were read in a Octave session). The examples that I have found for execute .m files using <code>oct2py</code> where about files that define functions, however that is not my case.</p>
1
2016-07-20T14:30:58Z
38,543,580
<p>Assuming your script places the results on the (virtual) octave workspace, you can simply attempt to access the workspace.</p> <p>Example:</p> <pre><code>%% In file myscript.m a = 1 b = 2 </code></pre> <p>Python code:</p> <pre><code>&gt;&gt;&gt; octave.run('myscript.m') &gt;&gt;&gt; vars = octave.who(); vars [u'A__', u'a', u'b'] &gt;&gt;&gt; octave.a() 1.0 &gt;&gt;&gt; octave.b() 2.0 </code></pre> <p>Some notes / caveats:</p> <ul> <li>I ran into problems when I tried running a script, as it complained I was trying to run it as a function; you can bypass this using the <code>run</code> command. </li> <li><p>Your octave current directory may not be the same as your python current directory (this depends on how the octave engine is started). For me python started in my home directory but octave started in my desktop directory. I had to manually check and go to the correct directory, i.e.:</p> <pre><code>octave.pwd() octave.cd('/path/to/my/homedir') </code></pre></li> <li><p>Those weird looking variables <code>A__</code> (<code>B__</code>, etc) in the workspace reflect the most recent arguments you passed into functions via the oct2py engine (but for some reason they can't be called like normal variables). E.g.</p> <pre><code>&gt;&gt;&gt; octave.plus(1,2) 3.0 &gt;&gt;&gt; print octave.who() [u'A__', u'B__', u'a', u'b'] &gt;&gt;&gt; octave.eval('A__') A__ = 1 &gt;&gt;&gt; octave.eval('B__') B__ = 2 </code></pre></li> <li><p>As you may have noticed from above, the usual <code>ans</code> variable is not kept in the workspace. Do not rely on any script actions that reference <code>ans</code>. In the context of <code>oct2py</code> it seems that <code>ans</code> will always evaluate to <code>None</code></p></li> </ul>
0
2016-07-23T15:48:23Z
[ "python", "matlab", "octave" ]
Doc2Vec model Python 3 compatibility
38,484,117
<p>I trained a doc2vec model with Python2 and I would like to use it in Python3.</p> <p>When I try to load it in Python 3, I get : </p> <pre><code>Doc2Vec.load('my_doc2vec.pkl') UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 0: ordinal not in range(128) </code></pre> <p>It seems to be related to a pickle compatibility issue, which I tried to solve by doing :</p> <pre><code>with open('my_doc2vec.pkl', 'rb') as inf: data = pickle.load(inf) data.save('my_doc2vec_python3.pkl') </code></pre> <p>Gensim saved other files which I renamed as well so they can be found when calling</p> <pre><code>de = Doc2Vec.load('my_doc2vec_python3.pkl') </code></pre> <p>The load() does not fail with UnicodeDecodeError but after the inference provides meaningless results.</p> <p>I can't easily re-train it using Gensim in Python 3 as I used this model to create derived data from it, so I would have to re-run a long and complex pipeline.</p> <p>How can I make the doc2vec model compatible with Python 3?</p>
2
2016-07-20T14:31:00Z
38,486,065
<p>Answering my own question, this <a href="http://stackoverflow.com/questions/33596082/load-gensim-word2vec-computed-in-python-2-in-python-3?rq=1">answer</a> worked for me.</p> <p>Here are the steps a bit more details :</p> <ol> <li>download gensim source code, e.g clone from repo</li> <li><p>in gensim/utils.py, edit the method unpickle to add the encoding parameter:</p> <pre><code> return _pickle.loads(f.read(), encoding='latin1') </code></pre></li> <li><p>using Python 3 and the modified gensim, load the model:</p> <pre><code>de = Doc2Vec.load('my_doc2vec.pkl') </code></pre></li> <li><p>save it:</p> <pre><code>de.save('my_doc2vec_python3.pkl') </code></pre></li> </ol> <p>This model should be now loadable in Python 3 with unmodified gensim.</p>
1
2016-07-20T16:33:27Z
[ "python", "python-3.x", "pickle", "gensim", "doc2vec" ]
System of equations in sympy with symbolic output
38,484,174
<p>Is it possible to solve a system of equations(linear or non linear) with sympy where the output is symbolic?</p> <p>Example:</p> <pre><code> 1. f_m = a0 + a1*(-dx) + a2*(-dx)^2 2. f_c = a0 3. f_p = a0 + a1*(dx) + a2*(dx)^2 </code></pre> <p>Solve for a2. </p> <p>By the Mathematica command </p> <p>Solve the solution is</p> <pre><code>a2 = (1/2)*(f_m - 2*f_c + f_p). </code></pre>
1
2016-07-20T14:32:47Z
38,484,721
<p>This is a fundamental operation in Sympy, you should study the documention. Just to get you started:</p> <pre><code>import sympy as sp f_m, f_c, f_p = sp.var('f_m, f_c, f_p') a0, a1, a2 = sp.var('a0:3') dx = sp.var('dx') eq1 = sp.Eq(f_m, a0 + a1*(-dx) + a2*(-dx)**2) eq2 = sp.Eq(f_c, a0) eq3 = sp.Eq(f_p, a0 + a1*(dx) + a2*(dx)**2 ) sp.linsolve([eq1, eq2, eq3], (a0, a1, a2)) # sp.solve([eq1, eq2, eq3], (a0, a1, a2)) # also works </code></pre> <blockquote> <p><code>{(f_c, (-f_m + f_p)/(2*dx), (-2*f_c + f_m + f_p)/(2*dx**2))}</code></p> </blockquote>
2
2016-07-20T15:29:38Z
[ "python", "wolfram-mathematica", "sympy", "symbolic-math" ]
Cannot connect to ssh via python
38,484,179
<p>so I just setted up a fresh new raspberry pi and I want it to communicate with python using ssh from my computer to my ssh server, the pi.. I first try to connect using putty and it work, I could execute all the commands I wanted, then I tried using librarys such as Paramiko, Spur and they didn't work.</p> <p>Spur code:</p> <pre><code>import spur shell = spur.SshShell("192.168.1.114", "pi", "raspberry") result = shell.run("ls") print result </code></pre> <p>Paramiko code:</p> <pre><code>ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username, password) </code></pre> <p>Here's the error code:</p> <pre><code>spur.ssh.ConnectionError: Error creating SSH connection Original error: Server '192.168.1.114' not found in known_hosts </code></pre> <p>This is the error with spur but it pretty much said the same thing with paramiko.</p> <p>Thanks in advance :)</p>
0
2016-07-20T14:33:10Z
38,484,228
<p>You need to accept the host key, similarly to what is shown <a href="https://iliaselmatani.wordpress.com/2014/04/16/spur/" rel="nofollow">here</a></p> <pre><code>import spur shell = spur.SshShell("192.168.1.114", "pi", "raspberry", missing_host_key=spur.ssh.MissingHostKey.accept) result = shell.run("ls") print result </code></pre> <p>EDIT: More useful link (<a href="https://pypi.python.org/pypi/spur" rel="nofollow"><code>spur documentation</code></a>)</p>
0
2016-07-20T14:35:25Z
[ "python", "ssh" ]
django-mptt raises 'NoneType' object has no attribute 'tree_id' when saving node
38,484,192
<p><img src="https://cloud.githubusercontent.com/assets/5443029/16989577/6ffb8ac2-4e9d-11e6-9b1f-749177230c84.png" alt="screen shot 2016-07-20 at 17 06 39"></p> <p>Environment: python 2.7.10, Django 1.9.1, django-mptt 0.8.4</p> <pre><code># models.py class Foo(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True) </code></pre> <p>Error raises in:</p> <pre><code>getattr(self, opts.tree_id_attr) != getattr(parent, opts.tree_id_attr) </code></pre> <p>where parent is <code>None</code> because of:</p> <p>1) <a href="https://github.com/django-mptt/django-mptt/blob/0.8.x/mptt/models.py#L892" rel="nofollow">link</a></p> <pre><code>opts.set_raw_field_value(self, opts.parent_attr, old_parent_id) # old_parent_id is None </code></pre> <p>2) <a href="https://github.com/django-mptt/django-mptt/blob/0.8.x/mptt/models.py#L900" rel="nofollow">link</a></p> <pre><code>parent = getattr(self, opts.parent_attr) </code></pre> <p><a href="https://github.com/django-mptt/django-mptt/blob/0.8.x/mptt/models.py#L109" rel="nofollow">set_raw_field_value source:</a></p> <pre><code>def set_raw_field_value(self, instance, field_name, value): field = instance._meta.get_field(field_name) setattr(instance, field.attname, value) </code></pre> <p>Help me to understand this behavior. Why it's not enough to set relation by <code>self.parent_id</code>?</p>
0
2016-07-20T14:33:39Z
38,495,831
<blockquote> <p>It seems that setting parent_id does not reset parent in any way, resp. parent isn't dynamically loaded from the database just because the underlying id field has some value.</p> </blockquote> <p><a href="https://github.com/django-mptt/django-mptt/issues/428" rel="nofollow">https://github.com/django-mptt/django-mptt/issues/428</a></p>
0
2016-07-21T05:48:53Z
[ "python", "django", "django-mptt" ]
Slicing a dataframe based on range of time
38,484,207
<p>I am new to Pandas. I have a set of Excel data read into a dataframe as follows:</p> <pre><code>TimeReceived A B 08:00:01.010 70 40 08:00:01.050 80 50 08:01:01.100 50 20 08:01:01.150 40 30 </code></pre> <p>I want to compute the average for columns A &amp; B based on time intervals of 100 ms. The output in this case would be :</p> <pre><code>TimeReceived A B 08:00:01.000 75 45 08:00:01.100 45 25 </code></pre> <p>I have set the 'TimeReceived' as a Date-Time index:</p> <pre><code>df = df.set_index (['TimeReceived']) </code></pre> <p>I can select rows based on predefined time ranges but I cannot do computations on time intervals as shown above.</p>
0
2016-07-20T14:34:14Z
38,498,512
<p>If you have a<code>DatetimeIndex</code> you can then use <code>resample</code> to up or down sample your data to a new frequency. This will introduce <code>NaN</code> rows where there are gaps but you can drop these using <code>dropna</code>:</p> <pre><code>df.resample('100ms').mean().dropna() </code></pre>
0
2016-07-21T08:08:53Z
[ "python", "pandas", "dataframe" ]
How to stop Twisted callback?
38,484,221
<p>I wrote a callback function using twisted Now my question is when websocket connection dropped I need to stop this callback. </p> <pre><code>def sendBack(self, payload): # find correct way to identify connection dropped now using wasnotcl... if self.wasNotCleanReason: # stop this callback self.sendMessage("Message") reactor.callLater(delay, self.sendBack, payload=payload) </code></pre>
0
2016-07-20T14:35:08Z
38,486,185
<p>You can <code>cancel</code> it...</p> <pre><code>callID = reactor.callLater(delay, self.sendBack, payload=payload) if self.wasNotCleanReason: callID.cancel() </code></pre> <p><code><a href="http://twistedmatrix.com/documents/10.1.0/core/howto/time.html" rel="nofollow">ref</a></code></p>
1
2016-07-20T16:40:05Z
[ "python", "twisted", "autobahn", "twisted.web", "twisted.internet" ]
How to Google in Python Using urllib or requests
38,484,268
<p>What is the proper way to Google something in Python 3? I have tried <code>requests</code> and <code>urllib</code> for a Google page. When I simply <code>res = requests.get("https://www.google.com/#q=" + query)</code> that doesn't come back with the same HTML as when I inspect the Google page in Safari. The same happens with <code>urllib</code>. A similar thing happens when I use Bing. I am familiar with <code>AJAX</code>. However, it seems that that is now depreciated. </p>
1
2016-07-20T14:37:18Z
38,484,545
<p>In python, if you do not specify the user agent header in http requests manually, python will add for you by default which can be detected by Google and may be forbidden by it.</p> <p>Try the following if it can help.</p> <pre><code>import urllib yourUrl = "post it here" headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(yourUrl, headers = headers) page = urllib.request.urlopen(req) </code></pre>
0
2016-07-20T15:20:56Z
[ "python", "python-3.x", "request", "urllib", "google-search" ]
Error AttributeError: 'NoneType' object has no attribute 'title' -> due to an empty class
38,484,275
<p>I am looping through an xpath getting all the bold text that has the class black.</p> <p>this then gets the title within the bold class. This works fine until I have come across one the is blank inside.</p> <p>Using the below code how can i edit it to remove/skip the class's that contain no data?</p> <pre><code>out = [b.text.title() + "##" + b.xpath("./following::text()[1]")[0].lstrip(",") for b in div.xpath(".//b[@class='black']")] </code></pre> <p>The error I get is:</p> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'title'</p> </blockquote> <p>due to this line:</p> <p><code>&lt;b class="black"&gt;&lt;/b&gt;</code></p> <p>if it helps the div.xpath is:</p> <pre><code>div = tree.xpath("//*[@id='ANALYSIS']")[0] </code></pre>
0
2016-07-20T14:37:28Z
38,484,321
<p>Just add a filter to your list comprehension:</p> <pre><code>out = [b.text.title() + "##" + b.xpath("./following::text()[1]")[0].lstrip(",") for b in div.xpath(".//b[@class='black']") if b.text] </code></pre> <p>The <code>if b.text</code> ensures there is a truthy (non-empty or not <code>None</code>) <code>b.text</code> attribute value.</p>
0
2016-07-20T14:39:27Z
[ "python", "xpath" ]
Pandas DatetimeIndex converting dates to 1970
38,484,277
<p>I have recently faced a similar problem (<a href="http://stackoverflow.com/questions/38201666/pandas-datetimeindex-from-mongodb-isodate">answered here</a>) whereby conversion of a date to a pandas <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#datetimeindex" rel="nofollow">DatetimeIndex</a> and subsequent <code>groupby</code> using those dates led to an error where the date appeared as <code>1970-01-01 00:00:00+00:00</code>. </p> <p>I'm facing this problem in a different context now, and the previous solution isn't helping me. </p> <p>I have a frame like this</p> <pre><code>import pandas as pd from dateutil import tz data = { 'Events' : range(1, 5 + 1 ,1), 'ID' : [1, 1, 1, 1, 1]} idx = pd.date_range(start='2008-01-01', end='2008-01-05', freq='D', tz=tz.tzlocal()) frame = pd.DataFrame(data, index=idx) Events ID 2008-01-01 00:00:00+00:00 1 1 2008-01-02 00:00:00+00:00 2 1 2008-01-03 00:00:00+00:00 3 1 2008-01-04 00:00:00+00:00 4 1 2008-01-05 00:00:00+00:00 5 1 </code></pre> <p>and I want to change the index from just the date, to a <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow">MultiIndex</a> of <code>[date, ID]</code>, but in doing so that "1970 bug" appears </p> <pre><code>frame.set_index([frame.ID, frame.index]) Events ID ID 1 2008-01-01 00:00:00+00:00 1 1 1970-01-01 00:00:00+00:00 2 1 1970-01-01 00:00:00+00:00 3 1 1970-01-01 00:00:00+00:00 4 1 1970-01-01 00:00:00+00:00 5 1 </code></pre> <p><strong>Versions</strong></p> <ul> <li>Python 2.7.11</li> <li>Pandas 0.18.0</li> </ul>
2
2016-07-20T14:37:35Z
38,486,494
<p>The accepted answer of your other question works for me (Python 3.5.2, Pandas 0.18.1):</p> <pre><code>print(frame.set_index([frame.ID, frame.index])) # Events ID # ID # 1 2008-01-01 00:00:00-05:00 1 1 # 1970-01-01 00:00:00-05:00 2 1 # 1970-01-01 00:00:00-05:00 3 1 # 1970-01-01 00:00:00-05:00 4 1 # 1970-01-01 00:00:00-05:00 5 1 frame.index = frame.index.tz_convert(tz='EST') print(frame.set_index([frame.ID, frame.index])) # Events ID # ID # 1 2008-01-01 00:00:00-05:00 1 1 # 2008-01-02 00:00:00-05:00 2 1 # 2008-01-03 00:00:00-05:00 3 1 # 2008-01-04 00:00:00-05:00 4 1 # 2008-01-05 00:00:00-05:00 5 1 </code></pre> <p>(My local time is different from yours.)</p>
1
2016-07-20T16:56:35Z
[ "python", "datetime", "pandas", "dataframe", "python-datetime" ]
Pandas DatetimeIndex converting dates to 1970
38,484,277
<p>I have recently faced a similar problem (<a href="http://stackoverflow.com/questions/38201666/pandas-datetimeindex-from-mongodb-isodate">answered here</a>) whereby conversion of a date to a pandas <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#datetimeindex" rel="nofollow">DatetimeIndex</a> and subsequent <code>groupby</code> using those dates led to an error where the date appeared as <code>1970-01-01 00:00:00+00:00</code>. </p> <p>I'm facing this problem in a different context now, and the previous solution isn't helping me. </p> <p>I have a frame like this</p> <pre><code>import pandas as pd from dateutil import tz data = { 'Events' : range(1, 5 + 1 ,1), 'ID' : [1, 1, 1, 1, 1]} idx = pd.date_range(start='2008-01-01', end='2008-01-05', freq='D', tz=tz.tzlocal()) frame = pd.DataFrame(data, index=idx) Events ID 2008-01-01 00:00:00+00:00 1 1 2008-01-02 00:00:00+00:00 2 1 2008-01-03 00:00:00+00:00 3 1 2008-01-04 00:00:00+00:00 4 1 2008-01-05 00:00:00+00:00 5 1 </code></pre> <p>and I want to change the index from just the date, to a <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow">MultiIndex</a> of <code>[date, ID]</code>, but in doing so that "1970 bug" appears </p> <pre><code>frame.set_index([frame.ID, frame.index]) Events ID ID 1 2008-01-01 00:00:00+00:00 1 1 1970-01-01 00:00:00+00:00 2 1 1970-01-01 00:00:00+00:00 3 1 1970-01-01 00:00:00+00:00 4 1 1970-01-01 00:00:00+00:00 5 1 </code></pre> <p><strong>Versions</strong></p> <ul> <li>Python 2.7.11</li> <li>Pandas 0.18.0</li> </ul>
2
2016-07-20T14:37:35Z
38,487,216
<pre><code>frame = frame.reset_index() frame = frame.set_index([frame.ID, frame.index]) print frame index Events ID ID 1 0 2008-01-01 00:00:00-05:00 1 1 1 2008-01-02 00:00:00-05:00 2 1 2 2008-01-03 00:00:00-05:00 3 1 3 2008-01-04 00:00:00-05:00 4 1 4 2008-01-05 00:00:00-05:00 5 1 print frame.info() &lt;class 'pandas.core.frame.DataFrame'&gt; MultiIndex: 5 entries, (1, 0) to (1, 4) Data columns (total 4 columns): level_0 5 non-null int64 index 5 non-null datetime64[ns, tzlocal()] Events 5 non-null int64 ID 5 non-null int64 dtypes: datetime64[ns, tzlocal()](1), int64(3) memory usage: 200.0+ bytes </code></pre>
1
2016-07-20T17:37:10Z
[ "python", "datetime", "pandas", "dataframe", "python-datetime" ]
How to tell when a QTableWidgetItem is being modified
38,484,452
<p>I'm writing an app in Python with the <em>PySide</em> library. I have a <code>QTableWidget</code> that gets updated about every second. The thing is, I want to be able to change the data manually, and I thought that if I could find out whether or not the user is changing the data in the cell, then I could just prevent the program from updating this cell. Otherwise I get "kicked out" of the cell at each update.</p> <ul> <li><p>Is this a good idea? Should I try something else and why?</p></li> <li><p>How can I achieve my goal?</p></li> </ul> <p>Many thanks</p> <hr> <p><strong>EDIT :</strong></p> <p>I know there exists an <code>itemChanged</code> signal, but what I'd really like to know is if there is a way to tell <em>when the user is writing a new value in the cell</em>, in order not to kick them out while editing.</p>
1
2016-07-20T14:44:44Z
38,486,018
<p>In Qt Document:</p> <p><strong>void QTableWidget::itemChanged(QTableWidgetItem * item)<br> This signal is emitted whenever the data of item has changed.</strong></p> <p>Hope this will help you.</p> <p>Edit:</p> <p>QTableWidget uses a default itemdelegate(QItemDelegate instance) which has createEditor method and closeEditor signal.</p> <p>You can reimplement createEditor which means edit starts, and connect the signal closeEditor which means the edit ends.</p> <p>This may be the correct way.</p>
1
2016-07-20T16:30:45Z
[ "python", "qt", "pyqt", "pyside" ]
How to tell when a QTableWidgetItem is being modified
38,484,452
<p>I'm writing an app in Python with the <em>PySide</em> library. I have a <code>QTableWidget</code> that gets updated about every second. The thing is, I want to be able to change the data manually, and I thought that if I could find out whether or not the user is changing the data in the cell, then I could just prevent the program from updating this cell. Otherwise I get "kicked out" of the cell at each update.</p> <ul> <li><p>Is this a good idea? Should I try something else and why?</p></li> <li><p>How can I achieve my goal?</p></li> </ul> <p>Many thanks</p> <hr> <p><strong>EDIT :</strong></p> <p>I know there exists an <code>itemChanged</code> signal, but what I'd really like to know is if there is a way to tell <em>when the user is writing a new value in the cell</em>, in order not to kick them out while editing.</p>
1
2016-07-20T14:44:44Z
38,487,194
<p>Generally, you would handle this situation with the use of <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qitemdelegate.html" rel="nofollow"><code>QItemDelegates</code></a>, which allow you to control what cells are editable by the user, what types of controls they are given to edit the cells, and you can catch the data they input and validate or manipulate it before saving it to the model.</p> <p><code>QItemDelegates</code> only control edits being made using the view interface. If the table is being updated programmatically, the changes won't be sent to the <code>QItemDelegate</code>.</p> <p><a href="http://stackoverflow.com/a/37623147/1547004">Here is an example</a> of a <code>QItemDelegate</code> for a <code>QTableWidget</code></p>
1
2016-07-20T17:36:09Z
[ "python", "qt", "pyqt", "pyside" ]
.join for possible empty Queue in python
38,484,535
<p>I'm trying to implement a <code>Queue</code> processing thread in python as follows:</p> <pre><code>from queue import Queue from threading import Thread import sys class Worker(Thread): def __init__(self, queue): # Call thread constructor self.queue = queue def run(self): while True: task = self.queue.get() # doTask() self.queue.task_done() queue = Queue() thread = Worker(thread) thread.start() while True: inp = user_input() if condition(inp): queue.put(sometask()) else: queue.join() thread.join() sys.exit(0) </code></pre> <p>In this example, suppose user decides to <code>exit</code> without adding any item to queue. Then my thread will be blocking at <code>self.queue.get</code> and I <code>queue.join()</code> won't work. Because of that, I can't perform a proper <code>exit</code>.</p> <p>How can I deal with this issue?</p>
1
2016-07-20T15:20:26Z
38,484,756
<p>You can give <code>Queue.get</code> a timeout and use a stop event:</p> <pre><code>from Queue import Queue, Empty from threading import Thread, Event import sys class Worker(Thread): def __init__(self, queue, stop): # Call thread constructor self.queue = queue self.stop = stop super(Worker, self).__init__() def run(self): while not self.stop.is_set(): try: task = self.queue.get(timeout=1) except Empty: continue # doTask() self.queue.task_done() queue = Queue() stop = Event() thread = Worker(queue, stop) thread.start() while True: inp = raw_input() if inp: queue.put(inp) else: stop.set() queue.join() thread.join() sys.exit(0) </code></pre> <p>This adds a condition to the Thread worker's while loop so that you can stop it whenever. You have to give the <code>Queue.get</code> a timeout so that it can check the stop event periodically.</p> <h1>Update</h1> <p>You can use a sentinel rather than timeout:</p> <pre><code>from Queue import Queue from threading import Thread import sys _sentinel = Object() class Worker(Thread): def __init__(self, queue, sentinel=None): # Call thread constructor self.queue = queue self.sentinel = sentinel super(Worker, self).__init__() def run(self): while True: task = self.queue.get() if task is self.sentinel: self.queue.task_done() return # doTask() self.queue.task_done() queue = Queue() thread = Worker(queue, sentinel=_sentinel) thread.start() while True: inp = raw_input() if inp: queue.put(inp) else: queue.put(_sentinel) queue.join() thread.join() sys.exit(0) </code></pre> <p>Thanks to Bakuriu for the sentinel = Object() suggestion.</p>
1
2016-07-20T15:30:44Z
[ "python", "multithreading", "python-3.x", "blockingqueue" ]
Have a list of dicts need to write csv file in python
38,484,646
<p>I need to ouput a list of dicts in python to a csv file. But I wanted to split them by filename. I have a list of dicts that looks like this:</p> <pre><code>{'Filename': 'F:\\Desktop\\Metadata\informationtechnologies1.pdf', 'DESCRIPTION': [u'This is a test sentence.'], 'NAME': [u'This is a test name'], 'PERIOD': [], 'INFO2': [u'TEST1', u'TEST2', u'TEST3', u'TEST4', u'TEST5',], 'INFO': [u'TEST6', u'TEST7', u'TEST8', u'TEST9', u'TEST10', u'TEST11',]}, {'Filename': 'F:\\Desktop\informationtechnologies.pdf', </code></pre> <p>I need to print these exactly how it appears in a single column, with the results being in a new row. Preferably a new line after each filename to separate all the results. For example:</p> <p><code>Filename: informationtechnologies1.pdf DESCRIPTION: This is a sentence INFO2: TEST2 TEST3 TEST4 TEST5</code></p> <p><code>Filename:informationtechnologies.pdf</code></p> <p>I have tried the following code but it places it each list into single columns(one column can have a list of 20 pieces of data in the info columns):</p> <pre><code>df = DataFrame.from_dict(results) df.to_csv("F:\Desktop/meta.csv",encoding='utf-8') </code></pre> <p>I need the data to be all iterated in column 1, so if there is a list within a dict I want each item in that list to print on a new line</p>
0
2016-07-20T15:26:25Z
38,486,017
<p>What you show is not a csv file but a plain text file.</p> <p>Assuming your requirements are:</p> <ul> <li>if a directory contains the key <code>Filename</code> print on first line the key, a colon, a space and the value</li> <li>for all other key, value items in the directory, first print a line with the key followed by a colon, then assuming the value is a list of unicode strings, print each value of the list encoded as utf8 on a line; if the value is not a list, convert it to unicode and print it encoded as utf8</li> <li>print an empty line after each directory</li> </ul> <p>I would use explicit loops and tests, because I do not know any tool that does this out of the box:</p> <pre><code>with open("F:\\Desktop/meta.csv", "w") as fd: for d in results: if 'Filename' in d: dummy = fd.write('Filename: ' + d['Filename'] + '\n') for k, l in d.iteritems(): if k != 'Filename': dummy = fd.write(k + ':\n') if isinstance(l, list): for item in l: dummy = fd.write(item.encode('utf8') + '\n') else: dummy = fd.write(unicode(l).encode('utf8') + '\n') dummy = fd.write('\n') </code></pre>
0
2016-07-20T16:30:43Z
[ "python", "python-2.7", "csv", "dictionary" ]
Calculate Number of Last Week in Isocalendar Year
38,484,950
<p>I am writing a script to grab files from a directory based on the week number in the filenames. I need to grab files with week N and week N+1 in the filenames. </p> <p>I have the basics down, but am now struggling to figure out the rollover for new years (the file format uses the isocalendar standard). Isocalendars can have either 52 or 53 weeks in them, so I need a way to figure out if the year I'm in is a 52 or 53 week year so that I can then compare to the results of <code>datetime.now().isocalendar()[1]</code> and see if I need to set <code>N+1</code> to 1.</p> <p>Is there a built in python function for this?</p>
0
2016-07-20T15:39:36Z
38,485,086
<p>Why not just use <code>(datetime.now() + timedelta(days=7)).isocalendar()[1]</code> rather than calculating it from the current week number at all?</p>
1
2016-07-20T15:45:13Z
[ "python" ]
Python interpreter does not show in Pycharm
38,485,010
<p>When I run <code>Pycharm</code> and select new project, there is no interpreter for me to select (please see the screenshot below), so what should I do and how do I fix this, please? I have installed Python 3.5.1 version on my Windows 7.</p> <p>Thanks!</p> <p><img src="http://i.stack.imgur.com/gxb00.jpg" alt="interpreter screenshot"></p>
-1
2016-07-20T15:42:32Z
38,485,184
<p>You can click right "Gear" icon in setting dialog, then select "Add local" add Python interpreter</p>
0
2016-07-20T15:50:14Z
[ "python", "python-3.x", "pycharm" ]
Python pafy global not working across a function-call boundary
38,485,103
<p>Okay, I was trying to make a simple script to download youtube videos using <a href="http://pythonhosted.org/Pafy/" rel="nofollow"><code>pafy</code></a>. Currently I have a problem with the global variable <code>video</code> which I use to store what <code>pafy.new('url')</code> returns. Here's the two functions I use:</p> <pre><code>video = {}; def downloadVideo(): options = {}; options['initialdir'] = 'C:\\'; options['mustexist'] = False; options['title'] = 'Download folder'; dir_path = tkinter.filedialog.askdirectory(**options); global video; video.getbest(preftype="mp4").download(quiet=True, filepath=dir_path); def get(): url = url_entry.get(); if url == '': return global video; video = pafy.new(url); # Some code to display video info </code></pre> <p>First I use <code>get()</code> function to get the video from <code>url_entry</code> which is a tkinter Entry widget. So far so good, but when I call <code>downloadVideo()</code> I get this error:</p> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'download'</p> </blockquote>
1
2016-07-20T15:46:06Z
38,491,155
<p>Found the problem in this line:</p> <pre><code>video.getbest(preftype="mp4").download(quiet=True, filepath=dir_path); </code></pre> <p>This:</p> <pre><code>video.getbest(preftype="mp4") </code></pre> <p>actually returned a <code>NoneType</code> object since it didn't contain any <code>mp4</code> stream. So, it's not exactly a problem, it's just something I should check before calling <code>download()</code>. Now I just get all the streams <code>video.streams</code> and download what I need or just let it download the best available <code>video.getbest().download()</code>.</p>
0
2016-07-20T21:27:51Z
[ "python", "python-3.x", "attributes", "global-variables", "instance" ]
Python cx_oracle variables
38,485,112
<pre><code>try: for row in data: id = row[0] name= row[1] b.execute("INSERT INTO NAME (NUMBER, NAME, ID) VALUES (1, %s, %s)" %(name, id)) conn.commit() except: #rest code </code></pre> <p>I can not add values to the database (as much as I understand it is because of the <strong>name</strong> variable), I always receive this error: <strong> ORA-00936: missing expression</strong>. What is wrong in my code? How should i specify parameter correctly?</p>
0
2016-07-20T15:46:40Z
38,504,872
<p>Use bind variables instead. Do not use %s and put the parameter directly in the string as this leads to possible SQL injection, not to mention quoting issues. This method permits passing any legal value without having to worry about such things!</p> <pre><code>try: for row in data: id = row[0] name= row[1] b.execute("INSERT INTO NAME (NUMBER, NAME, ID) VALUES (1, :1, :2)", (name, id)) conn.commit() except: # rest code </code></pre>
2
2016-07-21T12:55:29Z
[ "python", "database", "oracle", "variables", "cx-oracle" ]
Creating xml request using urllib2
38,485,119
<p>I need to create request to access to the XML services, it should be processed through a HTTP. Ass says in documentation I have to send "4 associated parameters and this parameters will work as identification and will provide the request". This parameters should look like strings:</p> <pre><code>"codes=12345" "user=user12345" "password=pass12345" "partner=part12345" </code></pre> <p>According documentation i have two systems for sending the XML file of the request:</p> <p>1 Through an URL coded in MIME format application/x-www-form- urlencoded: URL (“urlfile”)</p> <p>2 By entering the data directly in a variable, coded in MIME format application/x-www-form-urlencoded: Directly in a variable (“xml”).</p> <p>According to this my request data looks like this:</p> <pre><code>data=' &lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt; &lt;!DOCTYPE petition SYSTEM "http://xml.example.com/xml/dtd/xml.dtd"&gt; &lt;petition&gt; &lt;number&gt;Country request&lt;/number&gt; &lt;partner&gt;Company&lt;/partner&gt; &lt;type&gt;5&lt;/type&gt; &lt;/petition&gt;' </code></pre> <p>I create this request using python library urllib2. So here is my code:</p> <pre><code>request = urllib2.Request(url, data) request.add_header("codes=12345", "user=user12345", "password=pass12345", "partner=part12345") </code></pre> <p>But i got an error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: add_header() takes exactly 3 arguments (5 given) </code></pre> <p>So i changed header on this:</p> <pre><code>header = {'codes':'12345','user':'user12345','password':'pass12345','partner':'part12345'} </code></pre> <p>And this is how looks like my code after that:</p> <pre><code>request = urllib2.Request(url, data, header) response_xml = urllib2.urlopen(request) response = response_xml.read() print(response) </code></pre> <p>But I got response such if i not authenticated user. What i'm doing wrong? Thank You!</p>
0
2016-07-20T15:47:02Z
38,485,244
<p>Try this:</p> <pre><code>from urllib import urlencode from urllib2 import urlopen args = {'codes':'12345','user':'user12345','password':'pass12345','partner':'part12345'} conn = urlopen(url,urlencode(args)) data = conn.read() conn.close() print(data) </code></pre>
1
2016-07-20T15:52:53Z
[ "python", "urllib2" ]
Access violation exception Oculus VR DK2
38,485,122
<p>This python code raises vioaltion access error(last line):</p> <pre><code>import time from ovrsdk import * ovr_Initialize() hmd = ovrHmd_Create(0) hmdDesc = ovrHmdDesc() ovrHmd_GetDesc(hmd, byref(hmdDesc)) </code></pre> <p>Error:</p> <pre><code> File "D:\Georgy2\mypyscripts\ovr01.py", line 12, in &lt;module&gt; ovrHmd_GetDesc(hmd, byref(hmdDesc)) WindowsError: exception: access violation reading 0x00001148 </code></pre> <p>I've installed last version of </p> <p>Technical info:</p> <pre><code>Display Driver Version: 1.2.6.0 Positional Tracker Driver Version: 1.0.14.0 Intel(R) HD Graphics Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz HMD Firmware: 2.12 Connected to OVRService server. </code></pre> <p>Code is from the <a href="https://github.com/cmbruns/pyovr" rel="nofollow">https://github.com/cmbruns/pyovr</a></p> <p>I am new to python and (analogously to C case) I checked the values of hmd and hmdDesc. They are not zero:</p> <pre><code>&lt;ovrsdk.windows.wrapper.LP_struct_ovrHmdStruct object at 0x02098210&gt; &lt;ovrsdk.windows.wrapper.struct_ovrHmdDesc_ object at 0x020983F0&gt; </code></pre> <p>How to solve this problem? (I need simple scene to do some math with image in VR.)</p> <p>p.s. I have to ask here because of Oculus Forums are not working for me. (the page <a href="https://secure.oculus.com/login/" rel="nofollow">https://secure.oculus.com/login/</a> does not look correct)</p>
1
2016-07-20T15:47:10Z
38,491,292
<p>What Oculus runtime version do you have installed? The import statement and the calls you're making make it look as if you're using <a href="https://github.com/wwwtyro/python-ovrsdk" rel="nofollow">this</a> library, but that hasn't been updated in two years. I'm not sure it will even work with a DK2 compatible runtime.</p> <p>If you're on Windows (and only targeting windows) you should be using the 1.3 runtime at least. If you're targeting Linux and Mac, you should be using the 0.8 runtime, with the understanding that it won't work with any Windows machine running the 1.3 runtime.</p> <p>In order to use those versions with Python you need to be using the <a href="https://github.com/cmbruns/pyovr" rel="nofollow">cmbruns python bindings</a>, which include a number of examples along with the bindings. </p>
2
2016-07-20T21:38:38Z
[ "python", "oculus" ]
Python, BeautifulSoup - Extracting part of a string
38,485,167
<p>I'm working on a side project to see if I can predict the wins on a website, however this is one of the first times I've used BeautifulSoup and I'm not entirely sure on how to cut a string down to size. </p> <p>Here is the code, I basically want to grab the information that holds where it crashed.</p> <pre><code>from bs4 import BeautifulSoup from urllib import urlopen html = urlopen('https://www.csgocrash.com/game/1/1287324').read() soup = BeautifulSoup(html) for section in soup.findAll('div',{"class":"row panel radius"}): crashPoint = section.findChildren()[2] print crashPoint </code></pre> <p>Upon running it, I get this as the output.</p> <pre><code>&lt;p&gt; &lt;b&gt;Crashed At: &lt;/b&gt; 1.47x &lt;/p&gt; </code></pre> <p>I want to basically only want to grab the number value, which would require me to cut from both sides, I just don't know how to go about doing this, as well as removing the HTML tags.</p>
1
2016-07-20T15:49:34Z
38,485,197
<p>Find the <code>Crashed At</code> label by text and get the <em>next sibling</em>:</p> <pre><code>soup = BeautifulSoup(html, "html.parser") for section in soup.findAll('div', {"class":"row panel radius"}): crashPoint = section.find("b", text="Crashed At: ").next_sibling.strip() print(crashPoint) # prints 1.47x </code></pre> <hr> <p>Also, not sure if you need a loop in this case since there is a single <code>Crashed At</code> value:</p> <pre><code>from bs4 import BeautifulSoup from urllib import urlopen html = urlopen('https://www.csgocrash.com/game/1/1287324').read() soup = BeautifulSoup(html, "html.parser") section = soup.find('div', {"class":"row panel radius"}) crashPoint = section.find("b", text="Crashed At: ").next_sibling.strip() print(crashPoint) </code></pre>
2
2016-07-20T15:50:52Z
[ "python", "beautifulsoup" ]
Form autosubmit on radio/checkbox action (Python Flask)
38,485,217
<p>I currently am working on a dashboard tool. here I use Python to go through a dataframe, and create filters based on the data. I have the following code as an example output:</p> <pre><code>&lt;form name="FormYear" method="post"&gt; &lt;div class="panel"&gt; &lt;div id="checkboxes"&gt; &lt;div class="filterdiv"&gt; Forecast Year &lt;button class="filterButton clearfilter" type="submit" name="submit" value="clearFilterYear"&gt; &lt;i class="glyphicon glyphicon-remove"&gt;&lt;/i&gt; &lt;/button&gt; &lt;button class="filterButton filter" type="submit" name="submit" value="filter"&gt; &lt;i class="glyphicon glyphicon-filter"&gt;&lt;/i&gt; &lt;/button&gt; &lt;/div&gt; &lt;input value = "1" type="hidden" name="FormYear"&gt; &lt;input type="radio" name="Year" id="Year2016" value="2016" checked class="checkbox" &gt; &lt;label class="checkboxLabel" for="Year2016"&gt;2016&lt;/label&gt; &lt;input type="radio" name="Year" id="Year2017" value="2017" class="checkbox" &gt; &lt;label class="checkboxLabel" for="Year2017"&gt;2017&lt;/label&gt; &lt;input type="radio" name="Year" id="Year2018" value="2018" class="checkbox" &gt; &lt;label class="checkboxLabel" for="Year2018"&gt;2018&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>The above code contains 2 submit buttons (one to submit the selections, and one to clear all selections) and 3 radiobuttons. in order to style the radio buttons I am using the Labels and css. </p> <p>The dashboard will contain many such forms, and I would like to be able to have the form submit whenever the user either checks a checkbox, or a radio button.</p> <p>Basically I need to have the site hit the second button whenever the user changes a filter.</p> <p>Can this be done?</p>
0
2016-07-20T15:51:36Z
38,506,676
<p>You can use <a href="https://pythonhosted.org/Flask-Sijax/" rel="nofollow">Flask-Sijax</a>, it helps you add <a href="https://pypi.python.org/pypi/Sijax" rel="nofollow">Sijax</a> support to your Flask applications. Sijax is an easy to use AJAX library.</p> <pre><code>@flask_sijax.route(app, '/hello') def hello(): def say_hi(obj_response): obj_response.alert('Hi there!') if g.sijax.is_sijax_request: # Sijax request detected - let Sijax handle it g.sijax.register_callback('say_hi', say_hi) return g.sijax.process_request() return _render_template('sijaxexample.html') </code></pre>
0
2016-07-21T14:15:06Z
[ "jquery", "python", "forms", "flask", "submit" ]
Plotting scatter graph with marginal histograms with Python seaborn 0.7
38,485,252
<p>I have some python code that plotted a scatter graph with marginal histograms. This worked fine with seaborn 0.5 and still does work if I go back to this version. However, I'd like to get it to work with 0.7!</p> <p>I don't use python often and mainly only use scripts set up by others that I adjust slightly.</p> <p>The problem appears to be happening in the following line:</p> <pre><code>sns.lmplot(x='Moisture Content (%)', y='Dry Density (kg/m3)', hue='Test', data=data, ax=ax_joint, fit_reg=False, legend=False, palette=test_colours) </code></pre> <p>ax is no longer recognised in seaborn 0.7.</p> <pre><code>TypeError: lmplot() got an unexpected keyword argument 'ax' </code></pre> <p>The output still gives me completed marginal histograms but the scatter graph is blank.</p> <p>If you need more info then please let me know.</p> <p>Cheers</p>
0
2016-07-20T15:53:38Z
39,910,484
<p><code>seaborn lmplot ax</code> will show you that <code>lmplot</code> returns you a <code>figure-level</code> instead of <code>axes-level</code>. So in order to manage <code>lmplot</code> use <code>FacetGrid</code>.</p> <p><code>FacetGrid</code> will plot on different variables that you states in different graphs.</p> <pre><code>import matplotlib.pyplot as plt g = sns.FacetGrid(tips, col="time", row="smoker") g = g.map(plt.hist, "total_bill") </code></pre> <p><a href="https://stanford.edu/~mwaskom/software/seaborn/_images/seaborn-FacetGrid-2.png" rel="nofollow">FacetGrid result image</a></p> <p>You can imagine doing a <code>groupby</code> on the dataframe which gives you the different graphs.</p> <p>Refer to <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.lmplot.html" rel="nofollow">this</a> for more example on plotting <code>lmplot</code></p>
0
2016-10-07T06:06:27Z
[ "python", "scatter-plot", "seaborn" ]
tkinter.TclError: invalid command name "table"
38,485,253
<p>Okay, first of all I don't know what is the actual problem here so I couldn't come up with a more accurate title. Maybe some of you can edit it to make it accurate</p> <p>The following is the minimalised code to reproduce the problem I'm having.</p> <pre><code>from traybar import SysTrayIcon from cal import Calendar import Tkinter class Add(): def __init__(self,master): Calendar(master).pack() def add(systray): root = Tkinter.Tk() Add(root) root.mainloop() SysTrayIcon("abc.ico","abc", (('Add',None, add), ) ,default_menu_index=0).start() </code></pre> <p>The <code>cal</code> and the <code>trabar</code> are these files <a href="http://tkinter.unpythonic.net/wiki/TkTableCalendar" rel="nofollow">http://tkinter.unpythonic.net/wiki/TkTableCalendar</a> and <a href="https://github.com/Infinidat/infi.systray/blob/develop/src/infi/systray/traybar.py" rel="nofollow">https://github.com/Infinidat/infi.systray/blob/develop/src/infi/systray/traybar.py</a> respectively.</p> <p>If you run this, it will make a icon in the system tray of a windows machine with the options <code>Add</code> and <code>Quit</code>. clicking on the <code>app</code> opens up the calender, no problem. Close the calender and click on the <code>Add</code> again. But this time it doesn't open the calendar and throws the following error</p> <pre><code>` Traceback (most recent call last): File "_ctypes/callbacks.c", line 314, in 'calling callback function' File "C:\Users\Koushik Naskar\AppData\Roaming\Python\Python27\site-packages\traybar.py", line 79, in WndProc self._message_dict[msg](hwnd, msg, wparam.value, lparam.value) File "C:\Users\Koushik Naskar\AppData\Roaming\Python\Python27\site-packages\traybar.py", line 276, in _command self._execute_menu_option(id) File "C:\Users\Koushik Naskar\AppData\Roaming\Python\Python27\site-packages\traybar.py", line 283, in _execute_menu_option menu_action(self) File "C:\Users\Koushik Naskar\Desktop\So\temp.py", line 11, in add Add(root) File "C:\Users\Koushik Naskar\Desktop\So\temp.py", line 7, in __init__ Calendar(master).pack() File "C:\Users\Koushik Naskar\Desktop\So\cal.py", line 66, in __init__ state='disabled', browsecommand=self._set_selection) File "C:\Python27\lib\lib-tk\tktable.py", line 118, in __init__ Tkinter.Widget.__init__(self, master, 'table', kw) File "C:\Python27\lib\lib-tk\Tkinter.py", line 2090, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: invalid command name "table" ` </code></pre> <p>This problem only appears when I use <code>SysTrayIcon</code> with the <code>Calendar</code>.Instead of <code>Calendar</code> if you use simple <code>Tkinter</code> <code>Button</code> or <code>Label</code> etc. this error doesn't appear. Also I can use the <code>Calendar</code> widget normally (without the <code>SysTrayIcon</code> ) in a usual Tkinter GUI as many times as I want, no error occur there. Now I don't have any clue about whats happenning here and how to fix this. What problem does <code>SysTrayIcon</code> have with <code>Calendar</code> and Why the error doesn't happen the first time I open the GUI? Please help.</p>
1
2016-07-20T15:53:40Z
38,486,162
<p>TkTableCalendar requies the tktable module, which you have installed in lib-tk (3rd party modules usually go into lib/site-packages) as indicated by this part of the traceback.</p> <pre><code>File "C:\Python27\lib\lib-tk\tktable.py", line 118, in __init__ Tkinter.Widget.__init__(self, master, 'table', kw) </code></pre> <p>The tktable module requires that your tcl/tk installation have the tktable extension. That extension defines the 'table' widget. It is not part of the standard tcl/tk that is installed with Python on Windows. Hence</p> <pre><code>_tkinter.TclError: invalid command name "table" </code></pre> <p>The tktable source code (probably a mixture of tcl and C) is hosted at <a href="https://sourceforge.net/projects/tktable/" rel="nofollow">SourceForge</a>. <a href="http://wiki.tcl.tk/1877" rel="nofollow">This page</a> says that it <em>is</em> part of the ActiveState Batteries Included distribution. I don't know if the free version of AS tcl/tk has all the 'batteries'. And I don't know how to replace the tcl/tk installation you already have with a new one. I personally would use an alternative if possible.</p>
1
2016-07-20T16:38:51Z
[ "python", "multithreading", "tkinter", "tcl", "tktable" ]
Run a certain function according to a dictionary value in Python
38,485,263
<p>I built a script which runs a certain function according to a specific condition, the thing is I am sure there is a smarter way to do this.</p> <p>The current code I have is:</p> <pre><code>list_of_dicts= [{'brand':'a', 'url':'b'}, [{'brand':'b', 'url':'b'}] for element in list_of_dicts: if element['brand'] == 'a': function_a(element['url']) elif element['brand'] == 'b']: function_b(element['url']) else: None </code></pre> <p>Imagine I have instead of 2 brands, around 7, it's still feasible in this way, but I want to know if there is a better way to do this.</p>
0
2016-07-20T15:54:14Z
38,485,389
<p>Functions are objects too (sorta...) and so you can just connect the <code>brand</code> key to a function like this:</p> <pre><code>list_of_dicts= [{'brand':function_a, 'url':'b'}, [{'brand':function_b, 'url':'b'}] </code></pre> <p>and then just grab the function with the key:</p> <pre><code>for element in list_of_dicts: element['brand'](element['url']) </code></pre>
2
2016-07-20T15:59:24Z
[ "python", "dictionary", "functional-programming" ]
Run a certain function according to a dictionary value in Python
38,485,263
<p>I built a script which runs a certain function according to a specific condition, the thing is I am sure there is a smarter way to do this.</p> <p>The current code I have is:</p> <pre><code>list_of_dicts= [{'brand':'a', 'url':'b'}, [{'brand':'b', 'url':'b'}] for element in list_of_dicts: if element['brand'] == 'a': function_a(element['url']) elif element['brand'] == 'b']: function_b(element['url']) else: None </code></pre> <p>Imagine I have instead of 2 brands, around 7, it's still feasible in this way, but I want to know if there is a better way to do this.</p>
0
2016-07-20T15:54:14Z
38,485,531
<p>You can create a separate <code>dict</code> storing the functions from where you can then retrieve the appropriate function with brand:</p> <pre><code>list_of_dicts= [{'brand':'a', 'url':'b'}, {'brand':'b', 'url':'b'}] def function_a(url): print('A ' + url) def function_b(url): print('B ' + url) funcs = { 'a': function_a, 'b': function_b } for element in list_of_dicts: func = funcs.get(element['brand']) if func: func(element['url']) </code></pre> <p>Output:</p> <pre><code>A b B b </code></pre>
2
2016-07-20T16:05:28Z
[ "python", "dictionary", "functional-programming" ]
Reconstruct vector field from python dictionary keyed by nested tuple
38,485,307
<p>There's a dictionary in the following form:</p> <pre><code>vector_dict = {((3, 4), 2): 4678, ((0, 2), 1): 0, ... } </code></pre> <p>The tuple nested in the tuple corresponds to xy-coordinates. The next part is an integer with possible values n= 0, 1, 2, 3 representing the four main directions. The values keyed by that represent some magnitude. So the first key value pair becomes: Vector [1,0], located at x=3, y=4, scaled by 4,678. I tried using pandas but at I can't get my head around it, how to properly extract this in a usable way. Later I want to plot it broadly similar to the one on the right but completely filling the board: <a href="http://i.stack.imgur.com/qeHYo.png" rel="nofollow"><img src="http://i.stack.imgur.com/qeHYo.png" alt="enter image description here"></a></p>
1
2016-07-20T15:56:00Z
38,485,806
<p>Check out the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow">Series constructor</a> to load the data from a <code>dict</code>. Then you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow"><code>unstack</code></a> to get the direction in axis 1. Lastly, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_tuples.html" rel="nofollow">convert</a> the positional index into a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.html" rel="nofollow">MultiIndex</a>.</p> <pre><code>d = {((3, 4), 2): 4678, ((0, 2), 1): 0} df = pd.Series(d).unstack() df.index = pd.MultiIndex.from_tuples(df.index, names=['x', 'y']) print(df) </code></pre> <p>yields</p> <pre><code> 1 2 x y 0 2 0.0 NaN 3 4 NaN 4678.0 </code></pre>
1
2016-07-20T16:19:59Z
[ "python", "pandas", "dictionary", "nested", "tuples" ]
How do I force these ttk apps to resize when I resize the window?
38,485,410
<p>I have comments in a number of places where I've tried to use the columnconfigure or rowconfigure methods to cause the windows to resize, but none of it seems to be working. I can also take out mainloop() and my program runs exactly the same. This leads me to believe I'm perhaps not calling/using mainloop correctly. The methods are mostly just for organization, and I know they're not reusable methods right now. I was planning on maybe fixing that at some point, but that's not the purpose of this post. </p> <pre><code>#!/usr/bin/python from tkinter import * from tkinter import ttk import webbrowser from dictionary import * class AI(): def __init__(self): self.urls = dictionary.get() self.makeMainframe() self.makeLabels() self.makeDropDown() self.makeButton() self.makeEntry() for child in self.mainframe.winfo_children(): child.grid_configure(padx=2, pady=2) #child.columnconfigure(index='all',weight=1) #child.rowconfigure(index='all',weight=1) def openMenu(self): webbrowser.open(self.urls[self.lunchVar.get()]) print(self.urls[self.lunchVar.get()]) def saveChoice(self, event): print(self.foodVar.get()) def makeMainframe(self): self.mainframe = ttk.Frame(padding="3 3 12 12") self.mainframe.grid(column=0, row=0, sticky=(N,W,E,S)) #self.mainframe.columnconfigure('all', weight=1) #self.mainframe.rowconfigure(index='all', weight=1) def makeDropDown(self): self.lunchVar = StringVar() self.lunchChoice = ttk.Combobox(self.mainframe, textvariable=self.lunchVar, state='readonly') self.lunchChoice['values'] = list(self.urls.keys()) self.lunchChoice.grid(column=2, row=1, sticky=(W, E)) def makeLabels(self): ttk.Label(self.mainframe, text="Today's lunch is from...").grid(column=1, row=1, sticky=(E,W)) ttk.Label(self.mainframe, text="Click here for a menu --&gt;").grid(column=1, row=2, sticky=(E,W)) ttk.Label(self.mainframe, text="What will you be having?").grid(column=1, row=3, sticky=(E,W)) def makeButton(self): self.menu = ttk.Button(self.mainframe, textvariable=self.lunchVar, command=self.openMenu) self.menu.grid(column=2, row=2, sticky=(W, E)) def makeEntry(self): self.foodVar = StringVar() self.foodChoice = ttk.Entry(self.mainframe, textvariable=self.foodVar) self.foodChoice.grid(column=2, row=3, sticky=(E,W)) self.foodChoice.bind("&lt;Return&gt;", self.saveChoice) #self.foodChoice.columnconfigure(index='all', weight=1) AI=AI() mainloop() </code></pre>
0
2016-07-20T16:00:19Z
38,485,756
<p>You place <code>self.mainframe</code> in the root window, but you never give any rows and columns in the root window a weight. You also never explicitly create a root window, though that isn't contributing to the problem. Also, <code>"all"</code> isn't a valid row or column. </p> <p>The first step is to get your main frame to resize, then you can focus on the contents inside the frame.</p> <pre><code>def makeMainframe(self): ... self.mainframe._root().columnconfigure(0, weight=1) self.mainframe._root().rowconfigure(index=0, weight=1) </code></pre> <p>Note: in the case where you're putting a single frame inside some other widget (such as the root window), <code>pack</code> is arguably a better choice because you don't have to remember to give weight to the rows and columns. You can replace this:</p> <pre><code>self.mainframe.grid(column=0, row=0, sticky=(N,W,E,S)) self.mainframe._root().columnconfigure(0, weight=1) self.mainframe._root().rowconfigure(index=0, weight=1) </code></pre> <p>... with this:</p> <pre><code>self.mainframe.pack(fill="both", expand=True) </code></pre> <p>Assuming that you want the entry widgets to expand to fill the space horizontally, you need to do the same with <code>mainframe</code>:</p> <pre><code>def makeMainframe(self): ... self.mainframe.grid_columnconfigure(2, weight=1) </code></pre>
0
2016-07-20T16:17:11Z
[ "python", "tkinter", "ttk" ]
Iterate throughout different python files as variable
38,485,605
<p>I wonder how to invoke python files as variable. imagine that <code>i</code> is the name of one file </p> <p>obviously the example doesn't work but it shows a case. every file has the same class structure</p> <pre><code>for i in test: '%d'.ClassName.method(variables) %(i,) </code></pre>
-3
2016-07-20T16:09:07Z
38,487,320
<p>The question could have been clearer but I think I know what you are asking. You have a bunch of values (in this case the file names) which you want to use as variables. I had a similar requirement previously, but in my case I had to use the string as a method name.</p> <pre><code>method = getattr(self, "add_rule_%s" % rule_type) method(argument1, argument2) </code></pre> <p>In the above code, rule_type holds a value, it could be <code>sender_email_address</code>, <code>sender_domain</code>, etc. I have corresponding methods written: <code>add_rule_sender_email_address</code>, <code>add_rule_sender_domain</code>, etc.</p> <p>In this case, I used <code>self</code> because those methods (<code>add_rule_xxx</code>) are present in the same class, if they are in a different class we should use that handle.</p> <p>Otherwise, there is another solution using <code>locals()</code> and <code>globals()</code>. Reference: <a href="http://stackoverflow.com/questions/8028708/dynamically-set-local-variable-in-python">Dynamically set local variable in Python</a></p>
0
2016-07-20T17:43:23Z
[ "python", "python-2.7", "python-3.x" ]
entry points from setup.py not working
38,485,654
<p>I am trying to get an entry point to run my flask application.</p> <p>I think its due to the directory structure:</p> <pre><code>my_app - __init__.py - app.py - setup.py - etc.. </code></pre> <p>My setup.py file:</p> <pre><code>from setuptools import setup, find_packages import os.path def read_requirements(pathname): with open(pathname) as f: return [line for line in (x.strip() for x in f) if not line.startswith('#')] def project_path(*names): return os.path.join(os.path.dirname(__file__), *names) setup( name='my_app', version='0.1.0', install_requires=read_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt')), test_suite='nose.collector', entry_points={ 'console_scripts': [ 'START_ME=app:run', ], }, classifiers=["Programming Language :: Python :: 2.7"], description=__doc__, long_description='\n\n'.join(open(project_path(name)).read() for name in ( 'README.md', )), zip_safe=False, include_package_data=True, packages=find_packages(), ) </code></pre> <p>I think the <code>find_packages()</code> method is not picking up the fact that its in the package, maybe its looking in lower level directories for packages? I've tried <code>find_packages('.')</code> to try get it to search in the project root directory but this did not work. </p> <p>Can i get this to work without changing my directory structure?</p> <p>Here's the actual project:</p> <p><a href="https://github.com/ThriceGood/Mimic" rel="nofollow">https://github.com/ThriceGood/Mimic</a> </p> <p>EDIT:</p> <p>Also, I noticed that when I run setup.py install I get a top_level.txt file in my egg.info folder, it says that the top level is actually a package that exists inside of the root/main package, like:</p> <pre><code> / main_package - __init__.py - app.py / sub_package - __init__.py - sub.py </code></pre> <p>in the top_level.txt file, <code>sub_package</code> is written.</p>
0
2016-07-20T16:11:52Z
38,498,662
<p>I just ended up putting all the flask app files into a sub directory inside the project root directory. fixed it nicely.</p> <pre><code>/project - setup.py /flask_app - __init__.py - app.py </code></pre>
0
2016-07-21T08:15:23Z
[ "python", "flask", "setuptools", "setup.py" ]
Python - Find sequence of same characters
38,485,735
<p>I'm trying to use regex to match sequences of one or more instances of the same characters in a string. </p> <p>Example : </p> <pre><code>string = "55544355" # The regex should retrieve sequences "555", "44", "3", "55" </code></pre> <p>Can I have a few tips?</p>
0
2016-07-20T16:16:06Z
38,485,787
<p>You can do this easily without regex using <a href="https://docs.python.org/3.4/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; s = '55544355' &gt;&gt;&gt; [''.join(g) for _, g in groupby(s)] ['555', '44', '3', '55'] </code></pre>
1
2016-07-20T16:18:53Z
[ "python", "regex" ]
Python - Find sequence of same characters
38,485,735
<p>I'm trying to use regex to match sequences of one or more instances of the same characters in a string. </p> <p>Example : </p> <pre><code>string = "55544355" # The regex should retrieve sequences "555", "44", "3", "55" </code></pre> <p>Can I have a few tips?</p>
0
2016-07-20T16:16:06Z
38,485,895
<p>You can use <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow"><code>re.findall()</code></a> and the <code>((.)\2*)</code> regular expression:</p> <pre><code>&gt;&gt;&gt; [item[0] for item in re.findall(r"((.)\2*)", string)] ['555', '44', '3', '55'] </code></pre> <p>the key part is inside the outer capturing group - <code>(.)\2*</code>. Here we capture a single character via <code>(.)</code> then reference this character by the group number: <code>\2</code>. The group number is 2 because we have an outer capturing group with number 1. <code>*</code> means 0 or more times.</p> <p>You could've also solved it with a single capturing group and <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>re.finditer()</code></a>:</p> <pre><code>&gt;&gt;&gt; [item.group(0) for item in re.finditer(r"(.)\1*", string)] ['555', '44', '3', '55'] </code></pre>
3
2016-07-20T16:24:21Z
[ "python", "regex" ]
Python - Find sequence of same characters
38,485,735
<p>I'm trying to use regex to match sequences of one or more instances of the same characters in a string. </p> <p>Example : </p> <pre><code>string = "55544355" # The regex should retrieve sequences "555", "44", "3", "55" </code></pre> <p>Can I have a few tips?</p>
0
2016-07-20T16:16:06Z
38,486,393
<p>Probably not the best option here, but for the sake of variety, how about this logic:</p> <pre><code>&gt;&gt;&gt; def f(s): l = [] c = s[0] for x in s: if x in c: c += x continue l.append(c) c = x l.append(c) return l &gt;&gt;&gt; f('55544355') ['555', '44', '3', '55'] &gt;&gt;&gt; f('123444555678999001') ['1', '2', '3', '444', '555', '6', '7', '8', '999', '00', '1'] </code></pre>
0
2016-07-20T16:50:43Z
[ "python", "regex" ]
How to set the algorithm to barrier when use CPLEX in PuLP
38,485,745
<p>I use 'prob.solve(CPLEX())' to call CPLEX in PuLP.</p> <p>However, I am wondering how to use barrier algorithm here to get a more non-zero solution.</p> <p>Thanks.</p>
-1
2016-07-20T16:16:21Z
38,491,858
<p>I'm not a PuLP expert, but it looks like this is possible (however, I'm not sure how reliable it is). There is a <a href="https://groups.google.com/forum/#!topic/pulp-or-discuss/gx1KTAH2SAE" rel="nofollow">hint</a> here about how you can set CPLEX parameters using the CPLEX DLL shared library. I believe this is outdated, but here is the corresponding snippet from that thread:</p> <pre><code>&gt;&gt;&gt;&gt; solver = CPLEX_DLL() &gt;&gt;&gt;&gt; CplexDll.CPXsetintparam(solver.env, CPX_PARAM_MIPDISPLAY, 4) Good point I would prefer &gt;&gt;&gt; solver.CPXsetintparam(CPX_PARAM_MIPDISPLAY, 4) As this only requires Knowledge of CPLEX parameters and not Pulp internals </code></pre> <p>However, with a recent version of PuLP (version 1.6.1), it looks like the <code>CPLEX_DLL</code> class has the <code>setLpAlgorithm</code> method to make this more convenient. Here is an example, just to give you the gist:</p> <pre><code>&gt;&gt;&gt; from pulp import * &gt;&gt;&gt; cplex_dll_path '&lt;path_on_your_machine&gt;/libcplex1263.so' &gt;&gt;&gt; solver = CPLEX() &gt;&gt;&gt; solver.setLpAlgorithm(4) </code></pre> <p><code>&lt;path_on_your_machine&gt;/libcplex1263.so</code> must be configured in the <code>pulp.cfg.(linux|osx|win)</code> file (in the directory where the pulp module is installed). The magic number "4" in <code>solver.setLpAlgorithm(4)</code> corresponds to <code>CPX_ALG_BARRIER</code> (see <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/CPLEX/Parameters/topics/LPMETHOD.html" rel="nofollow">here</a>).</p> <p>With that said, if you want finer control over CPLEX, you might have better luck using the <a href="http://www.ibm.com/support/knowledgecenter/SSSA5P_12.6.3/ilog.odms.cplex.help/refpythoncplex/html/help.html?pos=2" rel="nofollow">CPLEX Python API</a> directly (although, it is a lower-level API than PuLP). Alternatively, check out the higher-level <a href="https://pypi.python.org/pypi/docplex" rel="nofollow">docplex</a> package which also allows you to solve on the cloud.</p>
0
2016-07-20T22:24:12Z
[ "python", "cplex", "pulp" ]
Create a secure unsubscribe link for emails sent with Flask
38,485,798
<p>I want to generate an unsubscribe link that a user can click when receiving an email to unsubscribe that address. I don't want to just include the email in the link because a user could edit the link to unsubscribe someone else. Most emails I see generate some sort of token and the site knows how to match the token to the user. How can I generate such a token with Flask?</p> <pre><code>for email in email_lst: body = 'unsubscribe link with token' msg.attach(MIMEText(body, 'html')) more code to send email </code></pre>
1
2016-07-20T16:19:41Z
38,486,112
<p>Flask includes the library <a href="https://pythonhosted.org/itsdangerous/" rel="nofollow">itsdangerous</a> which is used to generate tokens by securely signing serialized data.</p> <p>For each email, generate a token with the email to be unsubscribed, and create an <code>unsubscribe</code> route that accepts and decodes that token to determine who to unsubscribe.</p> <pre><code>from itsdangerous import URLSafeSerializer, BadData @app.route('/unsubscribe/&lt;token&gt;') def unsubscribe(token): s = URLSafeSerializer(app.secret_key, salt='unsubscribe') try: email = s.loads(token) except BadData: # show an error ... # unsubscribe ... def send_email(): s = URLSafeSerializer(app.secret_key, salt='unsubscribe') token = s.dumps(user.email) url = url_for('unsubscribe', token=token) # add the url to your message ... </code></pre> <p>Since the token is signed, a user can see the data but can't change it without invalidating the token.</p>
2
2016-07-20T16:36:21Z
[ "python", "email", "flask" ]
How convert output tensor to one-hot tensor?
38,485,905
<p>I need to calculate loss from the softmax output vs target. My target is like [0,0,1] and output is [0.3,0.3,0.4] For the purpose, prediction is correct. But a cost function of below type doesn't account for this kind of accuracy</p> <pre><code>self._output = output = tf.nn.softmax(y) self._cost = cost = tf.reduce_mean(tf.square( output - tf.reshape(self._targets, [-1]))) </code></pre> <p>How can I easily convert the output [0.3,0.3,0.4] to [0,0,1] in TF itself?</p>
0
2016-07-20T16:24:47Z
38,486,938
<p>The typical loss function used for comparing two probability distributions is called <a href="https://en.wikipedia.org/wiki/Cross_entropy" rel="nofollow">cross entropy</a>. TensorFlow has the <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#softmax_cross_entropy_with_logits" rel="nofollow">tf.nn.softmax_cross_entropy_with_logits</a> function which implements that loss. In your case, you can simply do :</p> <pre><code>self._cost = tf.nn.softmax_cross_entropy_with_logits( y, tf.reshape(self._targets, [-1])) </code></pre> <p>But if you really want to convert <code>[0.3, 0.3, 0.4]</code> to a one-hot representation for a different purpose, you can use the <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#one_hot" rel="nofollow"><code>tf.one_hot</code></a> function as follows :</p> <pre><code>sess = tf.InteractiveSession() a = tf.constant([0.3, 0.3, 0.4]) one_hot_a = tf.one_hot(tf.nn.top_k(a).indices, tf.shape(a)[0]) print(one_hot_a.eval()) # prints [[ 0. 0. 1.]] </code></pre>
1
2016-07-20T17:20:48Z
[ "python", "tensorflow" ]
Parsing XML from CZI image data
38,485,916
<p>I have the following XML file, where I want to extract the values for the key: <strong>Information|Image|S|Scene|Shape|Name</strong> using python, e.g. ElementTree.</p> <p>I already tried various things, but I always get stuck. Any help is really appreciated.</p> <p>Sebi</p> <p>Here is some code I tried out already:</p> <pre><code>from lxml import etree as etl import javabridge as jv import bioformats as bf def getinfo(root, ns, nodenames): NSMAP = {'mw': ns} namespace = u'{%s}' % ns nsl = len(namespace) if len(nodenames) &gt;= 1: search = './/mw:' + nodenames[0] if len(nodenames) &gt;= 2: search = search + '/mw:' + nodenames[1] if len(nodenames) &gt;= 3: search = search + '/mw:' + nodenames[2] out = root.findall(search, namespaces=NSMAP) dictlist = [] for i in range(0, len(out)): dict = {} for k in range(0, len(out[i].attrib)): dict[out[i].keys()[k]] = out[i].values()[k] print out[i].attrib dictlist.append(dict) return dictlist filename = r'c:\Users\M1SRH\Documents\Python_Projects_Testdata\CZI_XML_Test\B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi' bfpath = r'c:\Users\M1SRH\Documents\Software\BioFormats_Package\5.1.10\bioformats_package.jar' jars = jv.JARS + [bfpath] jv.start_vm(class_path=jars, max_heap_size='4G') omexml = bf.get_omexml_metadata(filename) new_omexml = omexml.encode('utf-8') result = getinfo(etl.fromstring(new_omexml), 'http://www.openmicroscopy.org/Schemas/SA/2015-01', ['StructuredAnnotations', 'XMLAnnotation']) print 'Done.' </code></pre> <p>And here is the XML dataset:</p> <pre><code>&lt;OME xmlns="http://www.openmicroscopy.org/Schemas/OME/2015-01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openmicroscopy.org/Schemas/OME/2015-01 http://www.openmicroscopy.org/Schemas/OME/2015-01/ome.xsd"&gt; &lt;Experimenter ID="Experimenter:0" UserName="M1SRH"/&gt; &lt;Instrument ID="Instrument:0"&gt; &lt;Microscope Type="Inverted"/&gt; &lt;Detector ID="Detector:Internal" Model="TestCam"/&gt; &lt;Objective ID="Objective:1" Immersion="Air" LensNA="0.35" Model="Plan-Apochromat 5x/0.35" NominalMagnification="5.0" WorkingDistance="5000.0" WorkingDistanceUnit="µm"/&gt; &lt;FilterSet ID="FilterSet:1"&gt; &lt;DichroicRef ID="Dichroic:1"/&gt; &lt;EmissionFilterRef ID="Filter:1"/&gt; &lt;EmissionFilterRef ID="Filter:2"/&gt; &lt;EmissionFilterRef ID="Filter:3"/&gt; &lt;/FilterSet&gt; &lt;Filter ID="Filter:1"&gt; &lt;TransmittanceRange CutIn="458.0" CutInUnit="nm" CutOut="474.0" CutOutUnit="nm"/&gt; &lt;/Filter&gt; &lt;Filter ID="Filter:2"&gt; &lt;TransmittanceRange CutIn="546.0" CutInUnit="nm" CutOut="564.0" CutOutUnit="nm"/&gt; &lt;/Filter&gt; &lt;Filter ID="Filter:3"&gt; &lt;TransmittanceRange CutIn="618.0" CutInUnit="nm" CutOut="756.0" CutOutUnit="nm"/&gt; &lt;/Filter&gt; &lt;Dichroic ID="Dichroic:1"/&gt; &lt;/Instrument&gt; &lt;Image ID="Image:0" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #1"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:0" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:0:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="0.46000003814697266" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="30533.145" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="5.456000089645386" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="30533.145" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;Image ID="Image:1" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #2"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:1" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:1:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="0.6510000228881836" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="32466.855" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="5.6519999504089355" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="32466.855" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;Image ID="Image:2" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #3"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:2" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:2:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="0.8610000610351562" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="30533.145" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="5.859999895095825" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="30533.145" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;Image ID="Image:3" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #4"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:3" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:3:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="1.0509998798370361" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="32466.855" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="6.055000066757202" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="32466.855" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;Image ID="Image:4" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #5"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:4" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:4:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="1.2590000629425049" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="39533.145" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="6.296999931335449" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="39533.145" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;Image ID="Image:5" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #6"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:5" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:5:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="1.4500000476837158" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="41466.855" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="6.490000009536743" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="41466.855" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;Image ID="Image:6" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #7"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:6" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:6:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="1.6640000343322754" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="39533.145" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="6.700000047683716" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="39533.145" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;Image ID="Image:7" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #8"&gt; &lt;AcquisitionDate&gt;2016-07-20T11:44:16.161&lt;/AcquisitionDate&gt; &lt;ExperimenterRef ID="Experimenter:0"/&gt; &lt;InstrumentRef ID="Instrument:0"/&gt; &lt;ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/&gt; &lt;Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:7" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"&gt; &lt;Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:7:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"&gt; &lt;DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/&gt; &lt;FilterSetRef ID="FilterSet:1"/&gt; &lt;LightPath/&gt; &lt;/Channel&gt; &lt;MetadataOnly/&gt; &lt;Plane DeltaT="1.8569998741149902" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="41466.855" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/&gt; &lt;Plane DeltaT="6.898000001907349" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="41466.855" PositionXUnit="reference frame" PositionY="18466.855" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/&gt; &lt;/Pixels&gt; &lt;/Image&gt; &lt;StructuredAnnotations xmlns="http://www.openmicroscopy.org/Schemas/SA/2015-01"&gt; &lt;XMLAnnotation ID="Annotation:0" Namespace="openmicroscopy.org/OriginalMetadata"&gt; &lt;Value&gt; &lt;OriginalMetadata&gt; &lt;Key&gt;Experiment|AcquisitionBlock|TimeSeriesSetup|RegionsSetup|SampleHolder|AllowedScanArea|ContourType&lt;/Key&gt; &lt;Value&gt;[Rectangle]&lt;/Value&gt; &lt;/OriginalMetadata&gt; &lt;/Value&gt; &lt;/XMLAnnotation&gt; &lt;XMLAnnotation ID="Annotation:2127" Namespace="openmicroscopy.org/OriginalMetadata"&gt; &lt;Value&gt; &lt;OriginalMetadata&gt; &lt;Key&gt;Information|Image|S|Scene|Shape|Name&lt;/Key&gt; &lt;Value&gt;[B4, B4, B4, B4, B5, B5, B5, B5]&lt;/Value&gt; &lt;/OriginalMetadata&gt; &lt;/Value&gt; &lt;/XMLAnnotation&gt; &lt;/StructuredAnnotations&gt; &lt;/OME&gt; </code></pre>
0
2016-07-20T16:25:33Z
38,498,939
<p>As an assumption maybe You did not use NameSpaces to find an Element. I tried to get keys and values from OriginalMetadata . </p> <pre><code>import xml.etree.ElementTree as ET tree = ET.fromstring(initial_string) # Define NameSpace name_space = "{http://www.openmicroscopy.org/Schemas/SA/2015-01}" origin_meta_datas = tree.findall(".//{}OriginalMetadata".format(name_space)) # Iterate in founded origins for origin in origin_meta_datas: key = origin.find("{}Key".format(name_space)).text if key == "Information|Image|S|Scene|Shape|Name": value = origin.find("{}Value".format(name_space)).text print("Value: {}".format(value)) </code></pre>
1
2016-07-21T08:28:27Z
[ "python", "xml" ]
Docker Mac Beta and container connecting to host ports?
38,485,943
<p>I currently use PyCharm (Actually IntelliJ) and have been using Kitematic with VirtualBox support.</p> <p>I have a container connecting to the host (which is a virtual machine) to do remote debugging.</p> <p>The issue is when I try to use Docker Mac Beta, the container doesn't seem to be able to access any specific ports on the host but it can ping the host. Which doesn't make any sense...</p> <p>Anyone have any ideas?</p> <p>Is there some magic sauce I need to make the python debugger listen on all IPs/Ports maybe? </p> <p>Edits:</p> <p>To clarify, when running a python script in this environment, the script has to initiate an outbound connect to a specified ip/port. </p> <p>Here's some console output to help understand:</p> <p>This is inside the container itself. I have the debugger running on port 15001 on my Mac.</p> <pre><code># /sbin/ip route|awk '/default/ { print $3 }' 172.17.0.1 # ping 172.17.0.1 PING 172.17.0.1 (172.17.0.1): 56 data bytes 64 bytes from 172.17.0.1: icmp_seq=0 ttl=64 time=0.078 ms 64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.066 ms ^C--- 172.17.0.1 ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.066/0.072/0.078/0.000 ms # telnet 172.17.0.1 15001 Trying 172.17.0.1... telnet: Unable to connect to remote host: Connection refused # </code></pre> <p>And then on the host (my mac):</p> <pre><code>➜ telnet localhost 15001 Trying ::1... telnet: connect to address ::1: Connection refused Trying fe80::1... telnet: connect to address fe80::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 501 1 0.1 UNIX </code></pre> <p>This all works fine with the old virtualbox based Docker setup, which makes sense since its using full fledge virtual machines. But not sure how the new Docker Beta works, especially when it comes to networking.</p> <p>I am using Docker-Compose for this, so I can set up the networking through the network configuration options but so far, I haven't gotten any random attempts to work.</p> <p>Also, the container is able to access anything else (google.com or whatever), just not a specific port on the host machine.</p>
0
2016-07-20T16:26:58Z
38,489,454
<p>I think the problem is that you need to expose port 15001.</p> <p>Try adding to Dockerfile</p> <p>EXPOSE 15001</p>
0
2016-07-20T19:40:59Z
[ "python", "osx", "intellij-idea", "docker", "docker-compose" ]
Docker Mac Beta and container connecting to host ports?
38,485,943
<p>I currently use PyCharm (Actually IntelliJ) and have been using Kitematic with VirtualBox support.</p> <p>I have a container connecting to the host (which is a virtual machine) to do remote debugging.</p> <p>The issue is when I try to use Docker Mac Beta, the container doesn't seem to be able to access any specific ports on the host but it can ping the host. Which doesn't make any sense...</p> <p>Anyone have any ideas?</p> <p>Is there some magic sauce I need to make the python debugger listen on all IPs/Ports maybe? </p> <p>Edits:</p> <p>To clarify, when running a python script in this environment, the script has to initiate an outbound connect to a specified ip/port. </p> <p>Here's some console output to help understand:</p> <p>This is inside the container itself. I have the debugger running on port 15001 on my Mac.</p> <pre><code># /sbin/ip route|awk '/default/ { print $3 }' 172.17.0.1 # ping 172.17.0.1 PING 172.17.0.1 (172.17.0.1): 56 data bytes 64 bytes from 172.17.0.1: icmp_seq=0 ttl=64 time=0.078 ms 64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.066 ms ^C--- 172.17.0.1 ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.066/0.072/0.078/0.000 ms # telnet 172.17.0.1 15001 Trying 172.17.0.1... telnet: Unable to connect to remote host: Connection refused # </code></pre> <p>And then on the host (my mac):</p> <pre><code>➜ telnet localhost 15001 Trying ::1... telnet: connect to address ::1: Connection refused Trying fe80::1... telnet: connect to address fe80::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 501 1 0.1 UNIX </code></pre> <p>This all works fine with the old virtualbox based Docker setup, which makes sense since its using full fledge virtual machines. But not sure how the new Docker Beta works, especially when it comes to networking.</p> <p>I am using Docker-Compose for this, so I can set up the networking through the network configuration options but so far, I haven't gotten any random attempts to work.</p> <p>Also, the container is able to access anything else (google.com or whatever), just not a specific port on the host machine.</p>
0
2016-07-20T16:26:58Z
38,890,044
<p>Create a host-based loopback device and then use a remote_host alternative (like in xdebug) to configure your container to connect back to that host ( on the port ), this will solve your issue as it does for PHP ( same issue ). We had the same case when switching from dockertoolbox to docker for mac. See a configuration example including the launchdaemon to create the host loopback interface here: <a href="https://gist.github.com/EugenMayer/3019516e5a3b3a01b6eac88190327e7c" rel="nofollow">https://gist.github.com/EugenMayer/3019516e5a3b3a01b6eac88190327e7c</a></p>
0
2016-08-11T07:32:22Z
[ "python", "osx", "intellij-idea", "docker", "docker-compose" ]
Interactive Slider using Bokeh
38,486,119
<p>I'm trying to use a bokeh interactive slider to modify the contents of a plot, similar the example <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#customjs-for-widgets" rel="nofollow" title="Bokeh Docs">here</a>. I have a two nested lists <code>x</code> and <code>y</code>.</p> <p>I simply want the slider to change the index of the lists to plot. i.e. If the slider index = 0, then plot <code>x[0]</code> vs <code>y[0]</code>, if the slider index is 1, plot <code>x[1]</code> vs <code>y[1]</code>, etc...</p> <p>The documentation example computes the new data on the fly, which is not feasible for the data that I need to work with. </p> <p>When I run the code below, nothing shows up in the plot... I don't know javascript, so I'm guessing this is where I'm going wrong.</p> <p>I'm running Python 3.5 and Bokeh 0.12. This is all run within a jupyter-notebook.</p> <pre><code>import numpy as np from bokeh.layouts import row from bokeh.models import CustomJS, ColumnDataSource, Slider from bokeh.plotting import Figure, show from bokeh.io import output_notebook from bokeh.resources import INLINE output_notebook(INLINE) x = [[x*0.05 for x in range(0, 500)], [x*0.05 for x in range(0, 500)]] y = [np.sin(x[0]), np.cos(x[1])] source = ColumnDataSource(data=dict(x=x, y=y)) plot = Figure(plot_width=400, plot_height=400) plot.line('x'[0], 'y'[0], source=source, line_width=3, line_alpha=0.6) callback = CustomJS(args=dict(source=source), code=""" var data = source.get('data'); var f = cb_obj.get('value'); x = data['x'][f]; y = data['y'][f]; source.trigger('change'); """) slider = Slider(start=0, end=1, value=0, step=1, title="index", callback=callback) layout = row(plot, slider) show(layout) </code></pre>
0
2016-07-20T16:36:46Z
39,150,823
<p>Instead of having a slider changing the index of the data to be plotted, you could define two <code>ColumnDataSource</code>s: <strong><em><code>source_visible</code></em></strong> and <strong><em><code>source_available</code></em></strong> where the first one holds the data that is currently being shown in the plot and the second one acts as a data repository from where we can sample data in <code>CustomJS</code> callback based on user selection on the web page: </p> <pre class="lang-py prettyprint-override"><code>import numpy as np from bokeh.layouts import row from bokeh.models import ColumnDataSource, Slider, CustomJS from bokeh.plotting import Figure, show # Define data x = [x*0.05 for x in range(0, 500)] trigonometric_functions = { '0': np.sin(x), '1': np.cos(x), '2': np.tan(x), '3': np.arcsin(x), '4': np.arccos(x), '5': np.arctan(x)} initial_function = '0' # Wrap the data in two ColumnDataSources source_visible = ColumnDataSource(data=dict( x=x, y=trigonometric_functions[initial_function])) source_available = ColumnDataSource(data=trigonometric_functions) # Define plot elements plot = Figure(plot_width=400, plot_height=400) plot.line('x', 'y', source=source_visible, line_width=3, line_alpha=0.6) slider = Slider(title='Trigonometric function', value=int(initial_function), start=np.min([int(i) for i in trigonometric_functions.keys()]), end=np.max([int(i) for i in trigonometric_functions.keys()]), step=1) # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible=source_visible, source_available=source_available), code=""" var selected_function = cb_obj.get('value'); // Get the data from the data sources var data_visible = source_visible.get('data'); var data_available = source_available.get('data'); // Change y-axis data according to the selected value data_visible.y = data_available[selected_function]; // Update the plot source_visible.trigger('change'); """) layout = row(plot, slider) show(layout) </code></pre> <p>Keep in mind that if your data is large, it might take a while to send it all at once to the client's browser.</p>
0
2016-08-25T16:53:56Z
[ "javascript", "python", "jupyter-notebook", "bokeh" ]
Dict List Continues to Overwrite - What am I doing wrong?
38,486,144
<p>I haven't had this problem before and have been trying to troubleshoot it for a while now but can't seem to figure out the issue (tried a variety of things including creating copies, deep copies, and appending to DataFrame).</p> <p>Basically, I'm trying to loop through a list, create a dictionary and append that dictionary to a different list. The dictionary creation is unique each time, but it overwrites all of the previous ones AND adds it.</p> <p>And sorry in advance if there is an obvious answer - still pretty new at this.</p> <p>See below for code:</p> <pre><code>bigram_values_dict_list = [] bigram_values_dict = {} counter = 0 for bigram in bigram_string_list: bigram_values_dict['bigram'] = bigram bigram_values_dict['impressions'] = get_total_impressions(bigram) print(bigram_values_dict) counter += 1 if counter % 10 == 0: print(bigram_values_dict_list) bigram_values_dict_list.append(bigram_values_dict) </code></pre> <p>And output:</p> <pre><code>{'bigram': 'mobile site', 'impressions': 10344864} {'bigram': 'learn more!', 'impressions': 4167059} {'bigram': 'lawn &amp;', 'impressions': 742291} {'bigram': '&amp; garden', 'impressions': 980153} [{'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}, {'bigram': '&amp; garden', 'impressions': 2123500}] </code></pre> <p>I don't think I ever had this problem with Python 2. Maybe I'm missing something?</p> <p>Thanks in advance for any help / insight!!</p>
1
2016-07-20T16:37:59Z
38,486,173
<p>Change:</p> <pre><code>bigram_values_dict_list.append(bigram_values_dict) </code></pre> <p>to:</p> <pre><code>bigram_values_dict_list.append(bigram_values_dict.copy()) </code></pre> <p>In that way, you are <em>appending</em> a copy of your dictionary to the list, so future modifications of the dictionary will not affect already appended dictionaries.</p> <p>Another alternative will be to <em>(re-)define</em> the dictionary at every iteration of the <code>for</code> loop.</p>
2
2016-07-20T16:39:21Z
[ "python", "python-3.x", "pandas", "dictionary", "data-analysis" ]
PyAutoGui click permissions error
38,486,151
<p>I have a very strange problem that I haven't seen happen in python before. </p> <p>I have a script that works flawlessly on one pc and when I try to use it on another my defined function fails. </p> <p>I'm using PyAutoGUI to automate some processes. </p> <pre><code>import csv import pyautogui pyautogui.PAUSE = 0.50 pyautogui.FAILSAFE = True #click function requires arguments ('fullPathToImage', "Error Identifier") def click(fullPathToImage, error): try: pyautogui.click(pyautogui.center(pyautogui.locateOnScreen(fullPathToImage))) except: print(error, " not found, trying again") click(fullPathToImage, error) def start(): click('C:/projects/images/test.png', "test.png") pyautogui.typewrite("This is my test text") if __name__ == '__main__': start() </code></pre> <p>What is happening on this other machine is when it locates the image, it moves the mouse and clicks as expected in the try statement but then it immediately executes the except statement too. </p> <p>The only difference between our two machines is I'm running pillow 3.1.1 and the one it doesn't work on is running pillow 3.3.0. </p> <p>My instinct is something changed that isn't returning a success flag on click which is triggering the exception. I don't know why that would be the case since all pillow is used for is image recognition. </p> <p>Admittedly I'm pretty new to error catching and I'm not sure where to continue from here. Any help would be greatly appreciated. </p> <p>edit: the reason for calling the click function in the exception is to eliminate wait statements during loading screens. depending no the amount of data being processed it's difficult to preprogram delays.</p>
0
2016-07-20T16:38:09Z
38,574,348
<p>So it turns out this was due to a permissions error on this machine. Due to it being a business computer the user didn't have admin rights. This caused clicks to be registered and then immediately triggered a WinError 5 exception. I solved this by adding another exception to my try block. "except PermissionError: pass" See below for implementation</p> <pre><code>import csv import pyautogui pyautogui.PAUSE = 0.50 pyautogui.FAILSAFE = True #click function requires arguments ('fullPathToImage', "Error Identifier") def click(fullPathToImage, error): try: pyautogui.click(pyautogui.center(pyautogui.locateOnScreen(fullPathToImage))) ################################## except PermissionError: pass ################################## except: print(error, " not found, trying again") click(fullPathToImage, error) def start(): click('C:/projects/images/test.png', "test.png") pyautogui.typewrite("This is my test text") if __name__ == '__main__': start() </code></pre>
0
2016-07-25T17:49:19Z
[ "python", "windows", "pyautogui" ]
Sum datetime differences based on column value
38,486,170
<p>I have a dataframe that looks like:</p> <pre><code> field1 field2 field3 time t1 1 1 1 t2 1 1 0 t3 2 3 1 t4 3 3 0 t5 1 2 0 </code></pre> <p>Times are in the form <code>yyyy-mm-dd hh:mm:ss</code>, and are currently indexing the dataframe. </p> <p><code>field 1</code> and <code>field 2</code> are used to identify items, such that the tuple <code>(field1,field2)</code> corresponds to a specific sensor somewhere in the world. <code>field 3</code> is the value of that sensor at the given time, and takes either the value 0 or 1.</p> <p>I'd like the group the dataframe by (field1, field2) and sum the total time that each sensor takes each value from field 3. So, if <code>t1='2016-07-20 00:00:00'</code> and <code>t2='2016-07-20 00:01:00'</code>, and the current time is <code>'2016-07-20 00:03:00'</code>, I would have a new dataframe that looks like:</p> <pre><code> field3=0 field3=1 (1,1) 2 min 1 min (2,3) ... ... (3,3) ... ... (1,2) ... ... </code></pre> <p>I assume that from <code>t1</code> to <code>t2</code>, <code>field3</code>'s value is 1, and from <code>t2</code> onwards it is 0 because (1,1) doesn't appear again in the dataframe. The <code>1 min</code> is from <code>t2 - t1</code> and the <code>2 min</code> is from <code>current_time - t2</code></p> <p>The <code>2 min</code> and <code>1 min</code> can be any format (be it total minutes/seconds, a timedelta, or whatever)</p> <p>I've tried the following:</p> <pre><code>import pandas as pd from collections import defaultdict, namedtuple # so i can create a defaultdict(Field3) and save some logic class Field3(object): def __init__(self): self.zero= pd.Timedelta('0 days') self.one = pd.Timedelta('0 days') # used to map to field3 in a dictionary Sensor = namedtuple('Sensor','field1 field2') # the dataframe mentioned above df = pd.DataFrame(...) # iterate through each row of the dataframe and map from (field1,field2) to # field3, adding time based on the value of field3 in the frame and the # time difference between this row and the next rows = list(df.iterrows()) sensor_to_field3 = defaultdict(Field3) for i in xrange(len(rows)-1): sensor = Sensor(field1=rows[i][1][0],field2=rows[i][1][1]) if rows[i][1][2]: sensor_to_field3[spot].one += rows[i+1][0]-rows[i][0] else: spot_to_status[spot].zero += rows[i+1][0]-rows[i][0] spot_to_status = {k:[v] for k,v in sensor_to_field3.iteritems()} result = pd.DataFrame(sensor_to_field3,index=[0]) </code></pre> <p>It gets me basically but I want (though it currently only works when there's a single sensor represented in the entire table, which I don't really want to have to deal with if there's a better way of solving this). </p> <p>I feel like there has to be a better way of going about this. Something like do a groupby on <code>field1,field2</code>, then aggregate timedeltas based on <code>field3</code> and the <code>time</code> index, but I'm not sure how to go about doing that.</p>
1
2016-07-20T16:39:13Z
38,534,266
<p>Managed to get it, in case anyone else runs into something remotely similar. Still not sure if it's optimal, but it feels better than what I was doing.</p> <p>I changed the original dataframe to include the time as a column, and just use integer indices.</p> <pre><code>def create_time_deltas(dataframe): # add a timedelta column dataframe['timedelta'] = pd.Timedelta(minutes=0) # iterate over each row and set the timedelta to the difference of the next one and this one for i in dataframe.index[:-1]: dataframe.set_value(i,'timedelta',dataframe.loc[i+1,'time']dataframe.loc[i,'time']) # set the last time value, which couldn't be set earlier because index out of bounds dataframe.set_value(i+1,'timedelta',pd.to_datetime(datetime.now())-dataframe.loc[i,'time']) return dataframe def group_by_field3_time(dataframe, start=None, stop=None): # optionally set time bounds on what to care about stop = stop or pd.to_datetime(datetime.now()) recent = dataframe.loc[logical_and(start &lt; df['time'] , df['time'] &lt; stop)] # groupby and apply to create a new dataframe with the time_deltas column by_td = df.groupby(['field1','field2']).apply(create_time_deltas) # sum the timedeltas for each triple, which can be used later by_oc = by_td.groupby(['field1','field2','field3']).sum() return by_oc </code></pre> <p>If anyone can think of a better way to do this I'm all ears, but this does feel a lot better than creating dictionaries all over the place.</p>
0
2016-07-22T19:49:19Z
[ "python", "pandas" ]
How do I send an email from python using outlook web access?
38,486,372
<p>I need to send an email in python if my job fails, however due to company polices, I am only allowed to use the Outlook Web Access. How can I connect to Outlook Web Access from python to send an email?</p>
0
2016-07-20T16:49:44Z
38,486,473
<p>I can't take credit for this but I can lead you to a possible solution.</p> <p>Here's the link: <a href="http://win32com.goermezer.de/content/view/227/192/" rel="nofollow">http://win32com.goermezer.de/content/view/227/192/</a> Here's the code</p> <pre><code>import win32com.client s = win32com.client.Dispatch("Mapi.Session") o = win32com.client.Dispatch("Outlook.Application") s.Logon("Outlook2003") Msg = o.CreateItem(0) Msg.To = "recipient@domain.com" Msg.CC = "more email addresses here" Msg.BCC = "more email addresses here" Msg.Subject = "The subject of you mail" Msg.Body = "The main body text of you mail" attachment1 = "Path to attachment no. 1" attachment2 = "Path to attachment no. 2" Msg.Attachments.Add(attachment1) Msg.Attachments.Add(attachment2) Msg.Send() </code></pre> <p>This is cool and I have to use it. A related SO question can be found here: <a href="http://stackoverflow.com/questions/24650518/python-send-html-formatted-email-via-outlook-2007-2010-and-win32com?rq=1">Python - Send HTML-formatted email via Outlook 2007/2010 and win32com</a></p>
0
2016-07-20T16:55:20Z
[ "python", "email", "outlook", "outlook-web-app" ]
First Business Date of Month Python
38,486,427
<p>How do I determine the first business date of the month in python? the program I am writing is drip fed dates each loop and I need to be able to get a true/false.</p> <p>I found that you can get last working business day with:</p> <pre><code>import pandas as pd pd.date_range("2014-01-14", periods=1, freq='BM') </code></pre> <p>Thanks</p>
-1
2016-07-20T16:52:51Z
38,486,598
<p>This uses the U.S. Federal Holiday calendar. It uses a list comprehension to go through every first weekday of the month between the <code>start_date</code> and <code>end_date</code>, and then increments the day if it falls on a U.S. Federal Holiday or on a weekend until a valid business date is found.</p> <pre><code>import datetime as dt import pandas as pd from pandas.tseries.holiday import USFederalHolidayCalendar cal = USFederalHolidayCalendar() start_date = '2015-1-1' end_date = '2015-12-31' def get_business_day(date): while date.isoweekday() &gt; 5 or date in cal.holidays(): date += dt.timedelta(days=1) return date &gt;&gt;&gt; first_bday_of_month = [get_business_day(d).date() for d in pd.date_range(start_date, end_date, freq='BMS')] [datetime.date(2015, 1, 2), datetime.date(2015, 2, 2), datetime.date(2015, 3, 2), datetime.date(2015, 4, 1), datetime.date(2015, 5, 1), datetime.date(2015, 6, 1), datetime.date(2015, 7, 1), datetime.date(2015, 8, 3), datetime.date(2015, 9, 1), datetime.date(2015, 10, 1), datetime.date(2015, 11, 2), datetime.date(2015, 12, 1)] &gt;&gt;&gt; cal.rules cal.rules [Holiday: New Years Day (month=1, day=1, observance=&lt;function nearest_workday at 0x10c593578&gt;), Holiday: Dr. Martin Luther King Jr. (month=1, day=1, offset=&lt;DateOffset: kwds={'weekday': MO(+3)}&gt;), Holiday: Presidents Day (month=2, day=1, offset=&lt;DateOffset: kwds={'weekday': MO(+3)}&gt;), Holiday: MemorialDay (month=5, day=31, offset=&lt;DateOffset: kwds={'weekday': MO(-1)}&gt;), Holiday: July 4th (month=7, day=4, observance=&lt;function nearest_workday at 0x10c593578&gt;), Holiday: Labor Day (month=9, day=1, offset=&lt;DateOffset: kwds={'weekday': MO(+1)}&gt;), Holiday: Columbus Day (month=10, day=1, offset=&lt;DateOffset: kwds={'weekday': MO(+2)}&gt;), Holiday: Veterans Day (month=11, day=11, observance=&lt;function nearest_workday at 0x10c593578&gt;), Holiday: Thanksgiving (month=11, day=1, offset=&lt;DateOffset: kwds={'weekday': TH(+4)}&gt;), Holiday: Christmas (month=12, day=25, observance=&lt;function nearest_workday at 0x10c593578&gt;)] </code></pre>
2
2016-07-20T17:02:24Z
[ "python", "date" ]
First Business Date of Month Python
38,486,427
<p>How do I determine the first business date of the month in python? the program I am writing is drip fed dates each loop and I need to be able to get a true/false.</p> <p>I found that you can get last working business day with:</p> <pre><code>import pandas as pd pd.date_range("2014-01-14", periods=1, freq='BM') </code></pre> <p>Thanks</p>
-1
2016-07-20T16:52:51Z
38,486,737
<p>I think by this you can get first buisness date of the month using <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases" rel="nofollow"><code>BMS</code></a>:</p> <pre><code>In[82]:pd.date_range('1/1/2000', '12/1/2000', freq='BMS') Out[82]: DatetimeIndex(['2000-01-03', '2000-02-01', '2000-03-01', '2000-04-03', '2000-05-01', '2000-06-01', '2000-07-03', '2000-08-01', '2000-09-01', '2000-10-02', '2000-11-01', '2000-12-01'], dtype='datetime64[ns]', freq='BMS', tz=None) </code></pre>
2
2016-07-20T17:10:14Z
[ "python", "date" ]
Get HTML table into pandas Dataframe, not list of dataframe objects
38,486,477
<p>I apologize if this question has been answered elsewhere but I have been unsuccessful in finding a satisfactory answer here or elsewhere.</p> <p>I am somewhat new to python and pandas and having some difficulty getting HTML data into a pandas dataframe. In the pandas documentation it says .read_html() returns a list of dataframe objects, so when I try to do some data manipulation to get rid of the some samples I get an error.</p> <p>Here is my code to read the HTML:</p> <pre><code>df = pd.read_html('http://espn.go.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2', header = 1) </code></pre> <p>Then I try to clean it up:</p> <pre><code>df = df.dropna(axis=0, thresh=4) </code></pre> <p>And I received the following error:</p> <pre><code>Traceback (most recent call last): File "module4.py", line 25, in &lt;module&gt; df = df.dropna(axis=0, thresh=4) AttributeError: 'list' object has no attribute 'dropna' </code></pre> <p>How do I get this data into an actual dataframe, similar to what .read_csv() does?</p>
0
2016-07-20T16:55:31Z
38,486,953
<p>From <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/io.html#io-read-html" rel="nofollow">http://pandas.pydata.org/pandas-docs/version/0.17.1/io.html#io-read-html</a>, "read_html returns a list of DataFrame objects, even if there is only a single table contained in the HTML content".</p> <p>So <code>df = df[0].dropna(axis=0, thresh=4)</code> should do what you want.</p>
0
2016-07-20T17:21:55Z
[ "python", "pandas", "dataframe", "html-parsing" ]
WTForm "OR" conditional validator? (Either email or phone)
38,486,527
<pre><code>class ContactForm(Form): name = StringField('Name', validators=[DataRequired(), Length(max=255)]) email = StringField('Email', validators=[Optional(), Email(), Length(max=255)]) phone = StringField('Phone number', validators=[Optional(), NumberRange(min=8, max=14)]) comment = TextAreaField(u'Comment', validators=[DataRequired()]) </code></pre> <p>Is there anyway to specify a validator such that either <code>email</code> or <code>phone</code> is required? </p>
0
2016-07-20T16:58:31Z
38,486,740
<p>You can create a <code>validate</code> method on the form and do some manual checking. Something like this might get you started.</p> <pre><code>class MyForm(Form): name = StringField('Name', validators=[DataRequired(), Length(max=255)]) email = StringField('Email', validators=[Optional(), Email(), Length(max=255)]) phone = StringField('Phone number', validators=[Optional(), NumberRange(min=8, max=14)]) comment = TextAreaField(u'Comment', validators=[DataRequired()]) def validate(self): valid = True if not Form.validate(self): valid = False if not self.email and not self.phone: self.email.errors.append("Email or phone required") valid = False else: return valid </code></pre>
0
2016-07-20T17:10:17Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
Interpolating a straight line on a log-log graph (NumPy)
38,486,528
<p>I’m using a program on a Raspberry Pi that measures the voltage across a probe within salt water to calculate the salinity of the water. The relationship is not linear but becomes a fairly straight line when a power trend line is plotted on a log-log plot. This means that the probes could be calibrated using only two values and simply interpolating a straight line between them when plotted on a log-log graph.</p> <p><img src="http://i.stack.imgur.com/KGoZj.png" alt="Salinity graphs"></p> <p>Unfortunately, the pre-existing program assumed a linear relationship using standard axes and I’m not sure how to change it to interpolate for a straight line on a log-log plot. Any help would be appreciated, please note that this is the first bit of coding I’ve done so my knowledge isn’t great. I've included bits of the code that involve the interpolation below:</p> <pre><code>import smbus import time # imports for plotting import numpy as np import matplotlib.pyplot as plt import scipy.interpolate # do the first plot - all values zero nprobe=4 x=np.array([10.0, 30.0, 10.0, 30.0]) y=np.array([10.0, 10.0, 20.0, 20.0]) z=np.array([0., 0., 0., 0.]) # changing probe 1 to my handmade probe 1 fresh=np.array([0.,0.,0.,0.]) sea =np.array([100.0,100.0,100.0,100.0]) range=np.array([100.0,100.0,100.0,100.0]) range=1.0*(sea-fresh) # grid for plots - 20 is a bit coarse - was 100 give explicit (0,1) limits as no bcs here ########### xi, yi = np.linspace(x.min(), x.max(), 50), np.linspace(y.min(), y.max(), 50) xi, yi = np.linspace(0, 1, 50), np.linspace(0, 1, 50) xi, yi = np.meshgrid(xi, yi) rbf= scipy.interpolate.Rbf(x,y, z, function='linear') zi= rbf(xi, yi) plt.ion() tank=plt.imshow(zi, vmin=0, vmax=50, origin='lower', extent=[0, 44, 0, 30]) plt.scatter(x, y, c=z) plt.colorbar() plt.draw() </code></pre> <p>Also, later on in the program:</p> <pre><code># make r1 an array, results between 0-100 where 0 is 0% salinity and 100 is 2.5% salinity z=100.0*(r1-fresh)/range print time.strftime("%a, %d %b %Y, %H:%M:%S") print "measured reading at above time (r1)" print r1[0],r1[1],r1[2],r1[3] print "fresh values used for calibration" print fresh print "range between calibration values" print range print "percentage seawater (z)" print z # interpolate rbf= scipy.interpolate.Rbf(x,y, z, function='linear') zi= rbf(xi, yi) # alt interpolate ######### zi=scipy.interpolate.griddata((x,y), z, (xi,yi), method='linear') print "zi" print zi </code></pre>
2
2016-07-20T16:58:31Z
38,493,425
<p>How about </p> <pre><code>import numpy as np import scipy import scipy.interpolate import matplotlib.pyplot as plt def log_interp1d(x, y, kind='linear'): """ Returns interpolator function """ log_x = np.log10(x) log_y = np.log10(y) lin_int = scipy.interpolate.interp1d(log_x, log_y, kind=kind) log_int = lambda z: np.power(10.0, lin_int(np.log10(z))) return log_int powerlaw = lambda x, amp, index: amp * (x**index) num_points = 20 # original data xx = np.linspace(1.1, 10.1, num_points) yy = powerlaw(xx, 10.0, -2.0) # get interpolator interpolator = log_interp1d(xx, yy) # interpolate at points zz = np.linspace(1.2, 8.9, num_points-1) # interpolated points fz = interpolator(zz) plt.plot(xx, yy, 'o', zz, fz, '+') plt.show() </code></pre>
0
2016-07-21T01:30:36Z
[ "python", "numpy", "interpolation", "loglog" ]
How to natively increment a dictionary element's value?
38,486,601
<p>When working with Python 3 dictionaries, I keep having to do something like this:</p> <pre><code>d=dict() if 'k' in d: d['k']+=1 else: d['k']=0 </code></pre> <p>I seem to remember there being a native way to do this, but was looking through the documentation and couldn't find it. Do you know what this is?</p>
5
2016-07-20T17:02:31Z
38,486,696
<p>This is the use case for <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict"><code>collections.defaultdict</code></a>, here simply using the <code>int</code> callable for the default factory. </p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(int) &gt;&gt;&gt; d defaultdict(&lt;class 'int'&gt;, {}) &gt;&gt;&gt; d['k'] +=1 &gt;&gt;&gt; d defaultdict(&lt;class 'int'&gt;, {'k': 1}) </code></pre> <p>A <code>defaultdict</code> is configured to create items whenever a missing key is searched. You provide it with a callable (here <code>int()</code>) which it uses to produce a default value whenever the lookup with <code>__getitem__</code> is passed a key that does not exist. This callable is stored in an instance attribute called <code>default_factory</code>. </p> <p>If you don't provide a <code>default_factory</code>, you'll get a <code>KeyError</code> as per usual for missing keys. </p> <p>Then suppose you wanted a different default value, perhaps 1 instead of 0. You would simply have to pass a callable that provides your desired starting value, in this case very trivially </p> <pre><code>&gt;&gt;&gt; d = defaultdict(lambda: 1) </code></pre> <p>This could obviously also be any regular named function. </p> <hr> <p>It's worth noting however that if in your case you are attempting to just use a dictionary to store the count of particular values, a <a href="https://docs.python.org/3/library/collections.html#collections.Counter"><code>collections.Counter</code></a> is more suitable for the job. </p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter('kangaroo') Counter({'a': 2, 'o': 2, 'n': 1, 'r': 1, 'k': 1, 'g': 1}) </code></pre>
11
2016-07-20T17:07:32Z
[ "python", "python-3.x", "dictionary" ]
How to natively increment a dictionary element's value?
38,486,601
<p>When working with Python 3 dictionaries, I keep having to do something like this:</p> <pre><code>d=dict() if 'k' in d: d['k']+=1 else: d['k']=0 </code></pre> <p>I seem to remember there being a native way to do this, but was looking through the documentation and couldn't find it. Do you know what this is?</p>
5
2016-07-20T17:02:31Z
38,490,783
<p>Take note that you can always remove the clutter from the <code>if</code> stamemt by using it in an expression:</p> <pre><code>d['k'] = d['k'] + 1 if 'k' in d else 0 </code></pre>
0
2016-07-20T21:01:31Z
[ "python", "python-3.x", "dictionary" ]
TypeError: func1() missing 1 required positional argument: 'self'
38,486,718
<p>Im pretty new to python and one of the harder things I'm having to learn is how to properly use self. My understanding is in the methods we should use self. However I have the following class with a method and Im getting a type error saying saying I'm missing the positional argument self.</p> <pre><code>class example(): list1 = ['a','b','c','d'] list2 = ['1','2','3','4'] def func1(self, list1, list2): i = 1 for item in list1: print(list1) print(list2[i]) i +=1 func1(list1=list1, list2=list2) #error seen below &lt;ipython-input-2-d17d317756a0&gt; in &lt;module&gt;() ----&gt; 1 class example(): 2 3 list1 = ['a','b','c','d'] 4 list2 = ['1','2','3','4'] 5 &lt;ipython-input-2-d17d317756a0&gt; in example() 11 print(list2[i]) 12 ---&gt; 13 func1(list1=list1, list2=list2) TypeError: func1() missing 1 required positional argument: 'self' </code></pre>
2
2016-07-20T17:08:47Z
38,486,772
<p>The function you defined as <code>func1</code> is a <a href="https://docs.python.org/3/tutorial/classes.html#method-objects" rel="nofollow">method</a>. Which needs to be used on an instance of that class. Such as,</p> <pre><code>abc = example() # We create the instance abc.func1() # This is how you call a method. </code></pre> <p><code>self</code> represents <code>abc</code> here.</p> <p>If you are going to call it in the class, you need to use self itself, which will replace with the instance name if called outside.</p> <pre><code>Class example(): def func1(self): #stuff def func2(self): self.func1() # This is the usage. </code></pre> <p><strong>Edit:</strong> In this case, you can use static methods.</p> <pre><code>class example(): def func1(): pass func1() </code></pre> <p>However you should realize that this is not much better than just creating a global function. So I suggest you to found a way of using the first ways I recommended.</p>
1
2016-07-20T17:11:58Z
[ "python", "python-3.x" ]
TypeError: func1() missing 1 required positional argument: 'self'
38,486,718
<p>Im pretty new to python and one of the harder things I'm having to learn is how to properly use self. My understanding is in the methods we should use self. However I have the following class with a method and Im getting a type error saying saying I'm missing the positional argument self.</p> <pre><code>class example(): list1 = ['a','b','c','d'] list2 = ['1','2','3','4'] def func1(self, list1, list2): i = 1 for item in list1: print(list1) print(list2[i]) i +=1 func1(list1=list1, list2=list2) #error seen below &lt;ipython-input-2-d17d317756a0&gt; in &lt;module&gt;() ----&gt; 1 class example(): 2 3 list1 = ['a','b','c','d'] 4 list2 = ['1','2','3','4'] 5 &lt;ipython-input-2-d17d317756a0&gt; in example() 11 print(list2[i]) 12 ---&gt; 13 func1(list1=list1, list2=list2) TypeError: func1() missing 1 required positional argument: 'self' </code></pre>
2
2016-07-20T17:08:47Z
38,486,773
<p>I'm not expert in python but please try below it may help you,</p> <pre><code>class example(): list1 = ['a','b','c','d'] list2 = ['1','2','3','4'] def func1(list1, list2): i = 1 for item in list1: print(list1) print(list2[i]) i +=1 func1(list1=list1, list2=list2) </code></pre>
-1
2016-07-20T17:11:58Z
[ "python", "python-3.x" ]
TypeError: func1() missing 1 required positional argument: 'self'
38,486,718
<p>Im pretty new to python and one of the harder things I'm having to learn is how to properly use self. My understanding is in the methods we should use self. However I have the following class with a method and Im getting a type error saying saying I'm missing the positional argument self.</p> <pre><code>class example(): list1 = ['a','b','c','d'] list2 = ['1','2','3','4'] def func1(self, list1, list2): i = 1 for item in list1: print(list1) print(list2[i]) i +=1 func1(list1=list1, list2=list2) #error seen below &lt;ipython-input-2-d17d317756a0&gt; in &lt;module&gt;() ----&gt; 1 class example(): 2 3 list1 = ['a','b','c','d'] 4 list2 = ['1','2','3','4'] 5 &lt;ipython-input-2-d17d317756a0&gt; in example() 11 print(list2[i]) 12 ---&gt; 13 func1(list1=list1, list2=list2) TypeError: func1() missing 1 required positional argument: 'self' </code></pre>
2
2016-07-20T17:08:47Z
38,486,891
<p>If you're trying to call <code>func1</code> outside of the class:</p> <pre><code>class Example(): def func1(self, list1, list2): i = 0 for item in list1: print(item) print(list2[i]) i +=1 list1 = ['a','b','c','d'] list2 = ['1','2','3','4'] a = Example() a.func1(list1,list2) </code></pre> <p>If you're trying to have the functionality of <code>func1</code> within the class:</p> <pre><code>class Example(): list1 = ['a','b','c','d'] list2 = ['1','2','3','4'] def func1(self): i = 0 for item in self.list1: print(item) print(self.list2[i]) i +=1 a = Example() a.func1() </code></pre> <p>An alternatively if your lists are the same length, your func could be:</p> <pre><code>def func1(self, list1, list2): for i in range(len(list1)): print(list1[i]) print(list2[i]) </code></pre>
0
2016-07-20T17:17:40Z
[ "python", "python-3.x" ]
the correct way to input images for testing the tensorflow model
38,486,763
<p>I have been trying to test the fcn implementation <a href="https://github.com/MarvinTeichmann/tensorflow-fcn/blob/master/test_fcn32_vgg.py" rel="nofollow">posted here</a>. The only thing I changed is the way for setting up the input images for test against the model. My modification is marked with red curve in the following figure. </p> <p><a href="http://i.stack.imgur.com/RoEqR.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/RoEqR.jpg" alt="enter image description here"></a></p> <p>However, running the program caused the following error message <code>TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, or numpy ndarrays. </code>, happened at <code>down, up = sess.run(tensors, feed_dict=feed_dict)</code>. I am curious to know what are something wrong in my implementation, and how to modify it. In the original post, the author uses <code>img1 = skimage.io.imread("./test_data/tabby_cat.png") </code> to input the image.</p> <p>If I change <code>batch_images=tf.expand_dims(images,0)</code> to <code>batch_images=tf.expand_dims(img1,0)</code> the program will output the following error messages.</p> <p><a href="http://i.stack.imgur.com/RdikU.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/RdikU.jpg" alt="enter image description here"></a></p>
1
2016-07-20T17:11:33Z
38,487,183
<p>As the error indicates, the types of values that you can use as feeds are Python scalars, strings, lists or numpy arrays. What you are trying to use as feed is <code>img1</code>, the output of <code>tf.image.decode_png</code>, which is of type <code>tf.Tensor</code>. Hence the error. You have two options :</p> <p>1) Convert <code>img1</code> to a numpy array before feeding it. You can do that by simply <em>evaluating</em> <code>img1</code> as follows :</p> <pre><code>feed_dict = {images:img1.eval()} </code></pre> <p>2) Use <code>img1</code> itself as the input to the rest of the model. You can do that as follows :</p> <pre><code>batch_images = tf.expand_dims(img1, 0) </code></pre>
0
2016-07-20T17:35:25Z
[ "python", "image-processing", "tensorflow" ]
What is a python recipe and how do i run it?
38,486,785
<p>I am new to Python and I came across a useful piece of code (Python recipe) <a href="http://code.activestate.com/recipes/475157-disk-dumper/" rel="nofollow">here</a> that I want to run. </p> <p>I tried installing Python 3.5 and running it using the "python.exe scriptname.py" format but that lands me into syntax errors. Also tried opening the script in a Python IDE and tried running a syntax checker that again flags some errors. The fist error that i get is the the "os" field is not identified. The second one is the missing brackets around the print statement. </p> <p>But from the multiple comments on the post in the link above, it appears to me that this should run out of the box. </p> <p>How am i supposed to run a Python recipe? Is it any different from running a python script. I have heard of recipes in context of Chef so i'm not sure if this has anything to do with it. </p>
0
2016-07-20T17:12:33Z
38,486,836
<p>Your guess was right, <code>python scriptname.exe</code> is the way to go. However this script is for a much older version of Python (2.7), you'll need to fix some syntax issues like <code>print(...)</code> instead of <code>print ...</code> to make it run on Python 3.5.</p>
3
2016-07-20T17:14:55Z
[ "python", "recipe" ]
What is a python recipe and how do i run it?
38,486,785
<p>I am new to Python and I came across a useful piece of code (Python recipe) <a href="http://code.activestate.com/recipes/475157-disk-dumper/" rel="nofollow">here</a> that I want to run. </p> <p>I tried installing Python 3.5 and running it using the "python.exe scriptname.py" format but that lands me into syntax errors. Also tried opening the script in a Python IDE and tried running a syntax checker that again flags some errors. The fist error that i get is the the "os" field is not identified. The second one is the missing brackets around the print statement. </p> <p>But from the multiple comments on the post in the link above, it appears to me that this should run out of the box. </p> <p>How am i supposed to run a Python recipe? Is it any different from running a python script. I have heard of recipes in context of Chef so i'm not sure if this has anything to do with it. </p>
0
2016-07-20T17:12:33Z
38,486,895
<p>Python recipe comes from here <strong>The O'Reilly Python Cookbook</strong></p> <p>Its only a fancy name for algorithms that come in use frequently in daily life solved in python coding language.</p>
2
2016-07-20T17:18:04Z
[ "python", "recipe" ]
Python Radio Button Not Showing Up?
38,486,864
<p>I'm follow a GUI through Python tutorial on YouTube, and I cannot get the radio buttons show up in the message box and it works fine for the author of the video. I get no error message, is there a piece of my code that is incorrect or what am I doing wrong? </p> <pre><code>#create radio buttons; input equal to a value of a string and will come up checked dayStatus = StringVar() dayStatus.set(None) radio1 = Radiobutton(app, text="I'm feeling good", value="I'm feeling good", variable = dayStatus, command=beenClicked).pack #clicked radio calls the been clicked command radio1 = Radiobutton(app, text="I'm feeling crummy", value="I'm feeling crummy", variable = dayStatus, command=beenClicked).pack button1 = Button(app, text="Click Here", width=20,command=changeLabel) button1.pack(side='bottom',padx=15,pady=15) </code></pre>
-2
2016-07-20T17:16:26Z
38,486,933
<p>You need to correct these two lines by adding braces () at the end of the lines:</p> <pre><code>radio1 = Radiobutton(app, text="I'm feeling good", value="I'm feeling good", variable = dayStatus, command=beenClicked).pack() radio1 = Radiobutton(app, text="I'm feeling crummy", value="I'm feeling crummy", variable = dayStatus, command=beenClicked).pack() </code></pre>
0
2016-07-20T17:20:42Z
[ "python", "user-interface", "tkinter", "radio-button" ]
regex of extracting html from path
38,486,950
<p>I'm new to Regex. I need to extract 2 things from a directory path. ../path_to_html/myhtmlpage.html?additional_args_or_url</p> <p>how can i get the name of the html? eg.myhtmlpage</p> <p>and how can i get the entire url? eg.myhtmlpage.html?video_url=www.google.com/video</p> <p>Thank you very much!</p>
-1
2016-07-20T17:21:43Z
38,487,090
<p>Here you go:</p> <pre><code>import re url = "/path_to_html/myhtmlpage.html?video_url=www.google.com/video" # Name print re.findall(r'/(\w+)\.html', url)[0] # Entire url print re.findall(r'/(\w+\.html.*)', url)[0] </code></pre> <p>This prints:</p> <pre><code>myhtmlpage myhtmlpage.html?video_url=www.google.com/video </code></pre>
0
2016-07-20T17:30:08Z
[ "python", "regex" ]
Python random list generation
38,486,967
<p>I'm looking at a little challenge which requires me to </p> <p>1.create a function which generates a random lists of size 2 (a list in which it's two elements are randomly generated letters). </p> <p>2.create a function which scores how well a randomly generated list compares to another pre-defined list, so typically we can think of how many matches we have in each position. </p> <p>3.create a function which keeps calling and scoring a new randomly generated list until we reach a score of a certain size. It also wants to print the best score for every 1000 generated lists.</p> <p>I've done 1. and 2. for 3. i've created a function which repeatedly calls the score function until we meet a score of a certain size however i'm unsure how to print the best score per every 1000 generated lists this is because i've used a while loop for this to keep generating until a score of certain size is reached. One solution i had was to store the scores in a list by appending each score starting from an empty list. Then use the max function to print the best scores as the list is sliced into chunks of size 1000. </p> <p>Is there a better way?</p>
-2
2016-07-20T17:22:52Z
38,487,033
<p>Use a variable count which you increase incrementally per run and when count % 1000 = 0 and count > 0 print the highest score that you got from the iterations possibly saved into a global variable.</p>
1
2016-07-20T17:26:27Z
[ "python", "list", "random" ]
Python random list generation
38,486,967
<p>I'm looking at a little challenge which requires me to </p> <p>1.create a function which generates a random lists of size 2 (a list in which it's two elements are randomly generated letters). </p> <p>2.create a function which scores how well a randomly generated list compares to another pre-defined list, so typically we can think of how many matches we have in each position. </p> <p>3.create a function which keeps calling and scoring a new randomly generated list until we reach a score of a certain size. It also wants to print the best score for every 1000 generated lists.</p> <p>I've done 1. and 2. for 3. i've created a function which repeatedly calls the score function until we meet a score of a certain size however i'm unsure how to print the best score per every 1000 generated lists this is because i've used a while loop for this to keep generating until a score of certain size is reached. One solution i had was to store the scores in a list by appending each score starting from an empty list. Then use the max function to print the best scores as the list is sliced into chunks of size 1000. </p> <p>Is there a better way?</p>
-2
2016-07-20T17:22:52Z
38,487,048
<p>Could you define a variable called maximum such that:</p> <pre><code>if score &gt; maximum: maximum = score </code></pre> <p>?</p>
1
2016-07-20T17:27:23Z
[ "python", "list", "random" ]
Python random list generation
38,486,967
<p>I'm looking at a little challenge which requires me to </p> <p>1.create a function which generates a random lists of size 2 (a list in which it's two elements are randomly generated letters). </p> <p>2.create a function which scores how well a randomly generated list compares to another pre-defined list, so typically we can think of how many matches we have in each position. </p> <p>3.create a function which keeps calling and scoring a new randomly generated list until we reach a score of a certain size. It also wants to print the best score for every 1000 generated lists.</p> <p>I've done 1. and 2. for 3. i've created a function which repeatedly calls the score function until we meet a score of a certain size however i'm unsure how to print the best score per every 1000 generated lists this is because i've used a while loop for this to keep generating until a score of certain size is reached. One solution i had was to store the scores in a list by appending each score starting from an empty list. Then use the max function to print the best scores as the list is sliced into chunks of size 1000. </p> <p>Is there a better way?</p>
-2
2016-07-20T17:22:52Z
38,487,100
<p>What you need is the basic definition of max function. A value which is equal to the first score, then assigned to the new score if a better score is achieved.</p> <pre><code>if new_score &gt; max_score: max_score = new_score </code></pre> <p>And to your suggestion, my experience in this shows that applying my suggestion or yours(storing all the scores in a list then calling max) does not save much time in means of complexity, however if you do not need the scores other than the maximum one, you are just wasting space.</p>
1
2016-07-20T17:30:44Z
[ "python", "list", "random" ]
XML remove nodes with no attributes or children
38,487,043
<p>I have an xml file loaded, from which I want to remove elements that have no attributes or children, I'm trying to achieve something like this:</p> <pre><code>for child in root.find('targetElement'): print(child) if(len(child.attrib) &lt; 1 and len(child) &lt; 1): root.remove(child) </code></pre> <p>But I guess the problem is that I'm finding the element then trying to remove it from the root element. Can someone please tell me how to do this?</p>
0
2016-07-20T17:26:57Z
38,487,112
<p>You need to remove a node from its parent, not from the root. </p> <p>The following code works for <code>lxml.etree</code>:</p> <pre><code>from lxml import etree as ET root = ET.parse('yourfile.xml') for child in root.iterfind('targetElement'): if(len(child.attrib) &lt; 1 and len(child) &lt; 1): child.getparent().remove(child) </code></pre> <p>The standard <code>xml.etree.ElementTree</code> lacks any decent method of selecting the parent node. We can work around this limitation by constructing a child-to-parent map for the entire tree (<a href="http://stackoverflow.com/a/20132342/18771">source</a>):</p> <pre><code>import xml.etree.ElementTree as ET root = ET.parse('yourfile.xml') # http://stackoverflow.com/a/20132342/18771 parent_map = {c:p for p in root.iter() for c in p} for child in root.iterfind('targetElement'): if(len(child.attrib) &lt; 1 and len(child) &lt; 1): parent_map[child].remove(child) </code></pre>
0
2016-07-20T17:31:29Z
[ "python", "xml", "python-3.x", "elementtree", "xml.etree" ]
Show fullscreen webpage in 5 seconds then close window (python)
38,487,066
<p>I want to make a python script that opens up a local html file in browser and after 5 seconds close that window.</p> <p>I've tried the self.close() method and if I add "time.sleep()" it will only delay the display of the web content</p> <p>Here's my code (I'm a newbie so, sorry for that)</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * import urllib import time class Window(QWidget): def __init__(self, url, dur): super(Window, self).__init__() view = QWebView(self) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(view) html = urllib.urlopen(url).read() view.setHtml(html) time.sleep(dur) self.close() def main(url, dur): app = QApplication(sys.argv) window = Window(url, dur) window.showFullScreen() app.exec_() main('test.html', 5) </code></pre> <p>Any suggestions? As you can see I want to pass both url and duration (sleep) in the constructor.</p>
0
2016-07-20T17:28:37Z
38,489,154
<p>Use a single-shot timer (the interval is in milliseconds):</p> <pre><code>class Window(QWidget): def __init__(self, url, dur): ... view.setHtml(html) QTimer.singleShot(dur * 1000, self.close) </code></pre>
0
2016-07-20T19:23:18Z
[ "python", "pyqt4", "qapplication" ]
Looping over columns and column values for subsetting pandas dataframe
38,487,074
<p>I have a dataframe as follows <code>df</code>:</p> <pre><code> ID color finish duration A1 black smooth 12 A2 white matte 8 A3 blue smooth 20 A4 green matte 10 B1 black smooth 12 B2 white matte 8 B3 blue smooth B4 green 10 C1 black smooth C2 white matte 8 C3 blue smooth C4 green 10 </code></pre> <p>I want to generate subsets of this dataframe based on certain conditions. For example, <code>color= black</code>, <code>finish = smooth</code>, <code>duration = 12</code>, I get the following dataframe.</p> <pre><code>ID color finish duration score A1 black smooth 12 1 B1 black smooth 12 1 </code></pre> <p><code>color= blue</code>, <code>finish = smooth</code>, <code>duration = 20</code>, I get the following dataframe.</p> <pre><code>ID color finish duration score A3 blue smooth 20 1 B3 blue smooth 0.666667 C3 blue smooth 0.666667 </code></pre> <p>Score is calculated as <em>number of columns populated/total number of columns</em>. I want to loop this in pandas dataframe. Following code is working for me for 2 columns.</p> <pre><code>list2 = list(df['color'].unique()) list3 = list(df['finish'].unique()) df_final = pd.DataFrame() for i in range(len(list2)): for j in range(len(list3)): print 'Current Attribute Value:',list2[i],list3[j] gbl["df_"+list2[i]] = df[df.color == list2[i]] gbl["df_" + list2[i] + list3[j]] = gbl["df_"+list2[i]].loc[gbl["df_"+list2[i]].finish == list3[j]] gbl["df_" + list2[i] + list3[j]]['dfattribval'] = list2[i] + list3[j] df_final = df_final.append(gbl["df_" + list2[i] + list3[j]], ignore_index=True) </code></pre> <p>However, I am not able to loop this over column names. What I would like to do is,</p> <pre><code>lista = ['color','finish'] df_final = pd.DataFrame() for a in range(len(lista)): for i in range(len(list2)): for j in range(len(list3)): print 'Current Attribute Value:',lista[a],list2[i],lista[a+1],list3[j] gbl["df_"+list2[i]] = df[df.lista[a] == list2[i]] gbl["df_" + list2[i] + list3[j]] = gbl["df_"+list2[i]].loc[gbl["df_"+list2[i]].lista[a+1] == list3[j]] gbl["df_" + list2[i] + list3[j]]['dfattribval'] = list2[i] + list3[j] df_final = df_final.append(gbl["df_" + list2[i] + list3[j]], ignore_index=True) </code></pre> <p>I get the obvious error -</p> <blockquote> <p>AttributeError: 'DataFrame' object has no attribute 'lista'. </p> </blockquote> <p>Anyone would know how to loop over column names and values. Thanks much in advance!</p>
0
2016-07-20T17:29:04Z
38,517,728
<p>Not quite sure of your needs, but consider permuting your lists with a list comprehension to avoid the nested loops and use a dictionary of data frames. Possibly the <code>scorecalc()</code> apply function can be adjusted to fit your needs:</p> <pre><code>colorlist = list(df['color'].unique()) finishlist = list(df['finish'].unique()) durationlist = list(df['duration'].unique()) # ALL COMBINATIONS BETWEEN LISTS allList = [(c,f, d) for c in colorlist for f in finishlist for d in durationlist] def scorecalc(row): row['score'] = row['duration'].count() return(row) dfList = []; dfDict = {} for i in allList: # SUBSET DFS tempdf = df[(df['color'] == i[0]) &amp; (df['finish']==i[1]) &amp; (df['duration']==i[2])] if len(tempdf) &gt; 0: # FOR NON-EMPTY DFS print('Current Attribute Value:', i[0], i[1], i[2]) tempdf = tempdf.groupby(['color','finish']).apply(scorecalc) tempdf['score'] = tempdf['score'] / len(tempdf) print(tempdf) key = str(i[0]) + str(i[1]) + str(i[2]) dfDict[key] = tempdf # DICTIONARY OF DFS (USE pd.DataFrame(list(...)) FOR FINAL) dfList.append(tempdf) # LIST OF DFS (USE pd.concat() FOR FINAL DF) # Current Attribute Value: black smooth 12.0 # ID color finish duration score #0 A1 black smooth 12.0 1.0 #4 B1 black smooth 12.0 1.0 #Current Attribute Value: white matte 8.0 # ID color finish duration score #1 A2 white matte 8.0 1.0 #5 B2 white matte 8.0 1.0 #9 C2 white matte 8.0 1.0 #Current Attribute Value: blue smooth 20.0 # ID color finish duration score #2 A3 blue smooth 20.0 1.0 #Current Attribute Value: green matte 10.0 # ID color finish duration score #3 A4 green matte 10.0 1.0 </code></pre>
1
2016-07-22T03:33:24Z
[ "python", "pandas", "for-loop" ]