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 to use correclty pyprind with scikit-learn?
38,473,538
<p>Currently I am using <a href="https://github.com/rasbt/pyprind" rel="nofollow">pyprind</a>, a library that implements a progress bar:</p> <pre><code>#Compute training time elapsed pbar = pyprind.ProgBar(45, width=120, bar_char='█') for _ in range(45): #Fiting clf = SVC().fit(X_train, y_train) pbar.update() #End of bar </code></pre> <p>However, I do not know if that is the correct way to use the <code>pbar</code>, since I guess I am fitting 45 times <code>clf</code>. Thus, how should I use correctly <code>pbar</code>?.</p>
3
2016-07-20T06:10:59Z
38,474,143
<p>I haven't used <code>pyprind</code> but I have used <code>progressbar</code>. Just install it using-</p> <pre><code>pip install progressbar </code></pre> <p>And then -</p> <pre><code>from progressbar import ProgressBar pbar = ProgressBar() for x in pbar(range(45)): clf = SVC().fit(X_train, y_train) </code></pre> <p>and you are good to go.</p>
1
2016-07-20T06:47:29Z
[ "python", "python-2.7", "python-3.x", "scikit-learn" ]
How to use correclty pyprind with scikit-learn?
38,473,538
<p>Currently I am using <a href="https://github.com/rasbt/pyprind" rel="nofollow">pyprind</a>, a library that implements a progress bar:</p> <pre><code>#Compute training time elapsed pbar = pyprind.ProgBar(45, width=120, bar_char='█') for _ in range(45): #Fiting clf = SVC().fit(X_train, y_train) pbar.update() #End of bar </code></pre> <p>However, I do not know if that is the correct way to use the <code>pbar</code>, since I guess I am fitting 45 times <code>clf</code>. Thus, how should I use correctly <code>pbar</code>?.</p>
3
2016-07-20T06:10:59Z
38,474,642
<p>Note that if you want more information regarding the learning process you can use <code>vebose</code> flag for that:</p> <pre><code>X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) y = np.array([1, 1, 2, 2]) clf = SVC(verbose =True) clf.fit(X, y) </code></pre> <p>Output:</p> <pre><code>optimization finished, #iter = 12 obj = -1.253423, rho = 0.000003 nSV = 4, nBSV = 0 Total nSV = 4 </code></pre>
1
2016-07-20T07:13:10Z
[ "python", "python-2.7", "python-3.x", "scikit-learn" ]
django search autocomplete not working
38,473,541
<p>I am trying to use autocomplete for search but I am getting this error "Uncaught TypeError: $(...).autocomplete is not a function".I have already included jquery library</p> <pre><code>&lt;head&gt; &lt;link rel="stylesheet" href="{% static 'styles.css' %}"&gt; &lt;link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"&gt; &lt;script src="http://code.jquery.com/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="{% static 'script.js' %}"&gt;&lt;/script&gt; &lt;title&gt;{% block title %}Home{% endblock %}&lt;/title&gt; &lt;script&gt; $(document).ready(function() { $( "#search_text" ).autocomplete({ source: "/item_search/", minLength: 2, }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='cssmenu'&gt; &lt;ul&gt; &lt;li class='menus'&gt;&lt;a href="{% url 'welcome_user' %}"&gt;&lt;span&gt;Home&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class='menus'&gt;&lt;a href="{% url 'user_logout' %}"&gt;&lt;span&gt;Logout&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li id="input" style="padding:11px;float:right;"&gt; &lt;form name="myform" method="GET" action="{% url 'search' %}"&gt; &lt;input type="text" name="search" id="search_text" placeholder="Search"/&gt; &lt;/form&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>views.py,</p> <pre><code>def item_search(request): book_name = request.GET.get('search') if book_name is not None: rows = Add_prod.objects.filter(book__icontains=book_name) results = [ x.book for x in rows ] return HttpResponse(json.dumps(results)) </code></pre>
0
2016-07-20T06:11:14Z
38,473,636
<p>For autocomplete to work, you need to have have jQuery UI library included in your head. You can download it from here -> <a href="https://jqueryui.com/download/all/" rel="nofollow">https://jqueryui.com/download/all/</a></p>
0
2016-07-20T06:17:43Z
[ "python", "django" ]
django search autocomplete not working
38,473,541
<p>I am trying to use autocomplete for search but I am getting this error "Uncaught TypeError: $(...).autocomplete is not a function".I have already included jquery library</p> <pre><code>&lt;head&gt; &lt;link rel="stylesheet" href="{% static 'styles.css' %}"&gt; &lt;link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"&gt; &lt;script src="http://code.jquery.com/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="{% static 'script.js' %}"&gt;&lt;/script&gt; &lt;title&gt;{% block title %}Home{% endblock %}&lt;/title&gt; &lt;script&gt; $(document).ready(function() { $( "#search_text" ).autocomplete({ source: "/item_search/", minLength: 2, }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='cssmenu'&gt; &lt;ul&gt; &lt;li class='menus'&gt;&lt;a href="{% url 'welcome_user' %}"&gt;&lt;span&gt;Home&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class='menus'&gt;&lt;a href="{% url 'user_logout' %}"&gt;&lt;span&gt;Logout&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li id="input" style="padding:11px;float:right;"&gt; &lt;form name="myform" method="GET" action="{% url 'search' %}"&gt; &lt;input type="text" name="search" id="search_text" placeholder="Search"/&gt; &lt;/form&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>views.py,</p> <pre><code>def item_search(request): book_name = request.GET.get('search') if book_name is not None: rows = Add_prod.objects.filter(book__icontains=book_name) results = [ x.book for x in rows ] return HttpResponse(json.dumps(results)) </code></pre>
0
2016-07-20T06:11:14Z
38,929,915
<p>Actually I think you are using two jquery remove this one</p> <p><code>&lt;script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"&gt;&lt;/script&gt;</code></p>
0
2016-08-13T06:30:17Z
[ "python", "django" ]
How to get string from a django.utils.safestring.SafeText
38,473,545
<p>I'm getting a django.utils.safestring.SafeText in my unit test:</p> <pre><code>ipdb&gt; mail.outbox[0].body u'Dear John Doe,&lt;br&gt;\n&lt;p&gt;\nYou have received a .. ipdb&gt; type(mail.outbox[0].body) &lt;class 'django.utils.safestring.SafeText'&gt; </code></pre> <p>I would like to convert the above into a string, so that I can strip out the <code>\n</code> characters.. ie I want to use the <code>rstrip()</code> method.. but I obviously can't do that on a <code>django.utils.safestring.SafeText</code> object. Ideas?</p>
0
2016-07-20T06:11:24Z
38,474,051
<p>Create new string based on SafeText</p> <pre><code>str(mail.outbox[0].body) </code></pre>
1
2016-07-20T06:42:16Z
[ "python", "django", "python-2.7" ]
How to get string from a django.utils.safestring.SafeText
38,473,545
<p>I'm getting a django.utils.safestring.SafeText in my unit test:</p> <pre><code>ipdb&gt; mail.outbox[0].body u'Dear John Doe,&lt;br&gt;\n&lt;p&gt;\nYou have received a .. ipdb&gt; type(mail.outbox[0].body) &lt;class 'django.utils.safestring.SafeText'&gt; </code></pre> <p>I would like to convert the above into a string, so that I can strip out the <code>\n</code> characters.. ie I want to use the <code>rstrip()</code> method.. but I obviously can't do that on a <code>django.utils.safestring.SafeText</code> object. Ideas?</p>
0
2016-07-20T06:11:24Z
38,477,425
<p>You can do the things you want to do with <code>django.utils.safestring.SafeText</code> object.You can apply almost every method as string on SafeText object. Available methods are </p> <pre><code>'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'islower', 'isnumeric', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill' </code></pre> <p>But they will return unicode object. Example:-</p> <pre><code>&gt;&gt;&gt; from django.utils.safestring import SafeText &gt;&gt;&gt; my_safe_text = SafeText('Dear John Doe,&lt;br&gt;\n&lt;p&gt;\nYou have received a .. ') &gt;&gt;&gt; type(my_safe_text) &lt;class 'django.utils.safestring.SafeText'&gt; &gt;&gt;&gt; my_replaced_unicode = my_safe_text.replace('\n','') &gt;&gt;&gt; my_replaced_unicode u'Dear John Doe,&lt;br&gt;&lt;p&gt;You have received a .. ' &gt;&gt;&gt; type(my_replaced_unicode) &lt;type 'unicode'&gt; &gt;&gt;&gt; my_rstriped_unicode = my_safe_text.rstrip() &gt;&gt;&gt; my_rstriped_unicode u'Dear John Doe,&lt;br&gt;\n&lt;p&gt;\nYou have received a ..' &gt;&gt;&gt; type(my_rstriped_unicode) &lt;type 'unicode'&gt; </code></pre>
0
2016-07-20T09:27:39Z
[ "python", "django", "python-2.7" ]
Removing quotes from mysql query in Python
38,473,598
<p>I know that this question has been asked in the past, but thorough searching hasn't seemed to fix my issue. I'm probably just missing something simple, as I'm new to the Python-mysql connector supplied by mysql. </p> <p>I have a Python script which accesses a mysql database, but I'm having issues with removing quotes from my query. Here is my code:</p> <pre><code>import mysql.connector try: db = mysql.connector.connect(user='root', password='somePassword', host='127.0.0.1', database='dbName') cursor = db.cursor() query = "select * from tags where %s = %s" a = 'tag_id' b = '0' cursor.execute(query, (a, b)) print cursor data = cursor.fetchall() print data except mysql.connector.Error as err: print "Exception tripped..." print "--------------------------------------" print err cursor.close() db.close() </code></pre> <p>My database is set up properly (as I'll prove shortly).</p> <p>My output for this program is:</p> <pre><code>MySQLCursor: select * from tags where 'tag_id' = '0' [] </code></pre> <p>Yet when I change my query to not use variables, for example:</p> <pre><code>cursor.execute("select * from tags where tag_id = 0") </code></pre> <p>Then my output becomes:</p> <pre><code>MySQLCursor: select * from tags where tag_id = 0 [(0, u'192.168.1.110')] </code></pre> <p>To me, this means that the only difference between my Cursor queries are the quotes.</p> <p>How do I remove them from the query?</p> <p>Thanks in advance.</p>
0
2016-07-20T06:15:23Z
38,475,321
<h2>I personally believe this code is correct and safe, but you should be <em>extremely skeptical</em> of using code like this without carefully reviewing it yourself or (better yet) with the help of a security expert. I am not qualified to be such an expert.</h2> <p>Two important things I changed:</p> <ol> <li>I changed <code>b = '0'</code> to <code>b = 0</code> so it ends up as a number rather than a quoted string. (This part was an easy fix.)</li> <li>I skipped the built-in parameterization for the column name and replaced it with my own slight modification to the escaping/quoting built in to mysql-connector. This is the scary part that should give you pause.</li> </ol> <p>Full code below, but again, be careful with this if the column name is user input!</p> <pre><code>import mysql.connector def escape_column_name(name): # This is meant to mostly do the same thing as the _process_params method # of mysql.connector.MySQLCursor, but instead of the final quoting step, # we escape any previously existing backticks and quote with backticks. converter = mysql.connector.conversion.MySQLConverter() return "`" + converter.escape(converter.to_mysql(name)).replace('`', '``') + "`" try: db = mysql.connector.connect(user='root', password='somePassword', host='127.0.0.1', database='dbName') cursor = db.cursor() a = 'tag_id' b = 0 cursor.execute( 'select * from tags where {} = %s'.format(escape_column_name(a)), (b,) ) print cursor data = cursor.fetchall() print data except mysql.connector.Error as err: print "Exception tripped..." print "--------------------------------------" print err cursor.close() db.close() </code></pre>
0
2016-07-20T07:46:12Z
[ "python", "mysql" ]
Django Templates: How best can the output of executing python code in a Django template be suppressed?
38,473,656
<p>Someone has probably encountered this before, and perhaps even the docs provide a solution already, but I couldn't find it yet. My situation is this:</p> <p>Just to illustrate the REAL PROBLEM: Assuming I have a list that I pass to the template, and which list I iterate over, with a <code>{% for...</code> in one instance, and in the other, I only need to display its first 5 elements only (based on some condition for example, and not just the first 5 elements of the list). Both loops are being used to output a table dynamically. Now, it's the second instance that's tricky... I adopted <a href="http://stackoverflow.com/a/8671715/522150">the solution here</a>, which utilizes a special Counter Class, passed to the template context, and on which one must invoke the <code>Counter.increment</code> method, to be able to increment the counter - which I then use in my conditional statement, to halt execution of the loop.</p> <p>The challenge: </p> <p>I currently have code like this:</p> <pre><code>&lt;script&gt;{{ Counter.reset }}&lt;/script&gt; &lt;table&gt; ... {% for l in list %} {%if Counter.counter &lt;= 5 %} &lt;tr&gt;&lt;td&gt;{{ l.some_field }} &lt;span style="display:none"&gt;{{ Counter.increment }}&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt; {% endif %} {% endfor %} &lt;/table&gt; </code></pre> <p>So, how can I just call the <code>Counter.increment</code> method, without needing the <code>&lt;span&gt;</code> inside which I encapsulate it (so the output from that code isn't sent to the browser)? Is it okay to just do:</p> <pre><code>&lt;tr&gt;&lt;td&gt;{{ l.some_field }}{{ Counter.increment }}&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>The above would work, if <code>Counter.increment</code> doesn't return anything, but what if it does?! </p> <p><strong>How best can the output of executing python code in a Django template be suppressed then?</strong></p>
1
2016-07-20T06:19:14Z
38,473,766
<p>If you only need the top five elements, then I think the right way is to <strong>send a list</strong> of only top 5 elements from your views to your your html templates in the very first place.</p> <p>Also, if for some reason, you are not able to do that, then you should there is a thing in Django known as <strong>Template Tags</strong> where you do all your calculations.</p> <p>See this -> <a href="https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/" rel="nofollow">https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/</a></p> <p>And finally if you still want to use Counter.increment, then simply put it inside a div say "count-flag" and using your javascript, hide that div forever on page load:</p> <pre><code>$(document).on('ready', function(){ $("#count-flag").hide(); } </code></pre> <p>So it will not be displayed on your html, but technically this is not the way to do it.</p>
0
2016-07-20T06:26:17Z
[ "python", "django", "django-templates" ]
Django Templates: How best can the output of executing python code in a Django template be suppressed?
38,473,656
<p>Someone has probably encountered this before, and perhaps even the docs provide a solution already, but I couldn't find it yet. My situation is this:</p> <p>Just to illustrate the REAL PROBLEM: Assuming I have a list that I pass to the template, and which list I iterate over, with a <code>{% for...</code> in one instance, and in the other, I only need to display its first 5 elements only (based on some condition for example, and not just the first 5 elements of the list). Both loops are being used to output a table dynamically. Now, it's the second instance that's tricky... I adopted <a href="http://stackoverflow.com/a/8671715/522150">the solution here</a>, which utilizes a special Counter Class, passed to the template context, and on which one must invoke the <code>Counter.increment</code> method, to be able to increment the counter - which I then use in my conditional statement, to halt execution of the loop.</p> <p>The challenge: </p> <p>I currently have code like this:</p> <pre><code>&lt;script&gt;{{ Counter.reset }}&lt;/script&gt; &lt;table&gt; ... {% for l in list %} {%if Counter.counter &lt;= 5 %} &lt;tr&gt;&lt;td&gt;{{ l.some_field }} &lt;span style="display:none"&gt;{{ Counter.increment }}&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt; {% endif %} {% endfor %} &lt;/table&gt; </code></pre> <p>So, how can I just call the <code>Counter.increment</code> method, without needing the <code>&lt;span&gt;</code> inside which I encapsulate it (so the output from that code isn't sent to the browser)? Is it okay to just do:</p> <pre><code>&lt;tr&gt;&lt;td&gt;{{ l.some_field }}{{ Counter.increment }}&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>The above would work, if <code>Counter.increment</code> doesn't return anything, but what if it does?! </p> <p><strong>How best can the output of executing python code in a Django template be suppressed then?</strong></p>
1
2016-07-20T06:19:14Z
38,475,317
<p>This is a bit of a hack, but it would solve your problem:</p> <pre><code>{{ Counter.increment|yesno:"," }} </code></pre> <p>(See the <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#yesno" rel="nofollow">documentation</a> on the <code>yesno</code> filter)</p>
1
2016-07-20T07:45:56Z
[ "python", "django", "django-templates" ]
Django Templates: How best can the output of executing python code in a Django template be suppressed?
38,473,656
<p>Someone has probably encountered this before, and perhaps even the docs provide a solution already, but I couldn't find it yet. My situation is this:</p> <p>Just to illustrate the REAL PROBLEM: Assuming I have a list that I pass to the template, and which list I iterate over, with a <code>{% for...</code> in one instance, and in the other, I only need to display its first 5 elements only (based on some condition for example, and not just the first 5 elements of the list). Both loops are being used to output a table dynamically. Now, it's the second instance that's tricky... I adopted <a href="http://stackoverflow.com/a/8671715/522150">the solution here</a>, which utilizes a special Counter Class, passed to the template context, and on which one must invoke the <code>Counter.increment</code> method, to be able to increment the counter - which I then use in my conditional statement, to halt execution of the loop.</p> <p>The challenge: </p> <p>I currently have code like this:</p> <pre><code>&lt;script&gt;{{ Counter.reset }}&lt;/script&gt; &lt;table&gt; ... {% for l in list %} {%if Counter.counter &lt;= 5 %} &lt;tr&gt;&lt;td&gt;{{ l.some_field }} &lt;span style="display:none"&gt;{{ Counter.increment }}&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt; {% endif %} {% endfor %} &lt;/table&gt; </code></pre> <p>So, how can I just call the <code>Counter.increment</code> method, without needing the <code>&lt;span&gt;</code> inside which I encapsulate it (so the output from that code isn't sent to the browser)? Is it okay to just do:</p> <pre><code>&lt;tr&gt;&lt;td&gt;{{ l.some_field }}{{ Counter.increment }}&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>The above would work, if <code>Counter.increment</code> doesn't return anything, but what if it does?! </p> <p><strong>How best can the output of executing python code in a Django template be suppressed then?</strong></p>
1
2016-07-20T06:19:14Z
38,475,363
<p>Also you can use <code>with</code> tag and ignore variable:</p> <pre><code>{% with ignorevar=Counter.increment %}{% endwith %} </code></pre>
1
2016-07-20T07:49:03Z
[ "python", "django", "django-templates" ]
write on newline in a text file on each iteration using python
38,473,691
<p>want to write in newline in each iteration but it does not work out. i read random string using function getUser() and getFriends() from abc.txt. And write in text file new_file.txt but it writes in first line in each iteration</p> <p>output:['Larina'] ['Oormi', 'Palky']['Kavia'] ['Chakradhari', 'Chunni']</p> <p>i need in this format:</p> <p>['Larina'] ['Oormi', 'Palky']</p> <p>['Kavia'] ['Chakradhari', 'Chunni']</p> <pre><code>with open("new_file.txt", "wb") as sink: for i in range(0,2): print&gt;&gt;sink, getUser(),getFriends() #print&gt;&gt;sink,("\n") def getUser(): with open("abc.txt", "rb") as source: lines = [line.rstrip() for line in source] random_choice = random.sample(lines, 1) source.close() return(random_choice); def getFriends(): with open("abc.txt", "rb") as source: lines = source.read().splitlines() random_choice = random.sample(lines, 2) source.close() return(random_choice); </code></pre>
1
2016-07-20T06:22:01Z
38,473,792
<p>You don't have to close <code>source</code> because <code>with</code> statement does it for you.</p> <p>Try this code:</p> <pre><code>with open("new_file.txt", "wb") as sink: for i in range(0,2): sink.write("%s %s\n" % (str(getUser()), str(getFriends()))) def getUser(): with open("abc.txt", "rb") as source: lines = [line.rstrip() for line in source] random_choice = random.sample(lines, 1) return(random_choice); def getFriends(): with open("abc.txt", "rb") as source: lines = source.read().splitlines() random_choice = random.sample(lines, 2) return(random_choice) </code></pre>
0
2016-07-20T06:27:13Z
[ "python", "file-io" ]
Apache Spark- Error initializing SparkContext. java.io.FileNotFoundException
38,473,736
<p>I am able to run simple Hello World program through Spark on standalone machine. But when I run a word count program using Spark Context and run it using pyspark I get the following error. ERROR SparkContext: Error initializing SparkContext. java.io.FileNotFoundException: Added file file:/Users/tanyagupta/Documents/Internship/Zyudly%20Labs/Tanya-Programs/word_count.py does not exist. I am on Mac OS X. I installed Spark through brew by brew install apache-spark. Any ideas now whats going wrong?</p> <p>Using Spark's default log4j profile: </p> <pre><code>org/apache/spark/log4j-defaults.properties 16/07/19 23:18:45 INFO SparkContext: Running Spark version 1.6.2 16/07/19 23:18:45 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 16/07/19 23:18:45 INFO SecurityManager: Changing view acls to: tanyagupta 16/07/19 23:18:45 INFO SecurityManager: Changing modify acls to: tanyagupta 16/07/19 23:18:45 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(tanyagupta); users with modify permissions: Set(tanyagupta) 16/07/19 23:18:46 INFO Utils: Successfully started service 'sparkDriver' on port 59226. 16/07/19 23:18:46 INFO Slf4jLogger: Slf4jLogger started 16/07/19 23:18:46 INFO Remoting: Starting remoting 16/07/19 23:18:46 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriverActorSystem@192.168.0.5:59227] 16/07/19 23:18:46 INFO Utils: Successfully started service 'sparkDriverActorSystem' on port 59227. 16/07/19 23:18:46 INFO SparkEnv: Registering MapOutputTracker 16/07/19 23:18:46 INFO SparkEnv: Registering BlockManagerMaster 16/07/19 23:18:46 INFO DiskBlockManager: Created local directory at /private/var/folders/2f/fltslxd54f5961xsc2wg1w680000gn/T/blockmgr-812de6f9-3e3d-4885-a7de-fc9c2e181c64 16/07/19 23:18:46 INFO MemoryStore: MemoryStore started with capacity 511.1 MB 16/07/19 23:18:46 INFO SparkEnv: Registering OutputCommitCoordinator 16/07/19 23:18:46 INFO Utils: Successfully started service 'SparkUI' on port 4040. 16/07/19 23:18:46 INFO SparkUI: Started SparkUI at http://192.168.0.5:4040 16/07/19 23:18:46 ERROR SparkContext: Error initializing SparkContext. java.io.FileNotFoundException: Added file file:/Users/tanyagupta/Documents/Internship/Zyudly%20Labs/Tanya-Programs/word_count.py does not exist. at org.apache.spark.SparkContext.addFile(SparkContext.scala:1364) at org.apache.spark.SparkContext.addFile(SparkContext.scala:1340) at org.apache.spark.SparkContext$$anonfun$15.apply(SparkContext.scala:491) at org.apache.spark.SparkContext$$anonfun$15.apply(SparkContext.scala:491) at scala.collection.immutable.List.foreach(List.scala:318) at org.apache.spark.SparkContext.&lt;init&gt;(SparkContext.scala:491) at org.apache.spark.api.java.JavaSparkContext.&lt;init&gt;(JavaSparkContext.scala:59) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:234) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381) at py4j.Gateway.invoke(Gateway.java:214) at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:79) at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:68) at py4j.GatewayConnection.run(GatewayConnection.java:209) at java.lang.Thread.run(Thread.java:745) 16/07/19 23:18:47 INFO SparkUI: Stopped Spark web UI at http://192.168.0.5:4040 16/07/19 23:18:47 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped! 16/07/19 23:18:47 INFO MemoryStore: MemoryStore cleared 16/07/19 23:18:47 INFO BlockManager: BlockManager stopped 16/07/19 23:18:47 INFO BlockManagerMaster: BlockManagerMaster stopped 16/07/19 23:18:47 WARN MetricsSystem: Stopping a MetricsSystem that is not running 16/07/19 23:18:47 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped! 16/07/19 23:18:47 INFO RemoteActorRefProvider$RemotingTerminator: Shutting down remote daemon. 16/07/19 23:18:47 INFO RemoteActorRefProvider$RemotingTerminator: Remote daemon shut down; proceeding with flushing remote transports. 16/07/19 23:18:47 INFO SparkContext: Successfully stopped SparkContext Traceback (most recent call last): File "/Users/tanyagupta/Documents/Internship/Zyudly Labs/Tanya-Programs/word_count.py", line 7, in &lt;module&gt; sc=SparkContext(appName="WordCount_Tanya") File "/usr/local/Cellar/apache-spark/1.6.2/libexec/python/lib/pyspark.zip/pyspark/context.py", line 115, in __init__ File "/usr/local/Cellar/apache-spark/1.6.2/libexec/python/lib/pyspark.zip/pyspark/context.py", line 172, in _do_init File "/usr/local/Cellar/apache-spark/1.6.2/libexec/python/lib/pyspark.zip/pyspark/context.py", line 235, in _initialize_context File "/usr/local/Cellar/apache-spark/1.6.2/libexec/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 1064, in __call__ File "/usr/local/Cellar/apache-spark/1.6.2/libexec/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext. : java.io.FileNotFoundException: Added file file:/Users/tanyagupta/Documents/Internship/Zyudly%20Labs/Tanya-Programs/word_count.py does not exist. at org.apache.spark.SparkContext.addFile(SparkContext.scala:1364) at org.apache.spark.SparkContext.addFile(SparkContext.scala:1340) at org.apache.spark.SparkContext$$anonfun$15.apply(SparkContext.scala:491) at org.apache.spark.SparkContext$$anonfun$15.apply(SparkContext.scala:491) at scala.collection.immutable.List.foreach(List.scala:318) at org.apache.spark.SparkContext.&lt;init&gt;(SparkContext.scala:491) at org.apache.spark.api.java.JavaSparkContext.&lt;init&gt;(JavaSparkContext.scala:59) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:234) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381) at py4j.Gateway.invoke(Gateway.java:214) at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:79) at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:68) at py4j.GatewayConnection.run(GatewayConnection.java:209) at java.lang.Thread.run(Thread.java:745) 16/07/19 23:18:47 INFO RemoteActorRefProvider$RemotingTerminator: Remoting shut down. 16/07/19 23:18:47 INFO ShutdownHookManager: Shutdown hook called 16/07/19 23:18:47 INFO ShutdownHookManager: Deleting directory /private/var/folders/2f/fltslxd54f5961xsc2wg1w680000gn/T/spark-f69e5dfc-6561-4677-9ec0-03594eabc991 </code></pre>
0
2016-07-20T06:24:16Z
38,647,228
<p>Adding [underscore][underscore]init[underscore][underscore].py file in my folder worked for me!</p> <p>Thanks!</p>
1
2016-07-28T21:43:23Z
[ "python", "osx", "apache-spark", "pyspark" ]
How to save board game? Python
38,473,754
<p>I have programmed Connect 4 using python, and I wanted to make a Save option although I'm unsure how I would save all of the users inputs. Which would be mainly all the counters that have been placed on the board. The board is a multidimensional array:</p> <pre><code>board = [] for row in range(6): board.append([]) for column in range(7): board[row].append(0) </code></pre> <p>Would anyone have any idea how I'd store this data? I was thinking of writing it to a file and when opening the save it can read it, although I'm unsure how to reinterpret the text into board positions.</p>
1
2016-07-20T06:25:40Z
38,473,850
<p>If you only care about reading this file with Python, then <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">pickle</a> it!</p> <pre><code>import pickle fp = '/path/to/saved/file.pkl' with open(fp, 'wb') as f: pickle.dump(board, f) </code></pre>
4
2016-07-20T06:30:32Z
[ "python", "python-3.x", "save", "pygame" ]
How to save board game? Python
38,473,754
<p>I have programmed Connect 4 using python, and I wanted to make a Save option although I'm unsure how I would save all of the users inputs. Which would be mainly all the counters that have been placed on the board. The board is a multidimensional array:</p> <pre><code>board = [] for row in range(6): board.append([]) for column in range(7): board[row].append(0) </code></pre> <p>Would anyone have any idea how I'd store this data? I was thinking of writing it to a file and when opening the save it can read it, although I'm unsure how to reinterpret the text into board positions.</p>
1
2016-07-20T06:25:40Z
38,477,715
<p>If your game state gets saved in a simple object, like a list of list of integers, like this:</p> <pre><code>WIDTH = 7 HEIGHT = 6 board = [[0 for column in range(WIDTH)] for row in range(HEIGHT)] </code></pre> <p>then you can also use JSON instead of pickle to store this object in a file, like this:</p> <pre><code>import json fp = "/path/to/saved/file.txt" with open(fp, "w") as savefile: json.dump(board, savefile) </code></pre> <p>Note that this is basically the same answer Alex gave, with pickle replaced with json. The advantage of pickle is that you can store almost all (not too bizarre) Python objects, while the advantage of json is that this format can be read by other programs, too. Also, loading game state from a pickled objected opens you to the risk of maliciously constructed code inside the pickle, if the saved game file can come from arbitrary locations.</p> <p>If you also want to save the history how your user got there, you have to implement some other data structure to save that history, but you then can save that other data object in a similar fashion.</p>
1
2016-07-20T09:42:39Z
[ "python", "python-3.x", "save", "pygame" ]
Find location of image inside bigger image
38,473,952
<p>So i have an image lets say <code>small.png</code> and a bigger image <code>big.png</code> .The small image occurs 2 times in the bigger image and i wish to find its location.</p> <p>I tried using numpy and Image but got error </p> <p><code>'JpegImageFile' object has no attribute '__getitem__'</code>.I had <code>png</code> format earlier and it gave the same error.</p> <p>Is there any other module or way to get this done.I am open to any .</p> <p>The code as of now which throws error is</p> <pre><code>import numpy from PIL import Image here = Image.open(r"/Users/vks/Desktop/heren.jpg") big = Image.open(r"/Users/vks/Desktop/Settingsn.jpg") print here,big herear = numpy.asarray(here) bigar = numpy.asarray(big) herearx = herear.shape[0] hereary = herear.shape[1] bigarx = bigar.shape[0] bigary = bigar.shape[1] print herearx , hereary , bigarx, bigary stopx = bigarx - herearx + 1 stopy = bigary - hereary + 1 for x in range(0, stopx): for y in range(0, stopy): x2 = x+ herearx y2 = y + hereary pic = big[y:y2, x:x2] ===&gt; error thrown here test = pic = here if test.all(): print x,y else: print "None" </code></pre> <p>There was another <code>cv2</code> module but it just doesnt get installed on my mac. <code>pip install cv2</code> fails saying on package found.</p> <p><a href="http://i.stack.imgur.com/VBwmB.png" rel="nofollow"><img src="http://i.stack.imgur.com/VBwmB.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/KGHhI.png" rel="nofollow"><img src="http://i.stack.imgur.com/KGHhI.png" alt="enter image description here"></a></p>
5
2016-07-20T06:37:20Z
38,474,539
<p>The following code works for me:</p> <pre><code>import numpy from PIL import Image here = Image.open(r"eye.png") big = Image.open(r"lenna.png") herear = numpy.asarray(here) bigar = numpy.asarray(big) hereary, herearx = herear.shape[:2] bigary, bigarx = bigar.shape[:2] stopx = bigarx - herearx + 1 stopy = bigary - hereary + 1 for x in range(0, stopx): for y in range(0, stopy): x2 = x + herearx y2 = y + hereary pic = bigar[y:y2, x:x2] test = (pic == herear) if test.all(): print(x,y) </code></pre> <p><strong>Output:</strong> <code>312 237</code></p> <p><strong>Graphically:</strong></p> <p><a href="http://i.stack.imgur.com/EGZ6H.png" rel="nofollow"><img src="http://i.stack.imgur.com/EGZ6H.png" alt="enter image description here"></a></p> <h2>Test Images Used</h2> <p><strong>lenna.png</strong></p> <p><a href="http://i.stack.imgur.com/A2QQe.png" rel="nofollow"><img src="http://i.stack.imgur.com/A2QQe.png" alt="Lenna"></a></p> <p><strong>eye.png</strong></p> <p><a href="http://i.stack.imgur.com/egf7S.png" rel="nofollow"><img src="http://i.stack.imgur.com/egf7S.png" alt="Eye"></a></p> <p><strong>Note</strong>: It's important that you use a lossless image format when you create the smaller, cropped version (PNG is lossless, JPEG is most usually lossy). If you use a lossy format, you risk the pixel values being close, but not identical. The above code based off yours will <em>only find exact pixel-by-pixel matches</em>. The OpenCV template matching functions are a bit more flexible in this regard. That is not to say you couldn't modify your code to work just as well, you could. But as it stands, the code in this answer has that limitation.</p> <p><strong>More general version</strong></p> <p>Here, as a function, this gathers all matching coordinates and returns them as a list of (x,y) tuples:</p> <pre><code>import numpy as np from PIL import Image im_haystack = Image.open(r"lenna.png") im_needle = Image.open(r"eye.png") def find_matches(haystack, needle): arr_h = np.asarray(haystack) arr_n = np.asarray(needle) y_h, x_h = arr_h.shape[:2] y_n, x_n = arr_n.shape[:2] xstop = x_h - x_n + 1 ystop = y_h - y_n + 1 matches = [] for xmin in range(0, xstop): for ymin in range(0, ystop): xmax = xmin + x_n ymax = ymin + y_n arr_s = arr_h[ymin:ymax, xmin:xmax] # Extract subimage arr_t = (arr_s == arr_n) # Create test matrix if arr_t.all(): # Only consider exact matches matches.append((xmin,ymin)) return matches print(find_matches(im_haystack, im_needle)) </code></pre> <p><strong>Update:</strong></p> <p>Given the images you provided, you'll notice that the way the matching is set up, it will only match one of the two here's. The top-left one is one the one you cropped for the needle image, so it matches exactly. The bottom-right image would need to match exactly pixel-for-pixel. With this implementation, even a single bit difference in one of the color channels would cause it to be ignored.</p> <p>As it turns out, the two here's vary quite a bit more: <a href="http://i.stack.imgur.com/nQ6RA.gif" rel="nofollow"><img src="http://i.stack.imgur.com/nQ6RA.gif" alt="enter image description here"></a></p> <p><strong>Tested Versions:</strong></p> <ul> <li>Python 2.7.10, Numpy 1.11.1, PIL (Pillow) 1.1.7</li> <li>Python 3.5.0, Numpy 1.10.4, PIL (Pillow) 1.1.7</li> </ul>
3
2016-07-20T07:08:06Z
[ "python", "numpy", "image-processing" ]
How to count numbers between l and r divisible by k
38,473,954
<pre><code># Taking inputs l=input() r=input() k=input() count = 0 # For loop for i in range(l,r): if(i%k)==0: count+=1 </code></pre>
-4
2016-07-20T06:37:23Z
38,474,090
<p>If you want to check if r is divisable by k you would need to use <code>range(l,r+1)</code>. See <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">https://docs.python.org/2/library/functions.html#range</a></p> <p>Otherwise your code is ok.</p>
0
2016-07-20T06:44:34Z
[ "python" ]
python object instance variable looks like a class variable?
38,474,138
<p>I'm using <code>SQLAlchemy</code> in Python 3 and am confused why the following code works - it looks to me like what should be an object level variable is acting as a class variable. I have seen <a href="http://stackoverflow.com/questions/13144433/why-is-instance-variable-behaving-like-a-class-variable-in-python">Why is instance variable behaving like a class variable in Python?</a> which doesn't look related to my question.</p> <p>I have the following declarations in a <code>db</code> module in which I create an instance of <code>Base</code> and set a <code>query</code> variable on it that points to the <code>SessionFactory</code> <code>query_property()</code></p> <pre><code>import sqlalchemy as sa import sqlalchemy.ext.declarative as sa_ed Base = sa_ed.declarative_base() engine = sa.create_engine('connection string') session_factory = session or sa_orm.scoped_session(sa_orm.sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base.query = session_factory.query_property() # make the query_property available in models for querying </code></pre> <p>My model classes are then declared as follows:</p> <pre><code>import db class MyModel(db.Base): id = Column(Integer) # more model stuff </code></pre> <p>I can then run queries by accessing the <code>query</code> variable as follows:</p> <pre><code>return MyModel.query.filter(MyModel.id == 22).first() </code></pre> <p>This does work, but it looks as though the <code>query</code> variable exists at the class level and not at the object instance level as I am able to access it directly through the class.</p> <p>What am I not understanding?</p>
1
2016-07-20T06:47:10Z
38,474,364
<p>You put the <code>query</code> property on the parent class earlier:</p> <pre><code>Base.query = session_factory.query_property() # make the query_property available in models for querying </code></pre> <p>So <code>query</code> is most definitely a member of <em>a</em> class (<code>Base</code>). And since <code>MyModel</code> inherits from <code>Base</code>, <code>MyModel</code> should also have a <code>query</code> member (due to the magic of inheritance).</p>
0
2016-07-20T06:59:32Z
[ "python", "sqlalchemy" ]
How to delete a file with invalid name using python?
38,474,210
<p>I've got a <code>file</code> named <code>umengchannel_316_豌豆荚</code> I want to delete this file.. I tried the following: <code>os.remove()</code>, <code>os.unlink()</code> , <code>shutil.move()</code> but nothing seems to work.. Are there any other approaches to this problem?</p>
0
2016-07-20T06:50:48Z
38,478,589
<p>I'm using Unix OS, have been able to create a blank file with the name you specified and delete it with <code>os.remove()</code> in python intepreter.</p> <pre><code>$ cd ~ $ touch "umengchannel_316_豌豆荚.txt" $ python &gt;&gt;&gt; import os &gt;&gt;&gt; os.remove("/home/neko/umengchannel_316_豌豆荚.txt") </code></pre>
0
2016-07-20T10:20:42Z
[ "python", "python-2.7", "python-3.x", "subprocess" ]
How to delete a file with invalid name using python?
38,474,210
<p>I've got a <code>file</code> named <code>umengchannel_316_豌豆荚</code> I want to delete this file.. I tried the following: <code>os.remove()</code>, <code>os.unlink()</code> , <code>shutil.move()</code> but nothing seems to work.. Are there any other approaches to this problem?</p>
0
2016-07-20T06:50:48Z
38,478,933
<p>This worked for me:</p> <p><code>os.system("rm umengchannel_316_豌豆荚")</code></p>
0
2016-07-20T10:36:26Z
[ "python", "python-2.7", "python-3.x", "subprocess" ]
Django: Inheriting from a class that has djangofsm field and not able to call the transition
38,474,219
<p>I have a abstract django model </p> <pre><code>from django_fsm import FSMField, transition from django.db.models import Model, NullBooleanField, TextField class ApprovalMixin(Model): status = FSMField(default='new') is_approved = NullBooleanField(blank=True, null=True) class Meta: """Meta Attributes""" abstract = True </code></pre> <p>Then I am inhering this class in another model:</p> <pre><code>class Request(ApprovalMixin): notes = TextField(blank=True, null=True, help_text="ts notes") @transition(field=status, source='new', target='rejected') def manager_rejection(self): pass </code></pre> <p>I am getting the following error: <strong>NameError: name 'status' is not defined</strong> why is this? The <code>status</code> should be part of Request models right since I am inheriting from the <code>ApprovalMixin</code>. If I am wrong, Please help me out on how to make this work.</p>
-1
2016-07-20T06:51:16Z
38,475,054
<p>From django-fsm docs:</p> <pre><code> The field parameter accepts both a string attribute name or an actual field instance. </code></pre>
1
2016-07-20T07:33:36Z
[ "python", "django", "django-models" ]
Value Error: Extra Data error when importing json file using python
38,474,277
<p>I'm trying to build a python script that imports json files into a MongoDB. This part of my script keeps jumping to the <code>except ValueError</code> for larger json files. I think it has something to do with parsing the json file line by line because very small json files seem to work.</p> <pre><code>def read(jsonFiles): from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client[args.db] counter = 0 for jsonFile in jsonFiles: with open(jsonFile, 'r') as f: for line in f: # load valid lines (should probably use rstrip) if len(line) &lt; 10: continue try: db[args.collection].insert(json.loads(line)) counter += 1 except pymongo.errors.DuplicateKeyError as dke: if args.verbose: print "Duplicate Key Error: ", dke except ValueError as e: if args.verbose: print "Value Error: ", e # friendly log message if 0 == counter % 100 and 0 != counter and args.verbose: print "loaded line:", counter if counter &gt;= args.max: break </code></pre> <p>I'm getting the following error message:</p> <pre><code>Value Error: Extra data: line 1 column 10 - line 2 column 1 (char 9 - 20) Value Error: Extra data: line 1 column 8 - line 2 column 1 (char 7 - 18) </code></pre>
0
2016-07-20T06:54:57Z
38,475,616
<p>Look at this example:</p> <pre><code>s = """{ "data": { "one":1 } },{ "1": { "two":2 } }""" json.load( s ) </code></pre> <p>It will produce the "Extra data" error like in your json file:</p> <blockquote> <p>ValueError: Extra data: line 1 column 24 - line 1 column 45 (char 23 - 44)</p> </blockquote> <p>This is because this is not a valid JSON object. It contains two independend "dict"s, separated by a colon. Perhaps this could help you finding the error in your JSON file.</p> <p>in <a href="http://stackoverflow.com/questions/21058935/python-json-loads-shows-valueerror-extra-data">this post</a> you find more information. </p>
0
2016-07-20T08:00:59Z
[ "python", "json", "mongodb", "pymongo" ]
Value Error: Extra Data error when importing json file using python
38,474,277
<p>I'm trying to build a python script that imports json files into a MongoDB. This part of my script keeps jumping to the <code>except ValueError</code> for larger json files. I think it has something to do with parsing the json file line by line because very small json files seem to work.</p> <pre><code>def read(jsonFiles): from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client[args.db] counter = 0 for jsonFile in jsonFiles: with open(jsonFile, 'r') as f: for line in f: # load valid lines (should probably use rstrip) if len(line) &lt; 10: continue try: db[args.collection].insert(json.loads(line)) counter += 1 except pymongo.errors.DuplicateKeyError as dke: if args.verbose: print "Duplicate Key Error: ", dke except ValueError as e: if args.verbose: print "Value Error: ", e # friendly log message if 0 == counter % 100 and 0 != counter and args.verbose: print "loaded line:", counter if counter &gt;= args.max: break </code></pre> <p>I'm getting the following error message:</p> <pre><code>Value Error: Extra data: line 1 column 10 - line 2 column 1 (char 9 - 20) Value Error: Extra data: line 1 column 8 - line 2 column 1 (char 7 - 18) </code></pre>
0
2016-07-20T06:54:57Z
38,491,554
<p>Figured it out. Looks like breaking it up into lines was the mistake. Here's what the final code looks like.</p> <pre><code>counter = 0 for jsonFile in jsonFiles: with open(jsonFile) as f: data = f.read() jsondata = json.loads(data) try: db[args.collection].insert(jsondata) counter += 1 </code></pre>
0
2016-07-20T21:58:36Z
[ "python", "json", "mongodb", "pymongo" ]
How to use my own classifier in ensemble python
38,474,294
<p>The main aim is to add a deep learning classification method like <a href="https://github.com/Newmu/Theano-Tutorials/blob/master/5_convolutional_net.py" rel="nofollow">CNN</a> as an individual in ensemble in python.<br> The following code works fine:</p> <pre><code> clf1=CNN() eclf1=VotingClassifier(estimators=[('lr', clf1)], voting='soft') eclf1=eclf1.fit(XTrain,YTrain) </code></pre> <p>But, the error: </p> <pre><code>'NoneType' object has no attribute 'predict_proba' </code></pre> <p>comes up once running <code>eclf1=eclf1.predict(XTest)</code>.</p> <p>Just in case, The <code>CNN</code> consists of <code>_fit_</code> function for training, and the following function:</p> <pre><code>def predict_proba(self,XTest): #prediction=np.mean(np.argmax(teY, axis=1) == predict(teX)) teX=XTest.reshape(len(XTest),3,112,112) p=predict(teX) i = np.zeros((p.shape[0],p.max()+1)) for x,y in enumerate(p): i[x,y] = 1 return i </code></pre>
0
2016-07-20T06:55:41Z
39,400,224
<p>Can you elaborate better what you did and which error you came across?</p> <p>By your question only I can assume you tried to call 'predic_proba' after the line <code>eclf1=eclf1.predict(XTest)</code>. And of course this will turn on an error because the <code>eclf1.predict(XTest)</code> returns an array, which doesn't have a predict() method. Try just changing it to: </p> <pre><code>pred_results=eclf1.predict(XTest) pred_result_probs = eclf1.predict_proba(XTest) </code></pre>
0
2016-09-08T21:07:39Z
[ "python", "classification", "ensemble-learning", "sklearn-pandas" ]
Splitting a string using re module of python
38,474,353
<p>I have a string</p> <pre class="lang-py prettyprint-override"><code>s = 'count_EVENT_GENRE in [1,2,3,4,5]' #I have to capture only the field 'count_EVENT_GENRE' field = re.split(r'[(==)(&gt;=)(&lt;=)(in)(like)]', s)[0].strip() #o/p is 'cou' # for s = 'sum_EVENT_GENRE in [1,2,3,4,5]' o/p = 'sum_EVENT_GENRE' </code></pre> <p>which is fine</p> <p>My doubt is for any character in <code>(in)(like)</code> it is splitting the string <code>s</code> at that character and giving me first slice.(as after "cou" it finds one matching char i:e <code>n</code>). It's happening for any string that contains any character from <code>(in)(like)</code>.</p> <p>Ex : <code>'percentage_AMOUNT' o/p = 'p'</code> </p> <p>as it finds a matching char as 'e' after <code>p</code>.</p> <p>So i want some advice how to treat (in)(like) as words not as characters , when splitting occurs/matters.</p> <p>please suggest a syntax.</p>
1
2016-07-20T06:58:54Z
38,474,549
<p>Answering your question, the <code>[(==)(&gt;=)(&lt;=)(in)(like)]</code> is a character class matching single characters you defined inside the class. To match sequences of characters, you need to remove <code>[</code> and <code>]</code> and use alternation:</p> <pre><code>r'==?|&gt;=?|&lt;=?|\b(?:in|like)\b' </code></pre> <p>or better:</p> <pre><code>r'[=&gt;&lt;]=?|\b(?:in|like)\b' </code></pre> <p>You <a href="https://ideone.com/gAAfsZ" rel="nofollow">code</a> would look like:</p> <pre><code>import re ss = ['count_EVENT_GENRE in [1,2,3,4,5]','coint_EVENT_GENRE = "ROMANCE"'] for s in ss: field = re.split(r'[=&gt;&lt;]=?|\b(?:in|like)\b', s)[0].strip() print(field) </code></pre> <p>However, there might be other (easier, or safer - depending on the actual specifications) ways to get what you want (splitting with space and getting the first item, use <code>re.match</code> with <code>r'\w+'</code> or <code>r'[a-z]+(?:_[A-Z]+)+'</code>, etc.)</p> <p><strong>If your value is at the start of the string and starts with lowercase ASCII letters, and then can have any amount of sequences of <code>_</code> followed with uppercase ASCII letters</strong>, use:</p> <pre><code>re.match(r'[a-z]+(?:_[A-Z]+)*', s) </code></pre> <p><a href="https://ideone.com/vJThVZ" rel="nofollow">Full demo code</a>:</p> <pre><code>import re ss = ['count_EVENT_GENRE in [1,2,3,4,5]','coint_EVENT_GENRE = "ROMANCE"'] for s in ss: fieldObj = re.match(r'[a-z]+(?:_[A-Z]+)*', s) if fieldObj: print(fieldObj.group()) </code></pre>
1
2016-07-20T07:08:42Z
[ "python", "regex", "string" ]
Splitting a string using re module of python
38,474,353
<p>I have a string</p> <pre class="lang-py prettyprint-override"><code>s = 'count_EVENT_GENRE in [1,2,3,4,5]' #I have to capture only the field 'count_EVENT_GENRE' field = re.split(r'[(==)(&gt;=)(&lt;=)(in)(like)]', s)[0].strip() #o/p is 'cou' # for s = 'sum_EVENT_GENRE in [1,2,3,4,5]' o/p = 'sum_EVENT_GENRE' </code></pre> <p>which is fine</p> <p>My doubt is for any character in <code>(in)(like)</code> it is splitting the string <code>s</code> at that character and giving me first slice.(as after "cou" it finds one matching char i:e <code>n</code>). It's happening for any string that contains any character from <code>(in)(like)</code>.</p> <p>Ex : <code>'percentage_AMOUNT' o/p = 'p'</code> </p> <p>as it finds a matching char as 'e' after <code>p</code>.</p> <p>So i want some advice how to treat (in)(like) as words not as characters , when splitting occurs/matters.</p> <p>please suggest a syntax.</p>
1
2016-07-20T06:58:54Z
38,474,551
<p>If you want only the first word of your string, then this should do the job:</p> <pre><code>import re s = 'count_EVENT_GENRE in [1,2,3,4,5]' field = re.split(r'\W', s)[0] # count_EVENT_GENRE </code></pre>
1
2016-07-20T07:08:47Z
[ "python", "regex", "string" ]
Splitting a string using re module of python
38,474,353
<p>I have a string</p> <pre class="lang-py prettyprint-override"><code>s = 'count_EVENT_GENRE in [1,2,3,4,5]' #I have to capture only the field 'count_EVENT_GENRE' field = re.split(r'[(==)(&gt;=)(&lt;=)(in)(like)]', s)[0].strip() #o/p is 'cou' # for s = 'sum_EVENT_GENRE in [1,2,3,4,5]' o/p = 'sum_EVENT_GENRE' </code></pre> <p>which is fine</p> <p>My doubt is for any character in <code>(in)(like)</code> it is splitting the string <code>s</code> at that character and giving me first slice.(as after "cou" it finds one matching char i:e <code>n</code>). It's happening for any string that contains any character from <code>(in)(like)</code>.</p> <p>Ex : <code>'percentage_AMOUNT' o/p = 'p'</code> </p> <p>as it finds a matching char as 'e' after <code>p</code>.</p> <p>So i want some advice how to treat (in)(like) as words not as characters , when splitting occurs/matters.</p> <p>please suggest a syntax.</p>
1
2016-07-20T06:58:54Z
38,474,941
<p>Is there anything wrong with using <code>split</code>? </p> <pre><code>&gt;&gt;&gt; s = 'count_EVENT_GENRE in [1,2,3,4,5]' &gt;&gt;&gt; s.split(' ')[0] 'count_EVENT_GENRE' &gt;&gt;&gt; s = 'coint_EVENT_GENRE = "ROMANCE"' &gt;&gt;&gt; s.split(' ')[0] 'coint_EVENT_GENRE' &gt;&gt;&gt; </code></pre>
1
2016-07-20T07:28:57Z
[ "python", "regex", "string" ]
MemoryError in Python 2.7 when iterating over a large file word by word
38,474,476
<p>I need to read a large file multiple times and need access to the total number of words in the file. I've implemented a wrapper class that contains an iterator, a copy of the iterator (to reset the iterator) and its length:</p> <pre><code>Class DataWrapper(object): def __init__(self, data): self.data, self.copy = itertools.tee(data) self.length = None def __iter__(self): return self.data def next(self): return self.data.next() def reset(self): self.data, self.copy = itertools.tee(self.copy) def __len__(self): if self.length is None: self.data, dcopy = itertools.tee(self.data) self.length = sum(1 for x in dcopy) return self.length </code></pre> <p>I then create the actual file reading iterator and start iterating:</p> <pre><code>def my_iter(fname): with open(fname, 'r') as f: for line in f: for word in line.split(): yield word dw = DataWrapper(my_iter("large_file.txt")) for w in dw: pass </code></pre> <p>For some reason though, I get a <code>MemoryError</code> while iterating:</p> <p>File "my_script.py", line 164, in my_iter for line in f: MemoryError</p> <p>Since this does not happen without the wrapper, I assume <a href="https://docs.python.org/3/library/itertools.html#itertools.tee" rel="nofollow"><code>itertools.tee</code></a> is to blame. But is there another way to reset the iterator?</p>
0
2016-07-20T07:05:28Z
38,475,097
<p>The problem here is that if the data is only read once, and must be iterated multiple times, it has to been kept in memory. If the file is large enough to exhaust the memory you will end with a MemoryError. Here the <code>itertool.tee</code> is indeed the culprit, even if IMHO it is not to blame for it because it has no other way to do ;-)</p> <p>If you cannot keep the data in memory, the only foolproof way would be to open a new file handler for each iterator - provided the OS and file system allow it. That way the memory will only contain one buffer and one line per iterator instead of the whole file.</p>
2
2016-07-20T07:36:01Z
[ "python", "iterator", "out-of-memory" ]
How to pass argument to subprocess using gksudo?
38,474,496
<p><strong>Data of FirstFile.py<br></strong></p> <pre><code>a=raw_input("Anything") p=subprocess.Popen(['gksudo','python','file1.py'],stdin=subprocess.PIPE).communicate(a)&lt;br&gt; #some related codes </code></pre> <p><strong>Data of file1.py<br></strong></p> <pre><code>pro=sys.stdin.read()&lt;br&gt; sys.stdout.write('received data %s' %pro)&lt;br&gt; </code></pre> <p>file1.py gives the output: "<strong>received data</strong>"<br> It does not show the actual data received.<br> When I make use of only 'sudo' instead of 'gksudo' it works absolutely fine. Please suggest how it can be modified. </p>
0
2016-07-20T07:06:09Z
38,474,641
<p>Because,</p> <p><code>gksudo</code> is used to run graphical (GUI) applications as root and <code>sudo</code> is used to run command line applications as root. Here you using command line application. So you have to use <code>sudo</code>. </p>
0
2016-07-20T07:13:09Z
[ "python", "subprocess" ]
Elementtree and xsd sequences
38,474,565
<p>I'm currently writing a code generator that produces <a href="http://www.plcopen.org/pages/tc6_xml/" rel="nofollow">PLCOpen XML files</a>. The Schema uses sequences in some places. The code generator uses <code>ElementTree</code> because of its simple interface. However, I can't find a way to make <code>ElementTree</code> respect the sequence; in fact, the children of an <code>Element</code> are always printed in canonical order. Is there any way around this?</p>
0
2016-07-20T07:09:21Z
38,474,917
<p>The method <code>ElementTree.append</code> that I used does not seem to keep the elements ordered. Using <code>ElementTree.insert</code>, however, solved the issue.</p>
0
2016-07-20T07:28:05Z
[ "python", "xml", "xsd", "elementtree" ]
Error:not all arguments converted during string formatting
38,474,576
<p>I have this signup page and when i am submitting the form i am getting this error:not all arguments converted during string formatting</p> <pre><code>class RegistrationForm(Form): email = StringField('Email address') password = PasswordField('password') name = StringField('Name') @app.route('/register/', methods=['GET', 'POST']) def register(): try: form = RegistrationForm(request.form) if request.method == 'POST': email = form.email.data password = sha256_crypt.encrypt((str(form.password.data))) con = connection() cur=con.cursor() x = cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email))) if int(x) &gt; 0: return render_template('register.html',form=form) else: cur.execute("INSERT INTO user (username,password,name) VALUES (%s,%s,%s);",(thwart(email),thwart(password),thwart(name),)) con.commit() cur.close() con.close() return redirect(url_for('dashboard')) return render_template('register.html', form=form) except Exception as e: return str(e) </code></pre>
1
2016-07-20T07:09:59Z
38,474,692
<p><code>x = cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email)))</code> </p> <p>The second argument of <code>execute</code> should be a tuple, you are missing a <code>,</code>: </p> <p><code>cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email),))</code></p> <p>I guess that you also don't need the <code>()</code> around the <code>%s</code> but it depends on how your table actually looks like.</p> <p>Further clarification:</p> <p><code>('str')</code> will evaluate to the string <code>'str'</code>, not to a tuple containing it.</p> <p>In order to create a one-tuple, you must include a comma: <code>('str',)</code>. </p>
1
2016-07-20T07:16:18Z
[ "python", "mysql", "mysql-python" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: print(letter) #lists down Outcome- Write something- test t e s t </code></pre> <p>Then I have this code that changes the letters into numbers, but I haven't been able to convert it back into letters. Code #2</p> <pre><code>u = input('Write Something') a = ord(u[-1]) print(a) #converts to number and prints ^^ enter code here print('') print(????) #need to convert from numbers back to letters. Outcome: Write Something- test 116 </code></pre> <p>How can I send a text through (test) and make it convert it to either set numbers (a->1, b->2) or random numbers, save it to a .txt file and be able to go back and read it at any time?</p>
-1
2016-07-20T07:12:26Z
38,474,895
<p>Just use <code>dictionary</code>:</p> <pre><code> letters = {'a': 1, 'b': 2, ... } </code></pre> <p>And in the loop:</p> <pre><code>for letter in word: print(letters[letter]) </code></pre>
0
2016-07-20T07:26:38Z
[ "python", "python-3.x" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: print(letter) #lists down Outcome- Write something- test t e s t </code></pre> <p>Then I have this code that changes the letters into numbers, but I haven't been able to convert it back into letters. Code #2</p> <pre><code>u = input('Write Something') a = ord(u[-1]) print(a) #converts to number and prints ^^ enter code here print('') print(????) #need to convert from numbers back to letters. Outcome: Write Something- test 116 </code></pre> <p>How can I send a text through (test) and make it convert it to either set numbers (a->1, b->2) or random numbers, save it to a .txt file and be able to go back and read it at any time?</p>
-1
2016-07-20T07:12:26Z
38,474,943
<p>What youre trying to achieve here is called "caesar encryption".</p> <p>You for example say normally you would have: A=1, a=2, B=3, B=4, etc...</p> <p>then you would have a "key" which "shifts" the letters. Lets say the key is "3", so you would shift all letters 3 numbers up and you would end up with: A=4, a=5, B=6, b=7, etc...</p> <p>This is of course only ONE way of doing a caesar encryption. This is the most basic example. You could also say your key is "G", which would give you:</p> <p>A=G, a=g, B=H, b=h, etc.. or<br> A=G, a=H, B=I, b=J, etc...</p> <p>Hope you understand what im talking about. Again, this is only one very simple example way. </p> <p>Now, for your program/script you need to define this key. And if the key should be variable, you need to save it somewhere (write it down). Put your words in a string, and check and convert each letter and write it into a new string.</p> <p>You then could say (pseudo code!):</p> <pre><code>var key = READKEYFROMFILE; string old = READKEYFROMFILE_OR_JUST_A_NORMAL_STRING_:) string new = ""; for (int i=0, i&lt;old.length, i++){ get the string at i; compare with your "key"; shift it; write it in new; } </code></pre> <p>Hope i could help you.</p> <p>edit:</p> <p>You could also use a dictionary (like the other answer says), but this is a very static (but easy) way.</p> <p>Also, maybe watch some guides/tutorials on programming. You dont seem to be that experienced. And also, google "Caesar encryption" to understand this topic better (its very interesting). </p> <p>edit2:</p> <p>Ok, so basically:</p> <p>You have a variable, called "key" in this variable, you store your key (you understood what i wrote above with the key and stuff?)</p> <p>You then have a string variable, called "old". And another one called "new". </p> <p>In old, you write your string that you want to convert. New will be empty for now. </p> <p>You then do a "for loop", which goes as long as the ".length" of your "old" string. (that means if your sentence has 15 letters, the loop will go through itself 15 times and always count the little "i" variable (from the for loop) up).</p> <p>You then need to try and get the letter from "old" (and save it for short in another vairable, for example <code>char temp = ""</code> ).</p> <p>After this, you need to compare your current letter and decide how to shift it. If thats done, just add your converted letter to the "new" string. </p> <p>Here is some more precise pseudo code (its not python code, i dont know python well), btw char stands for "character" (letter):</p> <pre><code>var key = g; string old = "teststring"; string new = ""; char oldchar = ""; char newchar = ""; for (int i=0; i&lt;old.length; i++){ oldchar = old.charAt[i]; newchar = oldchar //shift here!!! new.addChar(newchar); } </code></pre> <p>Hope i could help you ;)</p> <p>edit3:</p> <p>maybe also take a look at this:</p> <p><a href="https://inventwithpython.com/chapter14.html" rel="nofollow">https://inventwithpython.com/chapter14.html</a></p> <p><a href="http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python">Caesar Cipher Function in Python</a></p> <p><a href="https://www.youtube.com/watch?v=WXIHuQU6Vrs" rel="nofollow">https://www.youtube.com/watch?v=WXIHuQU6Vrs</a></p>
0
2016-07-20T07:29:01Z
[ "python", "python-3.x" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: print(letter) #lists down Outcome- Write something- test t e s t </code></pre> <p>Then I have this code that changes the letters into numbers, but I haven't been able to convert it back into letters. Code #2</p> <pre><code>u = input('Write Something') a = ord(u[-1]) print(a) #converts to number and prints ^^ enter code here print('') print(????) #need to convert from numbers back to letters. Outcome: Write Something- test 116 </code></pre> <p>How can I send a text through (test) and make it convert it to either set numbers (a->1, b->2) or random numbers, save it to a .txt file and be able to go back and read it at any time?</p>
-1
2016-07-20T07:12:26Z
38,474,998
<p>To convert to symbol codes and back to characters:</p> <pre><code>text = input('Write Something') for t in text: d = ord(t) n = chr(d) print(t,d,n) </code></pre> <p>To write into file:</p> <pre><code>f = open("a.txt", "w") f.write("someline\n") f.close() </code></pre> <p>To read lines from file:</p> <pre><code>f = open("a.txt", "r") lines = f.readlines() for line in lines: print(line, end='') # all lines have newline character at the end f.close() </code></pre> <p>Please see documentation for Python 3: <a href="https://docs.python.org/3/" rel="nofollow">https://docs.python.org/3/</a></p>
0
2016-07-20T07:31:28Z
[ "python", "python-3.x" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: print(letter) #lists down Outcome- Write something- test t e s t </code></pre> <p>Then I have this code that changes the letters into numbers, but I haven't been able to convert it back into letters. Code #2</p> <pre><code>u = input('Write Something') a = ord(u[-1]) print(a) #converts to number and prints ^^ enter code here print('') print(????) #need to convert from numbers back to letters. Outcome: Write Something- test 116 </code></pre> <p>How can I send a text through (test) and make it convert it to either set numbers (a->1, b->2) or random numbers, save it to a .txt file and be able to go back and read it at any time?</p>
-1
2016-07-20T07:12:26Z
38,476,458
<p>Here are a couple of examples. My method involves mapping the character to the string representation of an integer padded with zeros so it's 3 characters long using <code>str.zfill</code>.</p> <p>Eg <code>0 -&gt; '000', 42 -&gt; '042', 125 -&gt; '125'</code></p> <p>This makes it much easier to convert a string of numbers back to characters since it will be in lots of 3</p> <p>Examples</p> <pre><code>from string import printable #'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~ \t\n\r\x0b\x0c' from random import sample # Option 1 char_to_num_dict = {key : str(val).zfill(3) for key, val in zip(printable, sample(range(1000), len(printable))) } # Option 2 char_to_num_dict = {key : str(val).zfill(3) for key, val in zip(printable, range(len(printable))) } # Reverse mapping - applies to both options num_to_char_dict = {char_to_num_dict[key] : key for key in char_to_num_dict } </code></pre> <p>Here are two sets of dictionaries to map a character to a number. The first option uses random numbers eg <code>'a' = '042', 'b' = '756', 'c' = '000'</code> the problem with this is you can use it one time, close the program and then the next time the mapping will most definitely not match. If you want to use random values then you will need to save the dictionary to a file so you can open to get the key.</p> <p>The second option creates a dictionary mapping a character to a number and maintains order. So it will follow the sequence eg <code>'a' = '010', 'b' = '011', 'c' = '012'</code> everytime.</p> <p>Now I've explained the mapping choices here are the function to convert between</p> <pre><code>def text_to_num(s): return ''.join( char_to_num_dict.get(char, '') for char in s ) def num_to_text(s): slices = [ s[ i : i + 3 ] for i in range(0, len(s), 3) ] return ''.join( num_to_char_dict.get(char, '') for char in slices ) </code></pre> <p>Example of use ( with option 2 dictionary )</p> <pre><code>&gt;&gt;&gt; text_to_num('Hello World!') '043014021021024094058024027021013062' &gt;&gt;&gt; num_to_text('043014021021024094058024027021013062') 'Hello World!' </code></pre> <p>And finally if you don't want to use a dictionary then you can use <code>ord</code> and <code>chr</code> still keeping with padding out the number with zeros method</p> <pre><code>def text_to_num2(s): return ''.join( str(ord(char)).zfill(3) for char in s ) def num_to_text2(s): slices = [ s[ i : i + 3] for i in range(0, len(s), 3) ] return ''.join( chr(int(val)) for val in slices ) </code></pre> <p>Example of use</p> <pre><code>&gt;&gt;&gt; text_to_num2('Hello World!') '072101108108111032087111114108100033' &gt;&gt;&gt; num_to_text2('072101108108111032087111114108100033') 'Hello World!' </code></pre>
0
2016-07-20T08:44:55Z
[ "python", "python-3.x" ]
Sqlalchemy - how to fix '_sa_instance_state'
38,474,742
<p>I have a folder containing over 200 000 json files. Each json object is a Tweet (twitter). I'm getting an error while saving a tweet into the db</p> <pre><code>#sqlalchemy_insert.py def create_new_tweet(data, new_user): """ insert new tweet into db """ #tweet tweet_id = data.get('id') language = data.get('lang', 'en') tweet_text = data.get('text') in_reply_to_user = data.get('in_reply_to_user_id') coord = check_if_it_s_null(data.get('coordinates')) geo_location = check_if_it_s_null(data.get('geo')) created_at = parse(data.get('created_at')) try: new_tweet = Tweet(id=tweet_id, tweet=tweet_text, lang=language,created_at=created_at, geo=geo_location, coordinates=coord, user=new_user) session.add(new_tweet) except: import ipdb; ipdb.set_trace() session.commit() return new_tweet </code></pre> <p>I'm getting an error on this line <code>session.add(new_tweet)</code> </p> <pre><code>ipdb&gt; session.add(new_tweet) *** AttributeError: 'Query' object has no attribute '_sa_instance_state' </code></pre> <p>I added a <code>try</code> to be able to debug but I have no clue how to insert this tweet to this db. this problem occurs after inserting the 153th tweet </p> <p><a href="https://github.com/guinslym/dr_elizabeth_database/blob/master/sqlalchemy_insert.py" rel="nofollow">complete gist - line 85</a></p>
0
2016-07-20T07:18:20Z
38,475,220
<p><code>create_new_user</code> returns <code>Query</code> object if user exists</p> <pre><code>new_user = session.query(User).filter(User.id == user_id) # it's a query </code></pre> <p>but you need to pass <code>User</code> object to <code>create_new_tweet</code>.</p> <p>You can do something like this</p> <pre><code>def create_new_user(data): s_name = (data.get('user').get('screen_name')) user_name = (data.get('user').get('name')) user_id = (data.get('user').get('id')) new_user = session.query(User).filter(User.id == user_id).first() # it's a User object if new_user is None: new_user = User(id=user_id, name=user_name, screen_name=s_name) session.add(new_user) session.commit() #creating a profile create_new_profile(data, new_user) return new_user </code></pre>
1
2016-07-20T07:41:27Z
[ "python", "twitter", "sqlalchemy" ]
Pandas dataframe pivoting
38,474,807
<p>I have the following <code>pandas DataFrame</code>:</p> <pre><code> id quantity cost type 2016-06-18 1700057817 2 2383 A 2016-06-18 1700057817 1 744 B 2016-06-19 1700057817 5 934 A </code></pre> <p>Here, the dates are the <code>index</code>. I need the table to be pivoted like this:</p> <pre><code> id A-quantity A-cost B-quantity B-cost 2016-06-18 1700057817 2 2383 1 744 2016-06-19 1700057817 5 934 NA NA </code></pre> <p><strong>What I've tried so far:</strong></p> <p>I've tried many usages of <code>pivot</code>. This is as close as I've gotten:</p> <pre><code>&gt;&gt;&gt; df.pivot(index='id', columns='type') quantity cost type A B A B id 1700057817 2 1 2383 744 </code></pre> <p>Problems with this:</p> <ol> <li><code>date</code> index is gone</li> <li>I needed a row per <code>date</code>-<code>id</code> combination</li> </ol> <p>I've also gone through several articles on SO and elsewhere, including <a href="http://stackoverflow.com/questions/31146338/pandas-dataframe-pivot-using-dates-and-counts">this one</a>.</p>
3
2016-07-20T07:22:22Z
38,475,903
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> to preserve dates.</p> <pre><code>df.index.name = 'date' df = df.reset_index().pivot_table(index=['date', 'id'], columns=['type']) df = df.sort_index(axis=1, level=1) df.columns = ['-'.join(tup[::-1]) for tup in df.columns] </code></pre>
1
2016-07-20T08:16:10Z
[ "python", "pandas", "dataframe" ]
Pandas dataframe pivoting
38,474,807
<p>I have the following <code>pandas DataFrame</code>:</p> <pre><code> id quantity cost type 2016-06-18 1700057817 2 2383 A 2016-06-18 1700057817 1 744 B 2016-06-19 1700057817 5 934 A </code></pre> <p>Here, the dates are the <code>index</code>. I need the table to be pivoted like this:</p> <pre><code> id A-quantity A-cost B-quantity B-cost 2016-06-18 1700057817 2 2383 1 744 2016-06-19 1700057817 5 934 NA NA </code></pre> <p><strong>What I've tried so far:</strong></p> <p>I've tried many usages of <code>pivot</code>. This is as close as I've gotten:</p> <pre><code>&gt;&gt;&gt; df.pivot(index='id', columns='type') quantity cost type A B A B id 1700057817 2 1 2383 744 </code></pre> <p>Problems with this:</p> <ol> <li><code>date</code> index is gone</li> <li>I needed a row per <code>date</code>-<code>id</code> combination</li> </ol> <p>I've also gone through several articles on SO and elsewhere, including <a href="http://stackoverflow.com/questions/31146338/pandas-dataframe-pivot-using-dates-and-counts">this one</a>.</p>
3
2016-07-20T07:22:22Z
38,476,062
<p>You could <code>set_index</code> with <code>append=True</code> followed by <code>unstack</code> and keep the <code>MultiIndex</code>:</p> <pre><code>df.set_index(['id', 'type'], append=True).unstack() </code></pre> <p><a href="http://i.stack.imgur.com/0uM8c.png" rel="nofollow"><img src="http://i.stack.imgur.com/0uM8c.png" alt="enter image description here"></a></p> <p>Or forcibly reformat to what you asked for:</p> <pre><code># step-one same as above df1 = df.set_index(['id', 'type'], append=True).unstack() # collapse MultiIndex columns into '-' separated string df1.columns = df1.columns.swaplevel(0, 1).to_series().str.join('-') # move 'Id' from the index back into dataframe proper df1 = df1.reset_index(1) df1 </code></pre> <p><a href="http://i.stack.imgur.com/S9z43.png" rel="nofollow"><img src="http://i.stack.imgur.com/S9z43.png" alt="enter image description here"></a></p>
3
2016-07-20T08:24:55Z
[ "python", "pandas", "dataframe" ]
Making Matplotlib and GTK3 work on python3 windows
38,475,134
<p>I'm trying to make GTK3 and Python3 work under windows to my project.</p> <p>I have an continuum anaconda setup with a 32-bit python 3.4 and Matplotib via conda install matplotlib.</p> <p>I've installed PyGobject(<a href="https://sourceforge.net/projects/pygobjectwin32/" rel="nofollow">https://sourceforge.net/projects/pygobjectwin32/</a>) and installed GTK+ / Glade via the installer.</p> <p>The basic exemple from the GTK3 tutorial works well (empty screen)</p> <pre><code>import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk win = Gtk.Window() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() </code></pre> <p>I want now to embed matplotlib in gtk, I got the example from matplotlib (<a href="http://matplotlib.org/examples/user_interfaces/embedding_in_gtk3.html" rel="nofollow">http://matplotlib.org/examples/user_interfaces/embedding_in_gtk3.html</a>)</p> <p>I saw then that I needed cairocffi because some incompabilities. (PyCairo has no support for a matplotlib function)</p> <p>I got the windows binaries for cffi from Gohlke </p> <p>And finnaly did a </p> <pre><code>pip install cairocffi </code></pre> <p>And now I just get a python.exe stopped working.</p> <p>Tried with GTK3agg and GTK3Cairo backends and I have the same result</p> <p>Looking around I found that maybe the cairo version is outdated for the functions used by matplotlib, but I dont know how to proceed.</p> <p>Cairocffi works if I try running something else.</p> <p><strong>More information</strong> (from the comment below):</p> <p>I still got an unhandled win32 error. I managed to open the error and it says: </p> <pre><code>Unhandled exception at 0x08CF6D58 (libcairo-2.dll) in python.exe: 0xC0000005: Access violation reading location 0x000000A8. If there is a handler for this exception, the program may be safely continued. </code></pre> <p>It just crashes...</p>
0
2016-07-20T07:37:32Z
38,484,297
<p>I've had my share of problems using <code>matplotlib</code> in <code>Python3 + Gtk3</code>. I found <a href="http://gtk3-matplotlib-cookbook.readthedocs.io/en/latest/hello-plot.html#embedding-matplotlib" rel="nofollow">this cookbook page</a> with working examples. Try to run the examples in the cookbook - particularly the simplest one:</p> <pre><code>#!/usr/bin/python3 from gi.repository import Gtk from matplotlib.figure import Figure from numpy import arange, pi, random, linspace import matplotlib.cm as cm #Possibly this rendering backend is broken currently #from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas myfirstwindow = Gtk.Window() myfirstwindow.connect("delete-event", Gtk.main_quit) myfirstwindow.set_default_size(400, 400) fig = Figure(figsize=(5,5), dpi=100) ax = fig.add_subplot(111, projection='polar') N = 20 theta = linspace(0.0, 2 * pi, N, endpoint=False) radii = 10 * random.rand(N) width = pi / 4 * random.rand(N) bars = ax.bar(theta, radii, width=width, bottom=0.0) for r, bar in zip(radii, bars): bar.set_facecolor(cm.jet(r / 10.)) bar.set_alpha(0.5) ax.plot() sw = Gtk.ScrolledWindow() myfirstwindow.add(sw) canvas = FigureCanvas(fig) canvas.set_size_request(400,400) sw.add_with_viewport(canvas) myfirstwindow.show_all() Gtk.main() </code></pre> <p>Also, not that you need a fairly recent version of <code>matplotlib</code> to make things work on <code>Python3</code>.</p> <p>If you still have problems, please show us the complete error message.</p> <p>Note: I tested this on Linux (don't have Windows), but, from you description of problems, the issue is (was) a common one.</p>
0
2016-07-20T14:38:21Z
[ "python", "matplotlib", "networkx", "gtk3", "cairo" ]
creating a string character as a default parameter for function
38,475,158
<p>Good morning,</p> <p>At the moment I am trying to create a histogram for class. I am now developing my skill as I have only been doing this for 2 months, and as I do know this is a website for professionals, and please you to excuse my lack of understanding.</p> <pre><code>def histo_print(times, dicerand, symbol='*'): print('%ds: %s' % (times, (dicerand * symbol))) </code></pre> <p>Question:</p> <ol> <li><p>Is it possible to use a string as a default for "symbol"?</p></li> <li><p>Would I be better off by assigning a default string character to the "symbol" variable outside of the loop? Then place an input function after assigning it?</p></li> </ol> <p>I have not found a previous question asked that is similar to the one I am asking now. <strong>Please if anyone is aware of where this question has been answered please post the url</strong>, I prefer to research than be given the answer; however, I have not much time left to finish. Thank you in advance for your assistance.</p> <p>This is the whole code:</p> <pre><code>def histo_print(times,dicerand,symbol): if symbol == none print ('%ds: %s' % (times,(dicerand * symbol))) def rand(user_input): number = 0 while number != user_input: die1 = random.randint(1, 6) die2 = random.randint(1, 6) roll_total = die1 + die2 return roll_total """Introduction""" print('Welcome to the Dice roll histogram.') if num_rolls &gt;= 1: """Adds one to user input because the for loop starts at one.""" num_rolls += 1 """Optional Secondary input based on if the number entered is greater than zero.""" character = str(input('Please enter character:\n')) # Additional input for user choice. """Unnecessary, just looks nice.""" print('Dice roll histogram:\n') for i in range(1,num_rolls): rand(num_rolls) #Output histo_print(i, rand(num_rolls),character) else: print('Invalid number of rolls. Try again.') </code></pre>
0
2016-07-20T07:38:46Z
38,475,490
<p>To answer your first question, yes. Yes, you can absolutely use a string value to pass off as a "default" in your function. For starters, take a quick read here to avoid common gotchas ==> <a href="http://docs.python-guide.org/en/latest/writing/gotchas/" rel="nofollow">http://docs.python-guide.org/en/latest/writing/gotchas/</a> . In your case, I would keep it as such.</p> <p>Now for your next question, while you can absolutely place this "default" value in your for loop. However, the rule of thumb is, for the sake of readability, place these default values in functions and override as needed.</p>
1
2016-07-20T07:55:09Z
[ "python", "python-3.x" ]
Cannot pip install the python module tables
38,475,159
<p>I am trying to install tables so an existing python script does not complain when it tries to 'import tables'</p> <pre><code>pip install tables </code></pre> <p>Here is the output:</p> <pre><code>Collecting tables Using cached tables-3.2.3.1.tar.gz Requirement already satisfied (use --upgrade to upgrade): numpy&gt;=1.8.0 in ./miniconda/envs/optimus/lib/python2.7/site-packages (from tables) Requirement already satisfied (use --upgrade to upgrade): numexpr&gt;=2.5.2 in ./miniconda/envs/optimus/lib/python2.7/site-packages (from tables) Installing collected packages: tables Running setup.py install for tables: started Running setup.py install for tables: finished with status 'error' Complete output from command /home/jonathonhill/miniconda/envs/optimus/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-jcuNfM/tables/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ofzTc6-record/install-record.txt --single-version-externally-managed --compile: * Using Python 2.7.8 |Continuum Analytics, Inc.| (default, Aug 21 2014, 18:22:21) * USE_PKGCONFIG: True * pkg-config header dirs for HDF5: /usr/include/hdf5/serial * pkg-config library dirs for HDF5: /usr/lib/x86_64-linux-gnu/hdf5/serial * Found HDF5 headers at ``/usr/include/hdf5/serial``, library at ``/usr/lib/x86_64-linux-gnu/hdf5/serial``. .. WARNING:: Could not find the HDF5 runtime. The HDF5 shared library was *not* found in the default library paths. In case of runtime problems, please remember to install it. /tmp/lzo_version_dateanObdP.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/lzo_version_dateanObdP.c: In function âmainâ: /tmp/lzo_version_dateanObdP.c:2:5: warning: implicit declaration of function âlzo_version_dateâ [-Wimplicit-function-declaration] lzo_version_date(); ^ * Could not find LZO 2 headers and library; disabling support for it. /tmp/lzo_version_datedINlTK.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/lzo_version_datedINlTK.c: In function âmainâ: /tmp/lzo_version_datedINlTK.c:2:5: warning: implicit declaration of function âlzo_version_dateâ [-Wimplicit-function-declaration] lzo_version_date(); ^ * Could not find LZO 1 headers and library; disabling support for it. /tmp/BZ2_bzlibVersionL7B4pC.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/BZ2_bzlibVersionL7B4pC.c: In function âmainâ: /tmp/BZ2_bzlibVersionL7B4pC.c:2:5: warning: implicit declaration of function âBZ2_bzlibVersionâ [-Wimplicit-function-declaration] BZ2_bzlibVersion(); ^ * Found bzip2 headers at ``/usr/include``, the library is located in the standard system search dirs. /tmp/blosc_list_compressorsQc0Mok.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/blosc_list_compressorsQc0Mok.c: In function âmainâ: /tmp/blosc_list_compressorsQc0Mok.c:2:5: warning: implicit declaration of function âblosc_list_compressorsâ [-Wimplicit-function-declaration] blosc_list_compressors(); ^ * Could not find blosc headers and library; using internal sources. </code></pre> <p>I gather from this that I am missing a HDF5 shared library. How can I fix this error / install any necessary dependencies.</p>
0
2016-07-20T07:38:46Z
38,475,337
<p>Your log explicitly tell what's wrong:</p> <blockquote> <p>WARNING:: Could not find the HDF5 runtime.</p> </blockquote> <p>Try this:</p> <pre><code>sudo python setup.py build_ext --inplace --hdf5=/opt/local --lzo=/opt/local --bzip2==opt/local sudo python setup.py install --hdf5=/opt/local --lzo=/opt/local --bzip2==opt/local </code></pre>
0
2016-07-20T07:47:23Z
[ "python", "pytables" ]
Cannot pip install the python module tables
38,475,159
<p>I am trying to install tables so an existing python script does not complain when it tries to 'import tables'</p> <pre><code>pip install tables </code></pre> <p>Here is the output:</p> <pre><code>Collecting tables Using cached tables-3.2.3.1.tar.gz Requirement already satisfied (use --upgrade to upgrade): numpy&gt;=1.8.0 in ./miniconda/envs/optimus/lib/python2.7/site-packages (from tables) Requirement already satisfied (use --upgrade to upgrade): numexpr&gt;=2.5.2 in ./miniconda/envs/optimus/lib/python2.7/site-packages (from tables) Installing collected packages: tables Running setup.py install for tables: started Running setup.py install for tables: finished with status 'error' Complete output from command /home/jonathonhill/miniconda/envs/optimus/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-jcuNfM/tables/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ofzTc6-record/install-record.txt --single-version-externally-managed --compile: * Using Python 2.7.8 |Continuum Analytics, Inc.| (default, Aug 21 2014, 18:22:21) * USE_PKGCONFIG: True * pkg-config header dirs for HDF5: /usr/include/hdf5/serial * pkg-config library dirs for HDF5: /usr/lib/x86_64-linux-gnu/hdf5/serial * Found HDF5 headers at ``/usr/include/hdf5/serial``, library at ``/usr/lib/x86_64-linux-gnu/hdf5/serial``. .. WARNING:: Could not find the HDF5 runtime. The HDF5 shared library was *not* found in the default library paths. In case of runtime problems, please remember to install it. /tmp/lzo_version_dateanObdP.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/lzo_version_dateanObdP.c: In function âmainâ: /tmp/lzo_version_dateanObdP.c:2:5: warning: implicit declaration of function âlzo_version_dateâ [-Wimplicit-function-declaration] lzo_version_date(); ^ * Could not find LZO 2 headers and library; disabling support for it. /tmp/lzo_version_datedINlTK.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/lzo_version_datedINlTK.c: In function âmainâ: /tmp/lzo_version_datedINlTK.c:2:5: warning: implicit declaration of function âlzo_version_dateâ [-Wimplicit-function-declaration] lzo_version_date(); ^ * Could not find LZO 1 headers and library; disabling support for it. /tmp/BZ2_bzlibVersionL7B4pC.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/BZ2_bzlibVersionL7B4pC.c: In function âmainâ: /tmp/BZ2_bzlibVersionL7B4pC.c:2:5: warning: implicit declaration of function âBZ2_bzlibVersionâ [-Wimplicit-function-declaration] BZ2_bzlibVersion(); ^ * Found bzip2 headers at ``/usr/include``, the library is located in the standard system search dirs. /tmp/blosc_list_compressorsQc0Mok.c:1:1: warning: return type defaults to âintâ [-Wimplicit-int] main (int argc, char **argv) { ^ /tmp/blosc_list_compressorsQc0Mok.c: In function âmainâ: /tmp/blosc_list_compressorsQc0Mok.c:2:5: warning: implicit declaration of function âblosc_list_compressorsâ [-Wimplicit-function-declaration] blosc_list_compressors(); ^ * Could not find blosc headers and library; using internal sources. </code></pre> <p>I gather from this that I am missing a HDF5 shared library. How can I fix this error / install any necessary dependencies.</p>
0
2016-07-20T07:38:46Z
38,475,382
<p><a href="http://www.pytables.org/usersguide/installation.html" rel="nofollow">Take a look at the project site page</a>. You can download manually the dependeces (<a href="http://blosc.org/" rel="nofollow">blosc</a>), maybe the issue is given by a network problem, or can not be satisfy automatically.If you already have the library try to specify during the installation in this way:</p> <pre><code>python setup.py --blosc=/stuff/blosc-1.8.1 </code></pre>
0
2016-07-20T07:49:55Z
[ "python", "pytables" ]
give a root privilege to a python GUI application to run a command in ubuntu
38,475,185
<p>Now, i have a python GUI app which need to run a command with sudo privilege like this below:</p> <pre><code>import commands iStat, askpassPath = commands.getstatusoutput("which ssh-askpass") cmd = "export SUDO_ASKPASS=%s;sudo -A mkdir -p /usr/lib/test"%(askpassPath) commands.getstatusoutput(cmd) </code></pre> <p><a href="http://i.stack.imgur.com/rF4ng.png" rel="nofollow"><img src="http://i.stack.imgur.com/rF4ng.png" alt="enter image description here"></a></p> <p>This works fine if ssh-askpass has been installed on ubuntu.But it seems some ubuntu systems don't install it by default while i can't install it for them.</p> <p>So, I need to know if there is another way for me to get a sudo privilege.</p> <p>Thanks in advance.</p> <p>Edit:The app should not be started with root privilege.It needs to get root privilege only when it is running. </p>
2
2016-07-20T07:39:42Z
38,476,502
<p>Since you're for "another way for me to get a sudo privilege". You can, and probably should, not run the application with elevated privileges.</p> <p>An option I see is to install a helper binary and store it with a <a href="https://en.wikipedia.org/wiki/Setuid" rel="nofollow">SUID-bit</a>. You can then call this binary to have your operation performed.</p> <p>If you do want to run with elevated privileges, you may want to have a look at <a href="http://linuxcommand.org/man_pages/consolehelper8.html" rel="nofollow">consolehelper</a>. Even the <a href="https://wiki.qt.io/How_to_get_applications_running_with_root_privileges" rel="nofollow">Qt wiki</a> mentions that method.</p> <p>To give a more complete answer, I'll try to lay out what steps you need to do. This is not meant as a comprehensive set of instructions. Please refer to the documentation.</p> <p>Essentially, try</p> <pre><code>ln -s /usr/sbin/consolehelper /usr/bin/yourapp-root </code></pre> <p>Then configure PAM (e.g. /etc/pam.d/yourapp-root):</p> <pre><code>#%PAM-1.0 auth include config-util account include config-util session include config-util </code></pre> <p>And then /etc/security/console.apps/yourapp-root:</p> <pre><code>USER=root PROGRAM=/usr/bin/yourapp </code></pre>
0
2016-07-20T08:46:56Z
[ "python", "linux", "user-interface", "ubuntu", "pyqt" ]
Configuring Python project in eclipse
38,475,209
<p>Actually I'm trying to use a python framework in Eclipse (with PyDev plugin) - the framework was designed in PyCharm IDE where we do some configuration as in the screenshot below:</p> <p><a href="http://i.stack.imgur.com/Nz536.png" rel="nofollow"><img src="http://i.stack.imgur.com/Nz536.png" alt="enter image description here"></a></p> <p>I've tried searching for reference links, but no luck so far. So can someone help me on how to configure <strong>Target, Keywords, Options</strong> parameter in Eclipse?</p> <p>******** ADDING SOME ADDITIONAL INFO ********</p> <p>Herewith, I'm adding some basic snippet as instructed -</p> <pre><code>import pytest @pytest.mark.test def test_method(): print "test method" class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert 'o' in x </code></pre> <p>It's working fine when I try to run it through command prompt using the following command </p> <blockquote> <p>$ py.test -k "test"</p> <p>============================= test session starts ============================= platform win32 -- Python 2.7.12 -- pytest-2.5.1 plugins: xdist, xdist, xdist collected 3 items</p> <p>test_sample.py ...</p> <p>========================== 3 passed in 0.05 seconds ===========================</p> </blockquote> <p>But it's not working when I try to run it through Eclipse PyDev, please be informed I've changed the PyUnit test runner option to Py.test runner as specified in <a href="http://pydev.blogspot.se/2010/12/improved-unittest-support-in-pydev.html" rel="nofollow">blog</a>. I have also tried to provide the <code>-k "test"</code> option in <strong>Run > Run Configurations > Argument</strong>s, but getting some abrupt exception as below - please help!</p> <blockquote> <p>Traceback (most recent call last): File "D:\eclipse\plugins\org.python.pydev_5.1.2.201606231256\pysrc\runfiles.py", line 241, in main() File "D:\eclipse\plugins\org.python.pydev_5.1.2.201606231256\pysrc\runfiles.py", line 233, in main return pytest.main(argv) File "C:\Python27\lib\site-packages_pytest\config.py", line 18, in main config = _prepareconfig(args, plugins) File "C:\Python27\lib\site-packages_pytest\config.py", line 62, in _prepareconfig pluginmanager=pluginmanager, args=args) File "C:\Python27\lib\site-packages_pytest\core.py", line 376, in <strong>call</strong> return self._docall(methods, kwargs) File "C:\Python27\lib\site-packages_pytest\core.py", line 387, in _docall res = mc.execute() File "C:\Python27\lib\site-packages_pytest\core.py", line 288, in execute res = method(**kwargs) File "C:\Python27\lib\site-packages_pytest\helpconfig.py", line 25, in pytest_cmdline_parse config = <strong>multicall</strong>.execute() File "C:\Python27\lib\site-packages_pytest\core.py", line 288, in execute res = method(**kwargs) File "C:\Python27\lib\site-packages_pytest\config.py", line 617, in pytest_cmdline_parse self.parse(args) File "C:\Python27\lib\site-packages_pytest\config.py", line 710, in parse self._preparse(args) File "C:\Python27\lib\site-packages_pytest\config.py", line 686, in _preparse self.pluginmanager.consider_preparse(args) File "C:\Python27\lib\site-packages_pytest\core.py", line 185, in consider_preparse self.consider_pluginarg(opt2) File "C:\Python27\lib\site-packages_pytest\core.py", line 195, in consider_pluginarg self.import_plugin(arg) File "C:\Python27\lib\site-packages_pytest\core.py", line 214, in import_plugin mod = importplugin(modname) File "C:\Python27\lib\site-packages_pytest\core.py", line 269, in importplugin <strong>import</strong>(importspec) File "D:\eclipse\plugins\org.python.pydev_5.1.2.201606231256\pysrc_pydev_runfiles\pydev_runfiles_pytest2.py", line 284, in @pytest.hookimpl(hookwrapper=True) AttributeError: 'module' object has no attribute 'hookimpl'</p> </blockquote>
0
2016-07-20T07:40:50Z
38,619,861
<p>Humm, can you update your pytest version and retry that? Which pytest version are you using?</p> <p>I.e. it seems PyDev is now requiring pytest 2.7 onwards (hookwrapper: executing around other hooks is New in version 2.7 from: <a href="http://docs.pytest.org/en/latest/writing_plugins.html" rel="nofollow">http://docs.pytest.org/en/latest/writing_plugins.html</a>).</p> <p>As a note, pytest 2.7 is from Mar 26, 2015, so, it's already relatively old.</p>
1
2016-07-27T17:44:24Z
[ "python", "eclipse", "pycharm", "pydev" ]
Heatmap from List
38,475,268
<p>I have a list <code>x</code> which contains intensities in the range 0 to 1. I want to create a heatmap with a squared grid.</p> <p>For example:</p> <pre><code>x = [0, 0.1, 0, 0.5, ..., 0.5] n = len(x) dim = math.sqrt(n) + 1 </code></pre> <p>But how can I create an array with <code>dim × dim</code> (the not available last values could be zero) and create the heatmap in a specified size (for example 1024×769)?</p>
0
2016-07-20T07:43:39Z
38,475,969
<p>As mentioned in the comment, you could use numpy, and plot with the help of seaborn:</p> <pre><code>import numpy as np import math import matplotlib.pyplot as plt import seaborn as sns x_list = np.random.rand(100).tolist() x = np.array((x_list)) x_res=x.reshape(math.sqrt(len(x)),math.sqrt(len(x))) fig, ax = plt.subplots(figsize=(15,15)) sns.heatmap(x_res, square=True, ax=ax) plt.yticks(rotation=0,fontsize=16); plt.xticks(fontsize=12); plt.tight_layout() plt.savefig('colorlist.png') </code></pre> <p>Which produces<a href="http://i.stack.imgur.com/ylhpd.png" rel="nofollow"><img src="http://i.stack.imgur.com/ylhpd.png" alt="result"></a></p>
1
2016-07-20T08:19:28Z
[ "python", "matplotlib" ]
How can I sort my list by name/age separately?
38,475,389
<p>Additionally, if I wanted to sort them by their age, how could I do so? I tried myFile.sort(), but it crashes the code saying "Object has no attribute 'sort' "</p> <pre><code>fileName = "GuestList.csv" ACCESSMODE = "w" name = " " nbrGuest = " " myFile = open(fileName, ACCESSMODE) nbrGuest = input("How many guests do you have? ") for index in range (int(nbrGuest)) : name = input("Enter guest name: " ).capitalize() age = input("Enter guest age: " ) myFile.write(name + "," + age + "\n") myFile.close() </code></pre>
-3
2016-07-20T07:50:23Z
38,475,480
<p>Duplicate question : <a href="http://stackoverflow.com/questions/2100353/sort-csv-by-column">sort-csv-by-column</a></p> <pre><code>import operator sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True) or use lambda sortedlist = sorted(reader, key=lambda row: row[3], reverse=True) </code></pre> <p>Note that only the list in the variable will be sorted, not the file. Youl'll have tto sort the list first then write the file in a second time.</p>
-1
2016-07-20T07:54:48Z
[ "python", "sorting" ]
How can I sort my list by name/age separately?
38,475,389
<p>Additionally, if I wanted to sort them by their age, how could I do so? I tried myFile.sort(), but it crashes the code saying "Object has no attribute 'sort' "</p> <pre><code>fileName = "GuestList.csv" ACCESSMODE = "w" name = " " nbrGuest = " " myFile = open(fileName, ACCESSMODE) nbrGuest = input("How many guests do you have? ") for index in range (int(nbrGuest)) : name = input("Enter guest name: " ).capitalize() age = input("Enter guest age: " ) myFile.write(name + "," + age + "\n") myFile.close() </code></pre>
-3
2016-07-20T07:50:23Z
38,475,534
<p>So the code is now split into two parts.</p> <pre><code>fileName = "GuestList.csv" ACCESSMODE = "w" name = " " nbrGuest = " " nbrGuest = input("How many guests do you have? ") guest_list = [] for index in range(int(nbrGuest)): name = input("Enter guest name:\t").capitalize() age = input("Enter guest age:\t") guest_list.append((name, age)) guest_list.sort(key=lambda x: x[1]) with open(fileName, ACCESSMODE) as myFile: for guest in guest_list: myFile.write(guest[0] + "," + guest[1] + "\n") </code></pre> <p>The first part takes the user input and stores all information in a list of tuples. Each <code>tuple</code> looks like e.g., <code>('ALEX', '24')</code>. After the list of guests is complete, it is sorted in place using the <code>.sort()</code> method based on the age of the guests (<strong>youngest first</strong>, use the <code>,reverse=True</code> to reverse the order). Finally, the sorted names and ages are written to file that is managed by the <code>with</code> statement so that you don't have to worry about closing it or flushing it.</p>
1
2016-07-20T07:57:18Z
[ "python", "sorting" ]
reading compressed data gives different results
38,475,464
<p>I am using genfromtxt in order to read data.</p> <p>genfromtxt must work also for .gz files but it seems it doesn't.</p> <p>Using simple data ( not .gz files )</p> <pre><code>f = open('file', 'r') con = np.genfromtxt(f,dtype=str) print con print type(con) </code></pre> <p>file contents is:</p> <pre><code> @HWI ABCDE + @HWI7 EFSA + ???=AF GTEY@JF GVTAWM </code></pre> <p>and output of above code is:</p> <pre><code>['@HWI' 'ABCDE' '+' '@HWI7' 'EFSA' '+' '???=AF' 'GTEY@JF' 'GVTAWM'] &lt;type 'numpy.ndarray'&gt; </code></pre> <p>If , I simply use the same code with the aboce file compressed as .gz file , the output is:</p> <pre><code>[ "\x1f\x8b\x08\x08\x1b4\x8eW\x00\x03file\x00Sp\xf0\x08\xf7\xe4R\x00\x02G'g\x17W0K\x1bL\x82$\xcc\xc1,W\xb7`G$" '{{{[G70\xd3=\xc45\xd2\xc1' '\xca\x0e' 'q' '\xf7\x05' '\x06\x07\xc2P'] &lt;type 'numpy.ndarray'&gt; </code></pre> <p>And the problem is that I want to perform some calculations later and I can't like this.</p> <p>I tried also ( for the .gz version ) :</p> <pre><code>with gzip.open(file, 'r') as f: con = np.array([f.read()]) print con print type(con) </code></pre> <p>which gives :</p> <pre><code>[ ' @HWI\n ABCDE\n +\n @HWI7\n EFSA\n +\n ???=AF\n GTEY@JF\n GVTAWM'] &lt;type 'numpy.ndarray'&gt; </code></pre> <p>which is closer to the initial but still doesn't work ( can't move on with calculations )</p> <p>How can I accomplish the same result?</p>
0
2016-07-20T07:54:00Z
38,475,710
<p>From the documentation:</p> <pre><code>genfromtxt(fname, dtype=&lt;class 'float'&gt;, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None) Load data from a text file, with missing values handled as specified. Each line past the first `skip_header` lines is split at the `delimiter` character, and characters following the `comments` character are discarded. Parameters ---------- fname : file or str File, filename, or generator to read. If the filename extension is `.gz` or `.bz2`, the file is first decompressed. Note that generators must return byte strings in Python 3k. </code></pre> <p>For the gzip version, you should try passing directly the filename (with <code>.gz</code> extension for compressed files.</p> <p>Test data:</p> <pre><code>$&gt; cat ./test.txt @HWI ABCDE + @HWI7 EFSA + ???=AF GTEY@JF GVTAWM $&gt; gzip --stdout ./test.txt &gt; ./test.txt.gz </code></pre> <p>Then in python:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.genfromtxt('./test.txt', dtype=str) array(['@HWI', 'ABCDE', '+', '@HWI7', 'EFSA', '+', '???=AF', 'GTEY@JF', 'GVTAWM'], dtype='&lt;U7') &gt;&gt;&gt; np.genfromtxt('./test.txt.gz', dtype=str) array(['@HWI', 'ABCDE', '+', '@HWI7', 'EFSA', '+', '???=AF', 'GTEY@JF', 'GVTAWM'], dtype='&lt;U7') </code></pre>
2
2016-07-20T08:05:55Z
[ "python", "numpy" ]
reading compressed data gives different results
38,475,464
<p>I am using genfromtxt in order to read data.</p> <p>genfromtxt must work also for .gz files but it seems it doesn't.</p> <p>Using simple data ( not .gz files )</p> <pre><code>f = open('file', 'r') con = np.genfromtxt(f,dtype=str) print con print type(con) </code></pre> <p>file contents is:</p> <pre><code> @HWI ABCDE + @HWI7 EFSA + ???=AF GTEY@JF GVTAWM </code></pre> <p>and output of above code is:</p> <pre><code>['@HWI' 'ABCDE' '+' '@HWI7' 'EFSA' '+' '???=AF' 'GTEY@JF' 'GVTAWM'] &lt;type 'numpy.ndarray'&gt; </code></pre> <p>If , I simply use the same code with the aboce file compressed as .gz file , the output is:</p> <pre><code>[ "\x1f\x8b\x08\x08\x1b4\x8eW\x00\x03file\x00Sp\xf0\x08\xf7\xe4R\x00\x02G'g\x17W0K\x1bL\x82$\xcc\xc1,W\xb7`G$" '{{{[G70\xd3=\xc45\xd2\xc1' '\xca\x0e' 'q' '\xf7\x05' '\x06\x07\xc2P'] &lt;type 'numpy.ndarray'&gt; </code></pre> <p>And the problem is that I want to perform some calculations later and I can't like this.</p> <p>I tried also ( for the .gz version ) :</p> <pre><code>with gzip.open(file, 'r') as f: con = np.array([f.read()]) print con print type(con) </code></pre> <p>which gives :</p> <pre><code>[ ' @HWI\n ABCDE\n +\n @HWI7\n EFSA\n +\n ???=AF\n GTEY@JF\n GVTAWM'] &lt;type 'numpy.ndarray'&gt; </code></pre> <p>which is closer to the initial but still doesn't work ( can't move on with calculations )</p> <p>How can I accomplish the same result?</p>
0
2016-07-20T07:54:00Z
38,476,165
<p>Why don't you use <code>genfromtxt</code> with the file object from <code>gzip.open()</code>?</p> <pre><code>with gzip.open('file.gz') as f: print(numpy.genfromtxt(f, dtype=str)) </code></pre> <p><strong>EDIT</strong></p> <p><code>numpy</code> uses predefined file openers for <code>.gz</code> and <code>.bz2</code> files. You can check the configuration like:</p> <pre><code>import numpy.lib._datasource as DS DS._file_openers._load() print(DS._file_openers._file_openers) </code></pre> <p>On my machine this shows handlers for bz2 and gz files:</p> <pre><code>{'.bz2': &lt;type 'bz2.BZ2File'&gt;, None: &lt;built-in function open&gt;, '.gz': &lt;function open at 0x7efca562a6e0&gt;} </code></pre> <p>Since the handler for gz files is actually <code>gzip.open</code>, it seems strange that numpy doesn't use it on your machine.</p>
1
2016-07-20T08:29:43Z
[ "python", "numpy" ]
How to format output to create space between two variables in python when printing?
38,475,578
<p>I'm trying to create an output that would look something like this:</p> <p><a href="http://i.stack.imgur.com/Ndu4b.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ndu4b.png" alt="enter image description here"></a> </p> <p>As can be seeing in here, the left column spaces are lined up to the left and the right column is lined up from the right side. But for my output, I am getting left column lined up to the right side and right column lined up to the left. I want to do vice versa. Here is the output of what I am actually getting out of my second code where I have tried to use the format function: </p> <p><a href="http://i.stack.imgur.com/rTNuT.png" rel="nofollow"><img src="http://i.stack.imgur.com/rTNuT.png" alt="enter image description here"></a> </p> <p>It works but I am just trying to learn adjusting and formatting spacing when the string output moves. It would also be nice to know how to do it if I were to have more than 3 variables.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "4d"), end = '') for i in range(1, 2): print(" ", lb, end = '') print() </code></pre> <p>Here is my initial code where I attempted to do that but the spacing is screwed up but the left column in here lies perfectly fine, but the spacing can be seeing on the right side after the output increases to double digits.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb print(kg, ' ', round(lb, 2)) </code></pre> <p>Output:</p> <p><a href="http://i.stack.imgur.com/I08rW.png" rel="nofollow"><img src="http://i.stack.imgur.com/I08rW.png" alt="enter image description here"></a></p> <p>I'm new to python so still a complete noob. I would really appreciate the explanation of how to deal with format or weather there is alternatives to it. Thank you! Code:</p>
0
2016-07-20T07:59:20Z
38,475,721
<p>You can use this one.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 100): kg += 1 lb = 2.2 lb = kg * lb space_filler = " " * 10 print("%3d %s %.2f" % (kg, space_filler, lb)) </code></pre> <p>The value 3 can also be made dynamic by use <code>format</code> which is more flexible than <code>%</code> construct.</p>
1
2016-07-20T08:06:21Z
[ "python", "python-3.x", "spacing" ]
How to format output to create space between two variables in python when printing?
38,475,578
<p>I'm trying to create an output that would look something like this:</p> <p><a href="http://i.stack.imgur.com/Ndu4b.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ndu4b.png" alt="enter image description here"></a> </p> <p>As can be seeing in here, the left column spaces are lined up to the left and the right column is lined up from the right side. But for my output, I am getting left column lined up to the right side and right column lined up to the left. I want to do vice versa. Here is the output of what I am actually getting out of my second code where I have tried to use the format function: </p> <p><a href="http://i.stack.imgur.com/rTNuT.png" rel="nofollow"><img src="http://i.stack.imgur.com/rTNuT.png" alt="enter image description here"></a> </p> <p>It works but I am just trying to learn adjusting and formatting spacing when the string output moves. It would also be nice to know how to do it if I were to have more than 3 variables.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "4d"), end = '') for i in range(1, 2): print(" ", lb, end = '') print() </code></pre> <p>Here is my initial code where I attempted to do that but the spacing is screwed up but the left column in here lies perfectly fine, but the spacing can be seeing on the right side after the output increases to double digits.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb print(kg, ' ', round(lb, 2)) </code></pre> <p>Output:</p> <p><a href="http://i.stack.imgur.com/I08rW.png" rel="nofollow"><img src="http://i.stack.imgur.com/I08rW.png" alt="enter image description here"></a></p> <p>I'm new to python so still a complete noob. I would really appreciate the explanation of how to deal with format or weather there is alternatives to it. Thank you! Code:</p>
0
2016-07-20T07:59:20Z
38,475,761
<p>Give this a try:</p> <pre><code>between = ' '*4 print('Kilograms{between}Pounds'.format(between=between)) for kg in range(199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print('{kg:&lt;{kg_width}}{between}{lb:&gt;{lb_width}}'.format( kg=kg, kg_width=len('Kilograms'), between=between, lb=lb, lb_width=len('Pounds'))) # Output: # Kilograms Pounds # 1 2.2 # 2 4.4 # 3 6.6 # 4 8.8 # 5 11.0 # 6 13.2 # 7 15.4 # 8 17.6 # 9 19.8 # 10 22.0 # 11 24.2 # ... </code></pre> <p>The big gnarly print is just because I tried to parameterize everything. Given the fixed column names and spacing, you could just do this:</p> <pre><code>print('{kg:&lt;9} {lb:&gt;6}'.format(kg=kg, lb=lb)) </code></pre> <p><strong>EDIT</strong></p> <p>Closer to your original code:</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "&lt;4d"), end = '') print(" ", end = '') print(format(lb, "&gt;7.1f")) </code></pre>
2
2016-07-20T08:08:12Z
[ "python", "python-3.x", "spacing" ]
How to format output to create space between two variables in python when printing?
38,475,578
<p>I'm trying to create an output that would look something like this:</p> <p><a href="http://i.stack.imgur.com/Ndu4b.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ndu4b.png" alt="enter image description here"></a> </p> <p>As can be seeing in here, the left column spaces are lined up to the left and the right column is lined up from the right side. But for my output, I am getting left column lined up to the right side and right column lined up to the left. I want to do vice versa. Here is the output of what I am actually getting out of my second code where I have tried to use the format function: </p> <p><a href="http://i.stack.imgur.com/rTNuT.png" rel="nofollow"><img src="http://i.stack.imgur.com/rTNuT.png" alt="enter image description here"></a> </p> <p>It works but I am just trying to learn adjusting and formatting spacing when the string output moves. It would also be nice to know how to do it if I were to have more than 3 variables.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print(format(kg, "4d"), end = '') for i in range(1, 2): print(" ", lb, end = '') print() </code></pre> <p>Here is my initial code where I attempted to do that but the spacing is screwed up but the left column in here lies perfectly fine, but the spacing can be seeing on the right side after the output increases to double digits.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 199): kg += 1 lb = 2.2 lb = kg * lb print(kg, ' ', round(lb, 2)) </code></pre> <p>Output:</p> <p><a href="http://i.stack.imgur.com/I08rW.png" rel="nofollow"><img src="http://i.stack.imgur.com/I08rW.png" alt="enter image description here"></a></p> <p>I'm new to python so still a complete noob. I would really appreciate the explanation of how to deal with format or weather there is alternatives to it. Thank you! Code:</p>
0
2016-07-20T07:59:20Z
38,475,765
<p>Check out <a href="https://docs.python.org/3.1/library/string.html#string.Formatter.vformat" rel="nofollow">The Docs</a> Section 7.1.3.1</p> <p>You can pass <code>format()</code> a <code>width</code> as int, which should take care of your whitespace problem.</p> <p>From the Documentation Example:</p> <pre><code>&gt;&gt;&gt; for num in range(5,12): for base in 'dXob': print('{0:{width}{base}}'.format(num, base=base, width=width),end=' ') </code></pre> <p>produces: </p> <pre><code> 5 5 5 101 6 6 6 110 7 7 7 111 8 8 10 1000 9 9 11 1001 10 A 12 1010 11 B 13 1011 </code></pre>
1
2016-07-20T08:08:35Z
[ "python", "python-3.x", "spacing" ]
How to convert a list into a 1 item dictionary list
38,475,614
<p>I have a list like</p> <pre><code>a=[('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] </code></pre> <p>Now, I want to convert it to a list of one item <code>dict</code>:</p> <pre><code>[{'call': 260},{'insurance': 382},{'life': 357}, {'policy': 871}, {'request': 270}] </code></pre>
-3
2016-07-20T08:00:58Z
38,475,641
<p>You can convert a list of tuples to a dict simply by converting it to a dict:</p> <pre><code>&gt;&gt;&gt; a = [('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] &gt;&gt;&gt; dict(a) </code></pre> <p>will result in</p> <pre><code>{'policy': 871, 'call': 260, 'life': 357, 'request': 270, 'insurance': 382} </code></pre> <p>If you want it as a <code>json</code> string, try this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps(dict(a)) </code></pre> <p>this time it will print a json formatted string instead of a dict (note the enclosing quotes):</p> <pre><code>'{"policy": 871, "call": 260, "life": 357, "request": 270, "insurance": 382}' </code></pre> <p>Update: If you need a <code>list</code> of <code>dict</code>s instead, try the following method:</p> <pre><code>&gt;&gt;&gt; map(lambda x: {x[0]: x[1]}, a) [{'policy': 871}, {'insurance': 382}, {'life': 357}, {'request': 270}, {'call': 260}] </code></pre>
6
2016-07-20T08:02:14Z
[ "python", "list" ]
How to convert a list into a 1 item dictionary list
38,475,614
<p>I have a list like</p> <pre><code>a=[('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] </code></pre> <p>Now, I want to convert it to a list of one item <code>dict</code>:</p> <pre><code>[{'call': 260},{'insurance': 382},{'life': 357}, {'policy': 871}, {'request': 270}] </code></pre>
-3
2016-07-20T08:00:58Z
38,475,808
<p>I think you wanted a list of dictionaries, so here is one way:</p> <pre><code>&gt;&gt;&gt; [{k:v} for (k,v) in a] [{'policy': 871}, {'insurance': 382}, {'life': 357}, {'request': 270}, {'call': 260}] </code></pre>
4
2016-07-20T08:11:23Z
[ "python", "list" ]
How to convert a list into a 1 item dictionary list
38,475,614
<p>I have a list like</p> <pre><code>a=[('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] </code></pre> <p>Now, I want to convert it to a list of one item <code>dict</code>:</p> <pre><code>[{'call': 260},{'insurance': 382},{'life': 357}, {'policy': 871}, {'request': 270}] </code></pre>
-3
2016-07-20T08:00:58Z
38,477,774
<p>My version</p> <pre><code>def convert_to_dict(a): return [{i[0]: i[1]} for i in a] </code></pre> <p>Hope this helps :)</p>
0
2016-07-20T09:45:37Z
[ "python", "list" ]
not printing inside celery task
38,475,717
<p>In my celery I tried printing inside a task, but I cant seem to output the data even in console.</p> <p>Here is my structure:</p> <pre><code>/app.py @app.route('//create', methods = ['POST']) def create_file(): request.form ....... callback = build_file.s(name, address) header = [ send_param.s( id, key ) for key in request_api.keys() ] result = chord(header)(callback) @celery.task(name='app.send_param', routing_key='send_param', queue='send_param', retry=False, bind=True) def send_param(seld, id, key): //do something print 'NOT WORKING' @celery.task(name='app.build_file', routing_key='send_param', queue='send_param', retry=False, bind=True) def build_file(seld, name, address): //do something print 'NOT WORKING' </code></pre> <p>When printing within my create_file function it does print, but within my tasks it doesnt.</p>
-1
2016-07-20T08:06:07Z
38,482,557
<p>The most straightforward solution will be to:</p> <p>1) Configure a Logger instance which will capture all output from <code>logger.info()</code> (and other log levels) and put it into a local file or just <code>stdout</code></p> <p>2) While configuring, set </p> <pre><code>app.conf.update(CELERYD_HIJACK_ROOT_LOGGER=False) </code></pre> <p>to prevent Celery from removing any previously configured Loggers (more info: <a href="http://docs.celeryproject.org/en/latest/configuration.html#logging" rel="nofollow">http://docs.celeryproject.org/en/latest/configuration.html#logging</a>).</p> <hr> <p>Another option could be using the Siglans: <a href="http://docs.celeryproject.org/en/latest/userguide/signals.html" rel="nofollow">http://docs.celeryproject.org/en/latest/userguide/signals.html</a></p> <p>but it is a little bit more involved and probably an overkill in your situation.</p>
0
2016-07-20T13:23:05Z
[ "python", "flask", "celery" ]
'pip install -r requirements.txt' fails when using Chef
38,475,795
<p>I have a script which is copied to a Chef node; it activates a python virtual environment and then installs requirements from a requirements file:</p> <pre><code>#!/bin/bash source venv/bin/activate pip install -v -r requirements.txt &gt;&gt; scripts/scripts.out </code></pre> <p>When I run it locally, all is well. When run using a Chef execute block (bash) it is silently failing.</p> <pre><code>bash 'install_dependencies' do cwd '/opt/application/' user 'app-user' code &lt;&lt;-EOH ./scripts/install-deps.sh EOH end </code></pre> <p>Any suggestions why? Here's the failure output:</p> <pre><code>Collecting bs4 (from -r requirements.txt (line 4)) 1 location(s) to search for versions of bs4: * https://pypi.python.org/simple/bs4/ Getting page https://pypi.python.org/simple/bs4/ Looking up "https://pypi.python.org/simple/bs4/" in the cache No cache entry available Starting new HTTPS connection (1): pypi.python.org "GET /simple/bs4/ HTTP/1.1" 200 313 Updating cache with response from "https://pypi.python.org/simple/bs4/" Caching b/c date exists and max-age &gt; 0 Analyzing links from page https://pypi.python.org/simple/bs4/ Found link https://pypi.python.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz#md5=fe7e51587ac3b174608f3c4f8bd893ac (from https://pypi.python.org/simple/bs4/), version: 0.0.1 Found link https://pypi.python.org/packages/50/fe/c4bf5083af20ec85ac5d278dfd12a9756724100c308b7bdccbaa7cbf5715/bs4-0.0.0.tar.gz#md5=c1b62a2b9f2987d7f949f1392a82518f (from https://pypi.python.org/simple/bs4/), version: 0.0.0 Using version 0.0.1 (newest of versions: 0.0.0, 0.0.1) Cleaning up... </code></pre> <p>And the head of the output from a (successful) local run - i.e. it goes on to complete the installation:</p> <pre><code>Collecting bs4 (from -r requirements.txt (line 4)) 1 location(s) to search for versions of bs4: * https://pypi.python.org/simple/bs4/ Getting page https://pypi.python.org/simple/bs4/ Looking up "https://pypi.python.org/simple/bs4/" in the cache Current age based on date: 558 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 &gt; 558 Analyzing links from page https://pypi.python.org/simple/bs4/ Found link https://pypi.python.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz#md5=fe7e51587ac3b1 Found link https://pypi.python.org/packages/50/fe/c4bf5083af20ec85ac5d278dfd12a9756724100c308b7bdccbaa7cbf5715/bs4-0.0.0.tar.gz#md5=c1b62a2b9f2987 Using version 0.0.1 (newest of versions: 0.0.0, 0.0.1) Using cached wheel link: file:///ridl/.cache/pip/wheels/84/67/d4/9e09d9d5adede2ee1c7b7e8775ba3fbb04d07c4f946f0e4f11/bs4-0.0.1-cp34-none-any.whl Collecting requests (from -r requirements.txt (line 5)) 1 location(s) to search for versions of requests: * https://pypi.python.org/simple/requests/ Getting page https://pypi.python.org/simple/requests/ Looking up "https://pypi.python.org/simple/requests/" in the cache Current age based on date: 558 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 &gt; 558 Analyzing links from page https://pypi.python.org/simple/requests/ Found link https://pypi.python.org/packages/00/c8/8cf0f078100ce5fe7ff35927d8861e2e36daed9be2db56690f3ad80ccec4/requests-0.7.1.tar.gz#md5=4821c6902 Found link https://pypi.python.org/packages/01/44/39988315e036b79fe70428273053617266bf20d1363e91082346fae8450d/requests-0.10.3.tar.gz#md5=a055af00 Found link https://pypi.python.org/packages/01/da/da83c242c5a77c58aa86072d68fd2855aa9b4d3b1a8bac4b402531b25ff1/requests-0.13.9.tar.gz#md5=66d52b8f Found link https://pypi.python.org/packages/02/56/a6203485b552f9e8e8f16bd4e576446f94737ccbc563957e7510c8e401e4/requests-0.13.6.tar.gz#md5=9ea0f38c </code></pre>
0
2016-07-20T08:10:24Z
38,476,019
<p>Looks like Chef's bash block doesn't set the home directory for the user it is representing. As a result pip couldn't find/use the cache directory. Explicitly stating it in the script fixed the problem:</p> <pre><code>#!/bin/bash source venv/bin/activate pip install -v -r requirements.txt --cache-dir /home/app-user/.cache/pip &gt;&gt; scripts/scripts.out </code></pre>
0
2016-07-20T08:22:12Z
[ "python", "pip", "chef" ]
'pip install -r requirements.txt' fails when using Chef
38,475,795
<p>I have a script which is copied to a Chef node; it activates a python virtual environment and then installs requirements from a requirements file:</p> <pre><code>#!/bin/bash source venv/bin/activate pip install -v -r requirements.txt &gt;&gt; scripts/scripts.out </code></pre> <p>When I run it locally, all is well. When run using a Chef execute block (bash) it is silently failing.</p> <pre><code>bash 'install_dependencies' do cwd '/opt/application/' user 'app-user' code &lt;&lt;-EOH ./scripts/install-deps.sh EOH end </code></pre> <p>Any suggestions why? Here's the failure output:</p> <pre><code>Collecting bs4 (from -r requirements.txt (line 4)) 1 location(s) to search for versions of bs4: * https://pypi.python.org/simple/bs4/ Getting page https://pypi.python.org/simple/bs4/ Looking up "https://pypi.python.org/simple/bs4/" in the cache No cache entry available Starting new HTTPS connection (1): pypi.python.org "GET /simple/bs4/ HTTP/1.1" 200 313 Updating cache with response from "https://pypi.python.org/simple/bs4/" Caching b/c date exists and max-age &gt; 0 Analyzing links from page https://pypi.python.org/simple/bs4/ Found link https://pypi.python.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz#md5=fe7e51587ac3b174608f3c4f8bd893ac (from https://pypi.python.org/simple/bs4/), version: 0.0.1 Found link https://pypi.python.org/packages/50/fe/c4bf5083af20ec85ac5d278dfd12a9756724100c308b7bdccbaa7cbf5715/bs4-0.0.0.tar.gz#md5=c1b62a2b9f2987d7f949f1392a82518f (from https://pypi.python.org/simple/bs4/), version: 0.0.0 Using version 0.0.1 (newest of versions: 0.0.0, 0.0.1) Cleaning up... </code></pre> <p>And the head of the output from a (successful) local run - i.e. it goes on to complete the installation:</p> <pre><code>Collecting bs4 (from -r requirements.txt (line 4)) 1 location(s) to search for versions of bs4: * https://pypi.python.org/simple/bs4/ Getting page https://pypi.python.org/simple/bs4/ Looking up "https://pypi.python.org/simple/bs4/" in the cache Current age based on date: 558 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 &gt; 558 Analyzing links from page https://pypi.python.org/simple/bs4/ Found link https://pypi.python.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz#md5=fe7e51587ac3b1 Found link https://pypi.python.org/packages/50/fe/c4bf5083af20ec85ac5d278dfd12a9756724100c308b7bdccbaa7cbf5715/bs4-0.0.0.tar.gz#md5=c1b62a2b9f2987 Using version 0.0.1 (newest of versions: 0.0.0, 0.0.1) Using cached wheel link: file:///ridl/.cache/pip/wheels/84/67/d4/9e09d9d5adede2ee1c7b7e8775ba3fbb04d07c4f946f0e4f11/bs4-0.0.1-cp34-none-any.whl Collecting requests (from -r requirements.txt (line 5)) 1 location(s) to search for versions of requests: * https://pypi.python.org/simple/requests/ Getting page https://pypi.python.org/simple/requests/ Looking up "https://pypi.python.org/simple/requests/" in the cache Current age based on date: 558 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 &gt; 558 Analyzing links from page https://pypi.python.org/simple/requests/ Found link https://pypi.python.org/packages/00/c8/8cf0f078100ce5fe7ff35927d8861e2e36daed9be2db56690f3ad80ccec4/requests-0.7.1.tar.gz#md5=4821c6902 Found link https://pypi.python.org/packages/01/44/39988315e036b79fe70428273053617266bf20d1363e91082346fae8450d/requests-0.10.3.tar.gz#md5=a055af00 Found link https://pypi.python.org/packages/01/da/da83c242c5a77c58aa86072d68fd2855aa9b4d3b1a8bac4b402531b25ff1/requests-0.13.9.tar.gz#md5=66d52b8f Found link https://pypi.python.org/packages/02/56/a6203485b552f9e8e8f16bd4e576446f94737ccbc563957e7510c8e401e4/requests-0.13.6.tar.gz#md5=9ea0f38c </code></pre>
0
2016-07-20T08:10:24Z
38,483,393
<p>You could also use the <code>pip_requirements</code> resource from the <code>poise-python</code> cookbook, which does all this for you.</p>
1
2016-07-20T13:59:23Z
[ "python", "pip", "chef" ]
Save NumPy array / vector to CSV
38,475,824
<p>I have some numeric numbers ( about 550,000) and I tried to save them in a CSV file. My values can only be 1 or 2. But it is saved as:</p> <pre><code>['2.000000000000000000e+00'] ['1.000000000000000000e+00'] ['2.000000000000000000e+00'] ['2.000000000000000000e+00'] ... </code></pre> <p>My code is:</p> <pre><code>import numpy as np def save_in_scv_format(My_Labels): K = [] for i in range(len(My_Labels)): K.append(My_Labels[i]) np.savetxt('My_labels.csv', K, delimiter = ',') </code></pre> <p><code>My_labels</code> is a vector having integer values of 1 or 2 with length 550,000.</p> <p>How can I save these values as either a <code>1</code> or a <code>2</code>?</p>
0
2016-07-20T08:12:16Z
38,475,978
<p>First thing to point out, assuming <code>My_Labels</code> is a list as you suggest, the indicated section of your code is superfluous:</p> <pre><code>def save_in_scv_format(My_Labels): import numpy as np K = [] # &lt;-- for i in range(len(My_Labels)): # &lt;-- K.append(My_Labels[i]) # &lt;-- np.savetxt('My_labels.csv', K, delimiter = ',') </code></pre> <p>You'd be just as well off writing:</p> <pre><code>def save_in_scv_format(My_Labels): import numpy as np np.savetxt('My_labels.csv', My_Labels, delimiter = ',') </code></pre> <p>But I don't think you need numpy to do what it seems you want to do. Something like:</p> <pre><code>def save_in_scv_format(My_Labels): with open('My_labels.csv', 'w') as f: f.write(','.join(My_Labels)) </code></pre> <p>would likely work, and better.</p> <p>Alternatively, you could do something like:</p> <pre><code>def save_in_scv_format(My_Labels): with open('My_labels.csv', 'w') as f: f.write(str(My_Labels)) </code></pre> <p>which would preserve the enclosing square brackets, and add spaces between the integers.</p> <p>There is also the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv</a> and <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickle</a> modules, you might look into, for alternative means of outputting your list to a file.</p> <p>n.b. If I misunderstood, and <code>My_Labels</code> is, for example, a numpy array, then something like: </p> <pre><code>my_array = My_Labels.tolist() </code></pre> <p>(<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html" rel="nofollow">docs</a>) is a cleaner way of creating a python list.</p>
0
2016-07-20T08:19:54Z
[ "python", "csv" ]
Save NumPy array / vector to CSV
38,475,824
<p>I have some numeric numbers ( about 550,000) and I tried to save them in a CSV file. My values can only be 1 or 2. But it is saved as:</p> <pre><code>['2.000000000000000000e+00'] ['1.000000000000000000e+00'] ['2.000000000000000000e+00'] ['2.000000000000000000e+00'] ... </code></pre> <p>My code is:</p> <pre><code>import numpy as np def save_in_scv_format(My_Labels): K = [] for i in range(len(My_Labels)): K.append(My_Labels[i]) np.savetxt('My_labels.csv', K, delimiter = ',') </code></pre> <p><code>My_labels</code> is a vector having integer values of 1 or 2 with length 550,000.</p> <p>How can I save these values as either a <code>1</code> or a <code>2</code>?</p>
0
2016-07-20T08:12:16Z
38,476,566
<p>You can change the formatting of numeric values in the output. From the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow">manual</a>:</p> <blockquote> <p><strong>fmt</strong> : <code>str or sequence of strs, optional</code></p> <pre><code> A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case delimiter is ignored. </code></pre> </blockquote> <p>So try:</p> <pre><code>np.savetxt('My_labels.csv', K, delimiter = ',', fmt='%d') </code></pre> <p>However, there are other problems with this code.</p> <pre><code>import numpy as np def save_in_csv_format(My_Labels): np.savetxt('My_labels.csv', My_Labels, delimiter = ',', fmt='%d') </code></pre> <p>This should do exactly the same thing, and be much more efficient.</p>
0
2016-07-20T08:50:03Z
[ "python", "csv" ]
What is the $project (aggregation) API for Pymongo?
38,475,908
<p>I'm rather new to MongoDB, I can find some commands in shell to execute my query, however, I can not find a proper function in PyMongo API manual. </p> <p>For example, I would like to project some of the fields of the document to a new document. I suppose the $project could do it, but there is no such support in Pymongo. How could I execute the same query both in shell and Python? For example:</p> <pre><code>db.books.aggregate( [ { $project : { title : 1 , author : 1 } } ] ) </code></pre>
-1
2016-07-20T08:16:22Z
38,476,605
<p>For projecting you may use the query as</p> <pre><code>db.books.aggregate([{'$project':{ 'title':'$title', 'author':'$author'}}]) </code></pre>
0
2016-07-20T08:51:53Z
[ "python", "mongodb" ]
Referencing a variable from a different thread/class in python?
38,475,987
<p>What I'm trying to achieve is quite simple.</p> <p>So basically, I have a thread that loops continuously, grabbing data from the same url and updating a variable called "data", with text each time. The variable is stored locally within the class.</p> <p>Then I have a second class which is the mainframe. It should display the latest data, which is determined by whatever the variable in the first class is set to.</p> <p>The problem is that I cannot find a way to reference that variable from the other class/thread. </p> <p>The name of the variable that I am setting, and trying to reference is "data".</p> <p>Here is the source code:</p> <pre><code>#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 # -*- coding: utf-8 -*- from tkinter import * import time import urllib.request from bs4 import BeautifulSoup import threading from queue import Queue class httpReq(threading.Thread): def run(self): i = 0 while 1&lt;5: url = "https://twitter.com/realDonaldTrump" page = urllib.request.urlopen(url) soup = BeautifulSoup(page, "html.parser") self.data = data = soup.title.text print(x) x = httpReq() x.start() class Example(Frame, httpReq): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("IT Support App") self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Primary Video Stream", width= 20) lbl1.pack(side=LEFT, padx=5, pady=5) lbl6 = Label(frame1, text= x.data) lbl6.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=BOTH, expand=True) lbl2 = Label(frame2, text="Primary Audio Stream", width=20) lbl2.pack(side=LEFT, padx=5, pady=5) entry2 = Entry(frame2) entry2.pack(fill=X, padx=5, expand=True) frame3 = Frame(self) frame3.pack(fill=BOTH, expand=True) lbl3 = Label(frame3, text="Backup Video Stream", width=20) lbl3.pack(side=LEFT, padx=5, pady=5) entry3 = Entry(frame3) entry3.pack(fill=X, pady=5, padx=5, expand=True) frame4 = Frame(self) frame4.pack(fill=BOTH, expand=True) lbl4 = Label(frame4, text="Backup Audio Stream", width=20) lbl4.pack(side=LEFT, padx=5, pady=5) entry4 = Entry(frame4) entry4.pack(fill=X, pady=5, padx=5, expand=True) frame5 = Frame(self) frame5.pack(fill=X) lbl5 = Label(frame5, text="IPTV", width=20) lbl5.pack(side=LEFT, padx=5, pady=5) entry5 = Entry(frame5) entry5.pack(fill=X, pady=5, padx=5, expand=True) def main(): root = Tk() root.geometry("1920x1080") app = Example(root) root.mainloop() if __name__ == '__main__': main() </code></pre>
0
2016-07-20T08:20:32Z
38,476,128
<p>Try to declare the data variable outside of the while loop and the run method. Then you can call that static variable using <strong>httpReq.data</strong> </p> <p>For reference : <a href="https://stackoverflow.com/questions/68645/static-class-variables-in-python?rq=1">Static class variables in Python</a></p>
0
2016-07-20T08:27:54Z
[ "python", "multithreading" ]
Referencing a variable from a different thread/class in python?
38,475,987
<p>What I'm trying to achieve is quite simple.</p> <p>So basically, I have a thread that loops continuously, grabbing data from the same url and updating a variable called "data", with text each time. The variable is stored locally within the class.</p> <p>Then I have a second class which is the mainframe. It should display the latest data, which is determined by whatever the variable in the first class is set to.</p> <p>The problem is that I cannot find a way to reference that variable from the other class/thread. </p> <p>The name of the variable that I am setting, and trying to reference is "data".</p> <p>Here is the source code:</p> <pre><code>#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 # -*- coding: utf-8 -*- from tkinter import * import time import urllib.request from bs4 import BeautifulSoup import threading from queue import Queue class httpReq(threading.Thread): def run(self): i = 0 while 1&lt;5: url = "https://twitter.com/realDonaldTrump" page = urllib.request.urlopen(url) soup = BeautifulSoup(page, "html.parser") self.data = data = soup.title.text print(x) x = httpReq() x.start() class Example(Frame, httpReq): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("IT Support App") self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Primary Video Stream", width= 20) lbl1.pack(side=LEFT, padx=5, pady=5) lbl6 = Label(frame1, text= x.data) lbl6.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=BOTH, expand=True) lbl2 = Label(frame2, text="Primary Audio Stream", width=20) lbl2.pack(side=LEFT, padx=5, pady=5) entry2 = Entry(frame2) entry2.pack(fill=X, padx=5, expand=True) frame3 = Frame(self) frame3.pack(fill=BOTH, expand=True) lbl3 = Label(frame3, text="Backup Video Stream", width=20) lbl3.pack(side=LEFT, padx=5, pady=5) entry3 = Entry(frame3) entry3.pack(fill=X, pady=5, padx=5, expand=True) frame4 = Frame(self) frame4.pack(fill=BOTH, expand=True) lbl4 = Label(frame4, text="Backup Audio Stream", width=20) lbl4.pack(side=LEFT, padx=5, pady=5) entry4 = Entry(frame4) entry4.pack(fill=X, pady=5, padx=5, expand=True) frame5 = Frame(self) frame5.pack(fill=X) lbl5 = Label(frame5, text="IPTV", width=20) lbl5.pack(side=LEFT, padx=5, pady=5) entry5 = Entry(frame5) entry5.pack(fill=X, pady=5, padx=5, expand=True) def main(): root = Tk() root.geometry("1920x1080") app = Example(root) root.mainloop() if __name__ == '__main__': main() </code></pre>
0
2016-07-20T08:20:32Z
38,631,873
<p>It turns out that there are various ways of doing this. For my purposes however, (since only one thread writes to the variable, and the others read-only) I have found that using a global variable does the job.</p> <p>First declare and set the variable to none, outside the thread. Then within each thread, declare the variable as global:</p> <pre><code>#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 # -*- coding: utf-8 -*- from tkinter import * import time import urllib.request from bs4 import BeautifulSoup import threading from queue import Queue data = None class httpReq(threading.Thread): def run(self): global data while True: url = "https://twitter.com/realDonaldTrump" page = urllib.request.urlopen(url) soup = BeautifulSoup(page, "html.parser") data = soup.title.text print(data) x = httpReq() x.start() class Example(Frame): global data def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Example App") self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Title Data:", width= 20) lbl1.pack(side=LEFT, padx=5, pady=5) lbl2 = Label(frame1, text= data) lbl2.pack(fill=X, padx=5, expand=True) def main(): root = Tk() root.geometry("600x200") app = Example(root) root.mainloop() if __name__ == '__main__': main() </code></pre>
0
2016-07-28T09:09:48Z
[ "python", "multithreading" ]
Concatenating all Possible Column Values of Other Unique Column
38,476,096
<p><strong>Problem Setting</strong></p> <p>Suppose I am given the following data frame.</p> <pre><code>ID category 223 MMO 223 Game 444 Finance 360 Reading 360 Book </code></pre> <p>This data frame has an <code>ID</code> column and it's associated <code>category</code>. Notice that the same <code>ID</code> can have multiple categories.</p> <p>My goal is to create a new column, which contains the concatenation of all the possible categories for a given <code>ID</code>. This means:</p> <ul> <li>Removing the old <code>category</code> column</li> <li>Removing duplicate <code>ID</code> rows</li> </ul> <p>The output would look like this.</p> <pre><code>ID category 223 MMO_Game 444 Finance 360 Reading_Book </code></pre> <p><strong>Attempted Solution</strong></p> <p>My though process was to first create a groupby variable that would group <code>category</code> by <code>ID</code>.</p> <pre><code>groupby_ID = df['category'].groupby(df['ID']) </code></pre> <p>Now I can try and iterate through the grouped data and concatenate the strings.</p> <pre><code>for ID, category in groupby_appID: </code></pre> <p>I don't know how to go on at this point. Some pointers would be greatly appreciated!</p>
2
2016-07-20T08:26:24Z
38,476,116
<p>You can <code>groupby</code> on ID and then apply a <code>join</code> with your desired separator:</p> <pre><code>In [142]: df.groupby('ID')['category'].apply('_'.join) Out[142]: ID 223 MMO_Game 360 Reading_Book 444 Finance Name: category, dtype: object </code></pre> <p>To get the exact desired output you can call <code>reset_index</code> with <code>name</code> param:</p> <pre><code>In [145]: df.groupby('ID')['category'].apply('_'.join).reset_index(name='category') Out[145]: ID category 0 223 MMO_Game 1 360 Reading_Book 2 444 Finance </code></pre>
4
2016-07-20T08:27:28Z
[ "python", "pandas" ]
JSON and MySQL UPDATE query
38,476,206
<p>I'm trying to get info from a JSON msg out of ZeroMQ into MySQL by Python. This is the piece of code I'm attempting to run:</p> <pre><code>for i in json_msg["PropertyInfoMsg"]: db2 = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="db") cursor2 = db2.cursor() sql = """UPDATE settings SET value=%s WHERE name=%s""" % (i["PropertyType"].lower(), i["PropertyValue"].lower()) cursor2.execute(sql) db2.commit() cursor2.close() </code></pre> <p>But it's comming back as:</p> <blockquote> <p>1064, 'You have an error in your SQL syntax</p> </blockquote> <p>I could really use a second pair of eyes at this at this point in time, I feel like I'm completely missing it.</p> <p>Priting out the sql variable returns:</p> <pre><code>UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() </code></pre>
1
2016-07-20T08:32:13Z
38,476,346
<p>I would do the query this way :</p> <pre><code>cursor2.execute("UPDATE settings SET value = %s WHERE name = %s",(i["PropertyType"].lower(), i["PropertyValue"].lower())) </code></pre>
2
2016-07-20T08:40:31Z
[ "python", "mysql", "json" ]
JSON and MySQL UPDATE query
38,476,206
<p>I'm trying to get info from a JSON msg out of ZeroMQ into MySQL by Python. This is the piece of code I'm attempting to run:</p> <pre><code>for i in json_msg["PropertyInfoMsg"]: db2 = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="db") cursor2 = db2.cursor() sql = """UPDATE settings SET value=%s WHERE name=%s""" % (i["PropertyType"].lower(), i["PropertyValue"].lower()) cursor2.execute(sql) db2.commit() cursor2.close() </code></pre> <p>But it's comming back as:</p> <blockquote> <p>1064, 'You have an error in your SQL syntax</p> </blockquote> <p>I could really use a second pair of eyes at this at this point in time, I feel like I'm completely missing it.</p> <p>Priting out the sql variable returns:</p> <pre><code>UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() UPDATE settings SET value=i["PropertyType"].lower() WHERE name=i["PropertyValue"].lower() </code></pre>
1
2016-07-20T08:32:13Z
38,476,364
<p>You should wrap your parameters with single quote:</p> <pre><code>sql = """UPDATE settings SET value='%s' WHERE name='%s'""" % (i["PropertyType"].lower(), i["PropertyValue"].lower()) </code></pre> <p>Also you must confirm your json data is correct.</p>
2
2016-07-20T08:41:02Z
[ "python", "mysql", "json" ]
sort dataframe by a subset of levels in a multiindex
38,476,260
<p>I have following dataframe:</p> <pre><code>data = {'year': [2010, 2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012, 2013], 'store_number': ['1944', '1945', '1946', '1947', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV', 'CRV'], 'month': [1, 12, 3, 11, 10, 9, 5, 5, 4, 3], 'amount': [5, 5, 8, 6, 1, 5, 10, 6, 12, 11]} stores = pd.DataFrame(data, columns=['retailer_name', 'store_number', 'year', 'month', 'amount']) stores.set_index(['retailer_name', 'store_number', 'year', 'month'], inplace=True) </code></pre> <p>That looks like: </p> <pre><code> amount retailer_name store_number year month Walmart 1944 2010 1 5 1945 2010 12 5 CRV 1946 2011 3 8 1947 2012 11 6 1948 2011 10 1 Walmart 1949 2012 9 5 1947 2010 5 10 CRV 1948 2011 5 6 1949 2012 4 12 1947 2013 3 11 </code></pre> <p>How I can sort the groups:</p> <pre><code>stores_g = stores.groupby(level=0) </code></pre> <p>by <code>'year'</code> and <code>'month'</code> with <code>decreasing</code> order .</p>
2
2016-07-20T08:35:54Z
38,476,312
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a> by specific index levels and specify whether the ordering should be ascending or not:</p> <pre><code>In [148]: stores.sort_index(level=['year','month'], ascending=False) Out[148]: amount retailer_name store_number year month CRV 1947 2013 3 11 2012 11 6 Walmart 1949 2012 9 5 CRV 1949 2012 4 12 1948 2011 10 1 5 6 1946 2011 3 8 Walmart 1945 2010 12 5 1947 2010 5 10 1944 2010 1 5 </code></pre>
3
2016-07-20T08:38:36Z
[ "python", "pandas", "dataframe" ]
How to write csv file into sql database with python
38,476,268
<p>I have csv file that include some information about computer as like ostype, ram, cpu value and ı have sql database that already has same information and ı want to updated that database table with by python script. database table and csv file has uniqe "id" parameters. </p> <pre><code>import csv with open("Hypersanal.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter=';') for row in readCSV: print row </code></pre>
0
2016-07-20T08:36:09Z
38,477,003
<p>Depending on what type of database, there will be some slight adjustments to make to the code.<br> For this example, I'll use <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> with the <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">pymysql</a> driver. To find out what the first part of the connection String should be (depends on the kind of database you want to connect to), check <a href="http://docs.sqlalchemy.org/en/latest/dialects/index.html" rel="nofollow">SQLAlchemy Doc about Dialects</a>. </p> <p>First, we import the necessary modules</p> <pre><code>from sqlalchemy import * from sqlalchemy.orm import create_session from sqlalchemy.ext.declarative import declarative_base </code></pre> <p>Then, we create the connection string</p> <pre><code>dialect_part = "mysql+pymysql://" # username is the usernmae we'll use to connect to the db, and password the corresponding password # server_name is the name fo the server where the db is. It INCLUDES the port number (eg : 'localhost:9080') # database is the name of the db on the server we'll work on connection_string = dialect_part+username+":"+password+"@"+server_name+"/"+database </code></pre> <p>Some more setups needed for SQLAlchemy :</p> <pre><code>Base = declarative_base() engine = create_engine(connection_string) metadata = MetaData(bind=engine) </code></pre> <p>Now, we have a link to the db, but need some more work before being able to do anything to it.<br> We create a class corresponding to the table of the db we'll hit. This class will 'autofill' according to how the table is in the db. You can also fill it manually.</p> <pre><code>class TableWellHit(Base): __table__ = Table(name_of_the_table, metadata, autoload=True) </code></pre> <p>Now, to be able to interact with the table, we need to create a session :</p> <pre><code>session = create_session(bind=engine) </code></pre> <p>Now, we need to begin the session, and we'll be set. Your code will now be used. </p> <pre><code>import csv with open("Hypersanal.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter=';') for row in readCSV: # print row # I chose to push each value from the db one by one # If you're sure there won't be any duplicates for the primary key, you can put the session.begin() before the for loop session.begin() # I create an element for the db new_element = TableWellHit(field_in_table=row[field]) </code></pre> <p>An example for this, imagine you have required fiels 'username' and 'password' in the table, and row contains a dictionnary containing 'user' and 'pass' as keys.<br> The elements will be created by : <code>TableWellHit(username=row['user],password=row['pass'])</code></p> <pre><code> # I add the element to the table # I choose to merge instead of add, so as to prevent duplicates, one more time session.merge(new_element) # Now, we commit our changes to the db # This also closes the session # if you put the session.begin() outside of the loop, do the same for the session.commit() session.commit() </code></pre> <p>Hope this answers your question, and if he does not, just let me know so I can correct my answer.</p> <p>edit :<br> For MSSQL :<br> - Install <a href="http://pymssql.org/en/latest/" rel="nofollow">pymssql</a> (<code>pip install pymssql</code>)<br> The <code>connection_string</code> should be of the following form, according to this <a href="http://docs.sqlalchemy.org/en/latest/dialects/mssql.html#module-sqlalchemy.dialects.mssql.pymssql" rel="nofollow">SQLAlchemy page</a> : <code>mssql+pymssql://&lt;username&gt;:&lt;password&gt;@&lt;freetds_name&gt;/?charset=utf8</code></p> <p>Using merge allows you to create or update a value, depending on whether or not it already exists.</p>
0
2016-07-20T09:10:17Z
[ "python", "sql" ]
How to distribute values within a certain range (0 - 1.0)
38,476,292
<p>In Python I have a dictionary of values with a sum of 1.0.</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.10319750541697208} </code></pre> <p>I want to be able to set a new value to one of them, and the difference will distribute evenly to the rest of them. The sum of all values should always be 1.0.</p> <p>I wrote this to do just that.</p> <pre><code>set_inf = "obj_4" set_weight = 0.9 rest = set_weight-weights[set_inf] distribute_count = len(weights)-1 distribute_weight = rest/distribute_count for inf, val in weights.items(): if inf == set_inf: weights[inf] = set_weight else: new_val = val-distribute_weight weights[inf] = new_val print "%s : %s" % (inf, weights[inf]) </code></pre> <p>Which outputs:</p> <pre><code>obj_3 : 0.221688692166 obj_2 : -0.15528656628 obj_1 : -0.149536488904 obj_6 : -0.0649037265111 obj_5 : 0.248038089529 obj_4 : 0.9 Total sum: 1.0 </code></pre> <p>obj_4 is set the value I want, and the sum is equal to 1.0. The problem is I want to make sure each value is never under 0, and never over 1.0.</p> <p>That's where the confusion comes in, and I'm not sure the best way to handle it. If I limit the values, it needs to still compensate to other values otherwise the sum won't be 1.0. How can I achieve something like this?</p> <p><code>set_weight</code> can be any value between 0 to 1.0.</p>
0
2016-07-20T08:37:32Z
38,476,928
<p>It depends a lot on the kind of algorithm you want to implement. If setting the values that become negative in your implementation to zero and distribute the rest of over the remaining ones would work for you, try something like this</p> <pre><code>def updateDict(oldDict, key, val): assert(val &lt;= 1.0) assert(sum(oldDict.values()) == 1.0) while sum(oldDict.values()) + val &gt; 1.0: nVals = len(oldDict) diff = 1. - (sum(oldDict.values()) + val) diffPerVal = diff / nVals for k in oldDict: if oldDict[k] + diffPerVal &gt;= 0.: oldDict[k] += diffPerVal else: oldDict[k] = 0. oldDict[key] = val </code></pre> <p>Now </p> <pre><code>d = {1: 0.5, 2: 0.5} updateDict(d, 3, 0.2) </code></pre> <p>yields <code>d = {1: 0.4, 2: 0.4, 3: 0.2}</code>, while</p> <pre><code>d = {1: 0.2, 2: 0.8} updateDict(d, 3, 0.9) </code></pre> <p>yields <code>d = {1: 0.0, 2: 0.10000000000000009, 3: 0.9}</code>.</p>
3
2016-07-20T09:07:27Z
[ "python", "sum", "distribution" ]
How to distribute values within a certain range (0 - 1.0)
38,476,292
<p>In Python I have a dictionary of values with a sum of 1.0.</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.10319750541697208} </code></pre> <p>I want to be able to set a new value to one of them, and the difference will distribute evenly to the rest of them. The sum of all values should always be 1.0.</p> <p>I wrote this to do just that.</p> <pre><code>set_inf = "obj_4" set_weight = 0.9 rest = set_weight-weights[set_inf] distribute_count = len(weights)-1 distribute_weight = rest/distribute_count for inf, val in weights.items(): if inf == set_inf: weights[inf] = set_weight else: new_val = val-distribute_weight weights[inf] = new_val print "%s : %s" % (inf, weights[inf]) </code></pre> <p>Which outputs:</p> <pre><code>obj_3 : 0.221688692166 obj_2 : -0.15528656628 obj_1 : -0.149536488904 obj_6 : -0.0649037265111 obj_5 : 0.248038089529 obj_4 : 0.9 Total sum: 1.0 </code></pre> <p>obj_4 is set the value I want, and the sum is equal to 1.0. The problem is I want to make sure each value is never under 0, and never over 1.0.</p> <p>That's where the confusion comes in, and I'm not sure the best way to handle it. If I limit the values, it needs to still compensate to other values otherwise the sum won't be 1.0. How can I achieve something like this?</p> <p><code>set_weight</code> can be any value between 0 to 1.0.</p>
0
2016-07-20T08:37:32Z
38,477,286
<p>It does not quite sum up to 1 (I blame float accuracy), but I think you want to do it like this?</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.10319750541697208} set_inf = "obj_4" set_weight = 0.9 rest = set_weight-weights[set_inf] distribute_count = len(weights)-1 distribute_weight = rest/distribute_count sum = 0.0 for inf, val in weights.items(): if inf == set_inf: weights[inf] = set_weight else: weights[inf] = val*(1-set_weight) # this changed print "%s : %s" % (inf, weights[inf]) sum += weights[inf] print "%s" % sum </code></pre> <p>this yields</p> <pre><code>obj_3 : 0.0389789924094 obj_2 : 0.0012814665648 obj_1 : 0.00185647430241 obj_6 : 0.0103197505417 obj_5 : 0.0416139321457 obj_4 : 0.9 0.994050615964 </code></pre> <p>since you already have the fractions in your dictionary, you'd just need to multiply the rest of the numbers by 0.1 (1 - 0.9)? Depends on what you want to achieve.</p>
0
2016-07-20T09:22:03Z
[ "python", "sum", "distribution" ]
How to distribute values within a certain range (0 - 1.0)
38,476,292
<p>In Python I have a dictionary of values with a sum of 1.0.</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.10319750541697208} </code></pre> <p>I want to be able to set a new value to one of them, and the difference will distribute evenly to the rest of them. The sum of all values should always be 1.0.</p> <p>I wrote this to do just that.</p> <pre><code>set_inf = "obj_4" set_weight = 0.9 rest = set_weight-weights[set_inf] distribute_count = len(weights)-1 distribute_weight = rest/distribute_count for inf, val in weights.items(): if inf == set_inf: weights[inf] = set_weight else: new_val = val-distribute_weight weights[inf] = new_val print "%s : %s" % (inf, weights[inf]) </code></pre> <p>Which outputs:</p> <pre><code>obj_3 : 0.221688692166 obj_2 : -0.15528656628 obj_1 : -0.149536488904 obj_6 : -0.0649037265111 obj_5 : 0.248038089529 obj_4 : 0.9 Total sum: 1.0 </code></pre> <p>obj_4 is set the value I want, and the sum is equal to 1.0. The problem is I want to make sure each value is never under 0, and never over 1.0.</p> <p>That's where the confusion comes in, and I'm not sure the best way to handle it. If I limit the values, it needs to still compensate to other values otherwise the sum won't be 1.0. How can I achieve something like this?</p> <p><code>set_weight</code> can be any value between 0 to 1.0.</p>
0
2016-07-20T08:37:32Z
38,501,616
<p>This seems to work the way I was expecting.</p> <pre><code>weights = [0.2, 0.4, 0.3, 0.1] def update_value(index, new_value): dif = (1.0-new_value) / (1.0-weights[index]) for i in range(len(weights)): if i == index: weights[i] = new_value else: weights[i] *= dif </code></pre> <p>This way it works if the new value is smaller or larger than the original value, and all other values propagate accordingly.</p> <pre><code>update_value(1, 0.6) # Returns [0.13333333333333336, 0.6, 0.19999999999999998, 0.06666666666666668] </code></pre> <p>and</p> <pre><code>update_value(1, 0.1) # Returns: [0.30000000000000004, 0.1, 0.44999999999999996, 0.15000000000000002] </code></pre> <p>If there's a better way please feel free to let me know!</p>
0
2016-07-21T10:23:04Z
[ "python", "sum", "distribution" ]
FFT on image with Python
38,476,359
<p>I have a problem with FFT implementation in Python. I have completely strange results. Ok so, I want to open image, get value of every pixel in RGB, then I need to use fft on it, and convert to image again.</p> <p>My steps:</p> <p>1) I'm opening image with PIL library in Python like this</p> <pre><code>from PIL import Image im = Image.open("test.png") </code></pre> <p>2) I'm getting pixels</p> <pre><code>pixels = list(im.getdata()) </code></pre> <p>3) I'm seperate every pixel to r,g,b values</p> <pre><code>for x in range(width): for y in range(height): r,g,b = pixels[x*width+y] red[x][y] = r green[x][y] = g blue[x][y] = b </code></pre> <p>4). Let's assume that I have one pixel (111,111,111). And use fft on all red values like this</p> <pre><code>red = np.fft.fft(red) </code></pre> <p>And then:</p> <pre><code>print (red[0][0],green[0][0],blue[0][0]) </code></pre> <p>My output is:</p> <pre><code>(53866+0j) 111 111 </code></pre> <p>It's completely wrong I think. My image is 64x64, and FFT from gimp is completely different. Actually, my FFT give me only arrays with huge values, thats why my output image is black.</p> <p>Do you have any idea where is problem?</p> <p>[EDIT]</p> <p>I've changed as suggested to</p> <pre><code>red= np.fft.fft2(red) </code></pre> <p>And after that I scale it</p> <pre><code>scale = 1/(width*height) red= abs(red* scale) </code></pre> <p>And still, Im getting only black image.</p> <p>[EDIT2]</p> <p>Ok, so lets take one image. <a href="http://i.stack.imgur.com/H6Gp7.png" rel="nofollow"><img src="http://i.stack.imgur.com/H6Gp7.png" alt="test.png"></a></p> <p>Assume that I dont want to open it and save as greyscale image. So I'm doing like this.</p> <pre><code>def getGray(pixel): r,g,b = pixel return (r+g+b)/3 im = Image.open("test.png") im.load() pixels = list(im.getdata()) width, height = im.size for x in range(width): for y in range(height): greyscale[x][y] = getGray(pixels[x*width+y]) data = [] for x in range(width): for y in range(height): pix = greyscale[x][y] data.append(pix) img = Image.new("L", (width,height), "white") img.putdata(data) img.save('out.png') </code></pre> <p>After this, I'm getting this image <a href="http://i.stack.imgur.com/t8LqJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/t8LqJ.png" alt="greyscale"></a>, which is ok. So now, I want to make fft on my image before I'll save it to new one, so Im doing like this</p> <pre><code>scale = 1/(width*height) greyscale = np.fft.fft2(greyscale) greyscale = abs(greyscale * scale) </code></pre> <p>after loading it. After saving it to file, I have <a href="http://i.stack.imgur.com/ZmHSR.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZmHSR.png" alt="bad FFT"></a>. So lets try now open test.png with gimp and use FFT filter plugin. I'm getting this image, which is correct <a href="http://i.stack.imgur.com/etJgL.png" rel="nofollow"><img src="http://i.stack.imgur.com/etJgL.png" alt="good FFT"></a></p> <p>How I can handle it?</p>
2
2016-07-20T08:40:54Z
38,483,382
<p>There are several issues here.</p> <p><strong>1)</strong> Manual conversion to grayscale isn't good. Use <code>Image.open("test.png").convert('L')</code></p> <p><strong>2)</strong> Most likely there is an issue with types. You shouldn't pass <code>np.ndarray</code> from <code>fft2</code> to a PIL image without being sure their types are compatible. <code>abs(np.fft.fft2(something))</code> will return you an array of type <code>np.float32</code> or something like this, whereas PIL image is going to receive something like an array of type <code>np.uint8</code>.</p> <p><strong>3)</strong> Scaling suggested in the comments looks wrong. You actually need your values to fit into 0..255 range.</p> <p>Here's my code that addresses these 3 points:</p> <pre><code>import numpy as np from PIL import Image def fft(channel): fft = np.fft.fft2(channel) fft *= 255.0 / fft.max() # proper scaling into 0..255 range return np.absolute(fft) input_image = Image.open("test.png") channels = input_image.split() # splits an image into R, G, B channels result_array = np.zeros_like(input_image) # make sure data types, # sizes and numbers of channels of input and output numpy arrays are the save if len(channels) &gt; 1: # grayscale images have only one channel for i, channel in enumerate(channels): result_array[..., i] = fft(channel) else: result_array[...] = fft(channels[0]) result_image = Image.fromarray(result_array) result_image.save('out.png') </code></pre> <p>I must admit I haven't managed to get results identical to the GIMP FFT plugin. As far as I see it does some post-processing. My results are all kinda very low contrast mess, and GIMP seems to overcome this by tuning contrast and scaling down non-informative channels (in your case all chanels except Red are just empty). Refer to the image:</p> <p><a href="http://i.stack.imgur.com/9LM4L.png" rel="nofollow"><img src="http://i.stack.imgur.com/9LM4L.png" alt="enter image description here"></a></p>
0
2016-07-20T13:58:29Z
[ "python", "image", "fft", "dft" ]
FFT on image with Python
38,476,359
<p>I have a problem with FFT implementation in Python. I have completely strange results. Ok so, I want to open image, get value of every pixel in RGB, then I need to use fft on it, and convert to image again.</p> <p>My steps:</p> <p>1) I'm opening image with PIL library in Python like this</p> <pre><code>from PIL import Image im = Image.open("test.png") </code></pre> <p>2) I'm getting pixels</p> <pre><code>pixels = list(im.getdata()) </code></pre> <p>3) I'm seperate every pixel to r,g,b values</p> <pre><code>for x in range(width): for y in range(height): r,g,b = pixels[x*width+y] red[x][y] = r green[x][y] = g blue[x][y] = b </code></pre> <p>4). Let's assume that I have one pixel (111,111,111). And use fft on all red values like this</p> <pre><code>red = np.fft.fft(red) </code></pre> <p>And then:</p> <pre><code>print (red[0][0],green[0][0],blue[0][0]) </code></pre> <p>My output is:</p> <pre><code>(53866+0j) 111 111 </code></pre> <p>It's completely wrong I think. My image is 64x64, and FFT from gimp is completely different. Actually, my FFT give me only arrays with huge values, thats why my output image is black.</p> <p>Do you have any idea where is problem?</p> <p>[EDIT]</p> <p>I've changed as suggested to</p> <pre><code>red= np.fft.fft2(red) </code></pre> <p>And after that I scale it</p> <pre><code>scale = 1/(width*height) red= abs(red* scale) </code></pre> <p>And still, Im getting only black image.</p> <p>[EDIT2]</p> <p>Ok, so lets take one image. <a href="http://i.stack.imgur.com/H6Gp7.png" rel="nofollow"><img src="http://i.stack.imgur.com/H6Gp7.png" alt="test.png"></a></p> <p>Assume that I dont want to open it and save as greyscale image. So I'm doing like this.</p> <pre><code>def getGray(pixel): r,g,b = pixel return (r+g+b)/3 im = Image.open("test.png") im.load() pixels = list(im.getdata()) width, height = im.size for x in range(width): for y in range(height): greyscale[x][y] = getGray(pixels[x*width+y]) data = [] for x in range(width): for y in range(height): pix = greyscale[x][y] data.append(pix) img = Image.new("L", (width,height), "white") img.putdata(data) img.save('out.png') </code></pre> <p>After this, I'm getting this image <a href="http://i.stack.imgur.com/t8LqJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/t8LqJ.png" alt="greyscale"></a>, which is ok. So now, I want to make fft on my image before I'll save it to new one, so Im doing like this</p> <pre><code>scale = 1/(width*height) greyscale = np.fft.fft2(greyscale) greyscale = abs(greyscale * scale) </code></pre> <p>after loading it. After saving it to file, I have <a href="http://i.stack.imgur.com/ZmHSR.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZmHSR.png" alt="bad FFT"></a>. So lets try now open test.png with gimp and use FFT filter plugin. I'm getting this image, which is correct <a href="http://i.stack.imgur.com/etJgL.png" rel="nofollow"><img src="http://i.stack.imgur.com/etJgL.png" alt="good FFT"></a></p> <p>How I can handle it?</p>
2
2016-07-20T08:40:54Z
38,507,628
<p>Great question. I’ve never heard of it but the <a href="http://registry.gimp.org/node/19596" rel="nofollow">Gimp Fourier</a> plugin seems really neat: </p> <blockquote> <p>A simple plug-in to do fourier transform on you image. The major advantage of this plugin is to be able to work with the transformed image inside GIMP. You can so draw or apply filters in fourier space, and get the modified image with an inverse FFT.</p> </blockquote> <p>This idea—of doing Gimp-style manipulation on frequency-domain data and transforming back to an image—is very cool! Despite years of working with FFTs, I’ve never thought about doing this. Instead of messing with Gimp plugins and C executables and ugliness, let’s do this in Python!</p> <p><strong>Caveat.</strong> I experimented with a number of ways to do this, attempting to get something close to the output Gimp Fourier image (gray with moiré pattern) from the original input image, but I simply couldn’t. The Gimp image appears to be somewhat symmetric around the middle of the image, but it’s not flipped vertically or horizontally, nor is it transpose-symmetric. I’d expect the plugin to be using a real 2D FFT to transform an H×W image into a H×W array of real-valued data in the frequency domain, in which case there would be no symmetry (it’s just the to-complex FFT that’s conjugate-symmetric for real-valued inputs like images). So I gave up trying to reverse-engineer what the Gimp plugin is doing and looked at how I’d do this from scratch.</p> <p><strong>The code.</strong> Very simple: read an image, apply <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.rfft.html" rel="nofollow"><code>scipy.fftpack.rfft</code></a> in the leading two dimensions to get the “frequency-image”, rescale to 0–255, and save. </p> <p>Note how this is different from the other answers! <em>No grayscaling</em>—the 2D real-to-real FFT happens independently on all three channels. <em>No <code>abs</code> needed</em>: the frequency-domain image can legitimately have negative values, and if you make them positive, you can’t recover your original image. (Also a nice feature: <em>no compromises on image size</em>. The size of the array remains the same before and after the FFT, whether the width/height is even or odd.)</p> <pre><code>from PIL import Image import numpy as np import scipy.fftpack as fp ## Functions to go from image to frequency-image and back im2freq = lambda data: fp.rfft(fp.rfft(data, axis=0), axis=1) freq2im = lambda f: fp.irfft(fp.irfft(f, axis=1), axis=0) ## Read in data file and transform data = np.array(Image.open('test.png')) freq = im2freq(data) back = freq2im(freq) # Make sure the forward and backward transforms work! assert(np.allclose(data, back)) ## Helper functions to rescale a frequency-image to [0, 255] and save remmax = lambda x: x/x.max() remmin = lambda x: x - np.amin(x, axis=(0,1), keepdims=True) touint8 = lambda x: (remmax(remmin(x))*(256-1e-4)).astype(int) def arr2im(data, fname): out = Image.new('RGB', data.shape[1::-1]) out.putdata(map(tuple, data.reshape(-1, 3))) out.save(fname) arr2im(touint8(freq), 'freq.png') </code></pre> <p>(<strong>Aside: FFT-lover geek note.</strong> Look at the documentation for <code>rfft</code> for details, but I used Scipy’s FFTPACK module because its <code>rfft</code> interleaves real and imaginary components of a single pixel as two adjacent real values, guaranteeing that the output for any-sized 2D image (even vs odd, width vs height) will be preserved. This is in contrast to Numpy’s <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft2.html" rel="nofollow"><code>numpy.fft.rfft2</code></a> which, because it returns complex data of size <code>width/2+1</code> by <code>height/2+1</code>, forces you to deal with one extra row/column and deal with deinterleaving complex-to-real yourself. Who needs that hassle for this application.)</p> <p><strong>Results.</strong> Given input named <code>test.png</code>:</p> <p><a href="http://i.stack.imgur.com/c3M06.png" rel="nofollow"><img src="http://i.stack.imgur.com/c3M06.png" alt="test input"></a></p> <p>this snippet produces the following output (global min/max have been rescaled and quantized to 0-255):</p> <p><a href="http://i.stack.imgur.com/upFcG.png" rel="nofollow"><img src="http://i.stack.imgur.com/upFcG.png" alt="test output, frequency domain"></a></p> <p>And upscaled:</p> <p><a href="http://i.stack.imgur.com/qUKnO.png" rel="nofollow"><img src="http://i.stack.imgur.com/qUKnO.png" alt="frequency, upscaled"></a></p> <p>In this frequency-image, the DC (0 Hz frequency) component is in the top-left, and frequencies move higher as you go right and down.</p> <p>Now, let’s see what happens when you manipulate this image in a couple of ways. Instead of this test image, let’s use a <a href="https://www.flickr.com/photos/davispuh/9230485361/" rel="nofollow">cat photo</a>.</p> <p><a href="http://i.stack.imgur.com/WfGjr.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/WfGjr.jpg" alt="original cat"></a></p> <p>I made a few mask images in Gimp that I then load into Python and multiply the frequency-image with to see what effect the mask has on the image.</p> <p>Here’s the code:</p> <pre><code># Make frequency-image of cat photo freq = im2freq(np.array(Image.open('cat.jpg'))) # Load three frequency-domain masks (DSP "filters") bpfMask = np.array(Image.open('cat-mask-bpfcorner.png')).astype(float) / 255 hpfMask = np.array(Image.open('cat-mask-hpfcorner.png')).astype(float) / 255 lpfMask = np.array(Image.open('cat-mask-corner.png')).astype(float) / 255 # Apply each filter and save the output arr2im(touint8(freq2im(freq * bpfMask)), 'cat-bpf.png') arr2im(touint8(freq2im(freq * hpfMask)), 'cat-hpf.png') arr2im(touint8(freq2im(freq * lpfMask)), 'cat-lpf.png') </code></pre> <p>Here’s a <strong>low-pass filter</strong> mask on the left, and on the right, the result—click to see the full-res image:</p> <p><a href="http://i.stack.imgur.com/ad4pn.png" rel="nofollow"><img src="http://i.stack.imgur.com/ad4pn.png" alt="low-passed cat"></a></p> <p>In the mask, black = 0.0, white = 1.0. So the lowest frequencies are kept here (white), while the high ones are blocked (black). This blurs the image by attenuating high frequencies. Low-pass filters are used all over the place, including when decimating (“downsampling”) an image (though they will be shaped much more carefully than me drawing in Gimp 😜).</p> <p>Here’s a <strong>band-pass filter</strong>, where the lowest frequencies (see that bit of white in the top-left corner?) and high frequencies are kept, but the middling-frequencies are blocked. Quite bizarre!</p> <p><a href="http://i.stack.imgur.com/4jDV9.png" rel="nofollow"><img src="http://i.stack.imgur.com/4jDV9.png" alt="band-passed cat"></a></p> <p>Here’s a <strong>high-pass filter</strong>, where the top-left corner that was left white in the above mask is blacked out:</p> <p><a href="http://i.stack.imgur.com/l9eED.png" rel="nofollow"><img src="http://i.stack.imgur.com/l9eED.png" alt="high-passed filter"></a></p> <p>This is how edge-detection works.</p> <p><strong>Postscript.</strong> Someone, make a webapp using this technique that lets you draw masks and apply them to an image real-time!!!</p>
1
2016-07-21T14:55:46Z
[ "python", "image", "fft", "dft" ]
Python Matplotlib - imshow but with hexagons
38,476,373
<p>Code is:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import colors example_data = np.random.randint(4, size=(40,44)) cmap = colors.ListedColormap(['black', 'green', 'red', 'blue']) bounds = [0,1,2,3,4] norm = colors.BoundaryNorm(bounds, cmap.N) img = plt.imshow(example_data, interpolation = 'nearest', origin = 'lower', cmap = cmap, norm = norm) </code></pre> <p>Which gets me roughly what I want. What I am looking for is if there is a way to get the shape of each tile to be hexagonal rather than square? I think imshow might not be the way to do it but if there is a way you can change the default tile it would be good.</p> <p>Thanks.</p>
0
2016-07-20T08:41:33Z
38,477,407
<p>You could use a scatter plot with coloured hexagons,</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import colors nx = 40 ny = 44 example_data = np.random.randint(4, size=(nx,ny)) cmap = colors.ListedColormap(['black', 'green', 'red', 'blue']) bounds = [0,1,2,3,4] norm = colors.BoundaryNorm(bounds, cmap.N) x = np.linspace(0, 1, nx) y = np.linspace(0, 1, ny) X, Y = np.meshgrid(x, y) img = plt.scatter(X.ravel(),Y.ravel(),c=example_data.ravel(), cmap=cmap, norm=norm, s=360, marker=(6, 0), alpha=0.4) plt.colorbar(img) plt.show() </code></pre> <p>which looks like,</p> <p><a href="http://i.stack.imgur.com/KkqkY.png" rel="nofollow"><img src="http://i.stack.imgur.com/KkqkY.png" alt="enter image description here"></a></p>
0
2016-07-20T09:26:32Z
[ "python", "matplotlib", "imshow" ]
BSON object size of document retrieved from DB
38,476,377
<p>Mongo shell have <a href="https://docs.mongodb.com/v3.2/reference/mongo-shell/#miscellaneous" rel="nofollow">the bsonsize() method</a> to get BSON size of a given document retrieved from DB.</p> <p>Is there any way of getting the same using PyMongo driver? I have found the <a href="http://api.mongodb.com/python/current/api/bson/index.html" rel="nofollow">bson module</a> in the documentation but it is not fully clear to me how to use it to get the size of a document retrieved from DB.</p>
-1
2016-07-20T08:41:45Z
38,488,713
<p>Based on @SSDMS suggestion (thanks!) the following can be used:</p> <pre><code>len(bson.BSON.encode(document)) </code></pre> <p>I have tested with a couple of documents in my DB, comparing the result at mongo shell and with the above Python method and getting the same result:</p> <p>At mongo shell:</p> <pre><code>&gt; var doc1 = db.entities.findOne({'_id.id': '001'}) &gt; var doc2 = db.entities.findOne({'_id.id': '002'}) &gt; Object.bsonsize(doc1) 816 &gt; Object.bsonsize(doc2) 819 </code></pre> <p>At Python console:</p> <pre><code>&gt;&gt;&gt; import bson &gt;&gt;&gt; from pymongo import MongoClient &gt;&gt;&gt; db = MongoClient('localhost', 27017) &gt;&gt;&gt; doc1 = db['orion']['entities'].find_one({'_id.id': '001'}) &gt;&gt;&gt; doc2 = db['orion']['entities'].find_one({'_id.id': '002'}) &gt;&gt;&gt; len(bson.BSON.encode(doc1)) 816 &gt;&gt;&gt; len(bson.BSON.encode(doc2)) 819 </code></pre>
0
2016-07-20T18:57:50Z
[ "python", "mongodb", "pymongo", "bson" ]
How can I get IntelliJ to index libraries in my Python Conda environment?
38,476,379
<p>I am using Python with Conda to manage my environment and libraries. Does anyone know how to get IntelliJ (with the Python plugin) or PyCharm to add the libraries in my Conda environment to my project?</p> <p>It only pulls in site packages even when I select ~/anaconda/bin/python as my Python Interpreter.</p>
0
2016-07-20T08:41:47Z
38,732,023
<p>You ned to change your <code>Project Interpreter</code> to point to <code>$CONDA_PREFIX/bin/python</code> where <code>$CONDA_PREFIX</code> is the <em>location</em> of your conda env. The <code>$CONDA_PREFIX</code> environment location you're looking for should be in the second column of the output from <code>conda info --envs</code>.</p>
1
2016-08-02T23:28:10Z
[ "python", "intellij-idea", "pycharm", "conda" ]
Detecting events in a pandas data frame
38,476,501
<p>I have a pandas dataframe consisting of 0,1,-1's.</p> <pre><code>import pandas as pd df=pd.DataFrame({'indicator':[0, 0, 0, -1,0,0,1,0,-1,1,0,-1,0,1]}) </code></pre> <p>and I wan't to find the indices of every -1 and 1 such that the -1 is followed by some or none zeros and a +1. For exapmle in the above example I want to get </p> <pre><code>[(3,6),(8,9),(11,13)] </code></pre>
6
2016-07-20T08:46:55Z
38,476,905
<pre><code>s = pd.DataFrame({'indicator':[0, 0, 0, -1, 0, 0, 1, 0, -1, 1, 0, -1, 0, 1]}).squeeze() # reduce it to non-zeros s1 = s[s!=0] # must be -1 and next one be 1, grab index idx = s1.loc[(s1 == -1) &amp; (s1 != s1.shift(-1))].index # grab s1 index and next index s2 = s1.index.to_series().shift(-1).loc[idx].astype(int) # zip to get tuples zip(s2.index, s2.values) [(3, 6), (8, 9), (11, 13)] </code></pre>
6
2016-07-20T09:06:21Z
[ "python", "pandas" ]
Why do I get False when using issubclass in this way?
38,476,523
<pre><code># structure package/ m1.py m2.py # m1.py class A: pass if __name__ == '__main__': from m2 import B print(issubclass(B, A)) # m2.py from m1 import A class B(A): pass </code></pre> <p>I don't now why I get false while I think it's obviously true when I run m1.py. My python version is python3.5.2. </p>
0
2016-07-20T08:47:37Z
38,476,700
<p>You have to derive class <code>A</code> from <code>object</code> to get <code>issubclass</code> do its job:</p> <p><a href="http://stackoverflow.com/questions/8107313/isinstance-and-issubclass-behavior-differently">isinstance() and issubclass() behavior differently</a></p> <pre><code>class A(object): ... </code></pre> <p>Here an example of python cli:</p> <pre><code>&gt;&gt;&gt; class A(object): pass &gt;&gt;&gt; class B(A): pass &gt;&gt;&gt; issubclass(B,A) True </code></pre>
2
2016-07-20T08:56:08Z
[ "python", "python-3.x" ]
Why do I get False when using issubclass in this way?
38,476,523
<pre><code># structure package/ m1.py m2.py # m1.py class A: pass if __name__ == '__main__': from m2 import B print(issubclass(B, A)) # m2.py from m1 import A class B(A): pass </code></pre> <p>I don't now why I get false while I think it's obviously true when I run m1.py. My python version is python3.5.2. </p>
0
2016-07-20T08:47:37Z
38,476,782
<p>You create 2 class objects, derived from the same class. That is: the class code is executed twice and thus results in 2 objects. And those are not the same. Example: see the output of the <code>print</code> statements below</p> <pre><code># m2.py from m1 import A class B(A): pass print(A) # m1.py class A: pass if __name__ == '__main__': from m2 import B print(A) print(issubclass(B, A)) # Output #&lt;class 'm1.A'&gt; #&lt;class '__main__.A'&gt; #False </code></pre> <p>Also: see <a href="http://stackoverflow.com/a/11461574/5488275">this answer</a> for more information.</p>
1
2016-07-20T09:00:06Z
[ "python", "python-3.x" ]
Why do I get False when using issubclass in this way?
38,476,523
<pre><code># structure package/ m1.py m2.py # m1.py class A: pass if __name__ == '__main__': from m2 import B print(issubclass(B, A)) # m2.py from m1 import A class B(A): pass </code></pre> <p>I don't now why I get false while I think it's obviously true when I run m1.py. My python version is python3.5.2. </p>
0
2016-07-20T08:47:37Z
38,477,315
<p>Wellcome to the world of modules and namespaces!</p> <p>Here is what happens:</p> <p>In module m2, you import A from module m1. So you create a class <code>m2.A</code> as a reference to class <code>m1.A</code>. It happens to have the same definition as <code>__main__.A</code>, but they are different objects, because the main module is named <code>__main__</code> and not <code>m1</code>. Then in module <code>__main__</code> you create a class <code>__main__.B</code> as a reference to class <code>m2.B</code></p> <p>To better understand what happens here, I have added some code to m1:</p> <pre><code>... print(issubclass(B, A)) import m1 import m2 print(A == m1.A, m1.A == m2.A) print(B == m2.B) print(issubclass(B, m2.A), issubclass(B, m1.A)) </code></pre> <p>The output is:</p> <pre class="lang-none prettyprint-override"><code>False False True True True True </code></pre> <p>Proving that B is indeed a subclass of <code>m1.A</code> but not of <code>__main.A</code>.</p>
1
2016-07-20T09:23:12Z
[ "python", "python-3.x" ]
Debugger doesn't work out of a sudden in PyCharm
38,476,563
<p>I'm using:<br></p> <pre><code>PyCharm 2016.1.4 Build #PY-145.1504, built on May 25, 2016 JRE: 1.8.0_76-release-b198 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o </code></pre> <p>On a mac:</p> <pre><code>OSX El Capitan Version 10.11.4 </code></pre> <p>Without having made any changes to my code, I haven't been able to start the debugger anymore. I'm still able to use Run without any problem.</p> <p>Also the debugger doesn't work if I just run it from the terminal with: </p> <pre><code>/Users/Vandborg/.virtualenvs/hungry/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 54596 --file /Users/Vandborg/dev/dowant/dowant/manage.py runserver </code></pre> <p>It throws an unhandled excetions which can be seen here:</p> <pre><code>/Users/Vandborg/.virtualenvs/hungry/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 54596 --file /Users/Vandborg/dev/dowant/dowant/manage.py runserver pydev debugger: process 10046 is connecting Connected to pydev debugger (build 145.1504) pydev debugger: process 10055 is connecting Validating models... Unhandled exception in thread started by &lt;_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x107455248&gt; Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 553, in __call__ return self.original_func(*self.args, **self.kwargs) File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/db/models/loading.py", line 146, in get_app_errors self._populate() File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/db/models/loading.py", line 61, in _populate self.load_app(app_name, True) File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in load_app models = import_module('.models', app_name) File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/Vandborg/dev/dowant/dowant/apps/box_helicom/models.py", line 161, in &lt;module&gt; class MessageHelicom(models.Model): File "/Users/Vandborg/dev/dowant/dowant/apps/box_helicom/models.py", line 178, in MessageHelicom from dowant.cart.models import Order File "/Users/Vandborg/dev/dowant/dowant/cart/models.py", line 44, in &lt;module&gt; from dowant.cart.tasks import backend_cache, order_status File "/Users/Vandborg/dev/dowant/dowant/cart/tasks/__init__.py", line 1, in &lt;module&gt; from backend_cache import refresh_order_backend_cache File "/Users/Vandborg/dev/dowant/dowant/cart/tasks/backend_cache.py", line 2, in &lt;module&gt; from dowant.backend.models import OrderBackendCache File "/Users/Vandborg/dev/dowant/dowant/backend/models.py", line 18, in &lt;module&gt; from dowant.backend.tooltips import (tr_class_template, File "/Users/Vandborg/dev/dowant/dowant/backend/tooltips.py", line 53, in &lt;module&gt; '{% load localization %}' File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/template/__init__.py", line 158, in __init__ self.nodelist = compile_string(template_string, origin) File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/template/__init__.py", line 186, in compile_string return parser.parse() File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/template/__init__.py", line 282, in parse compiled_result = compile_func(self, token) File "/Users/Vandborg/.virtualenvs/hungry/lib/python2.7/site-packages/django/template/defaulttags.py", line 928, in load (taglib, e)) django.template.TemplateSyntaxError: 'localization' is not a valid tag library: ImportError raised loading dowant.templatetags.localization: cannot import name helper_evalifnotquoted </code></pre> <p>The code in dowant.templatetags.localization haven't been touched in years. And well it is able to run, it's just doing this when I try to use it with the debugger.</p>
0
2016-07-20T08:50:01Z
38,481,440
<p>Disregard. I found the issue, there was a difference in which order stuff was loaded with debug and run, and therefore helper_evalifnotquoted couldn't be resolved.</p>
0
2016-07-20T12:33:04Z
[ "python", "django", "osx", "debugging", "pycharm" ]
Python requests call with URL using parameters
38,476,648
<p>I am trying to make a call to the import.io API. This call needs to have the following structure:</p> <blockquote> <p>'<a href="https://extraction.import.io/query/extractor/" rel="nofollow">https://extraction.import.io/query/extractor/</a>{{crawler_id}}?_apikey=xxx&amp;url=<a href="http://www.example.co.uk/items.php?sortby=Price_LH&amp;per_page=96&amp;size=1%2C12&amp;page=35" rel="nofollow">http://www.example.co.uk/items.php?sortby=Price_LH&amp;per_page=96&amp;size=1%2C12&amp;page=35</a>'</p> </blockquote> <p>You can see in that call, the parameter "url" has to be also included: </p> <blockquote> <p><a href="http://www.example.co.uk/items.php?sortby=Price_LH&amp;per_page=96&amp;size=1%2C12&amp;page=35" rel="nofollow">http://www.example.co.uk/items.php?sortby=Price_LH&amp;per_page=96&amp;size=1%2C12&amp;page=35</a></p> </blockquote> <p>It just so happens that this secondary URL also needs parameters. But if I pass it as a normal string like in the example above, the API response only includes the part before the first parameter when I get the API response:</p> <blockquote> <p><a href="http://www.example.co.uk/items.php?sortby=Price_LH" rel="nofollow">http://www.example.co.uk/items.php?sortby=Price_LH</a></p> </blockquote> <p>And this is not correct, it appears as if it would be making the call with the incomplete URL instead of the one I passed in.</p> <p>I am using Python and requests to do the call in the following way:</p> <pre><code>import requests import json row_dict = {'url': u'http://www.example.co.uk/items.php?sortby=Price_LH&amp;per_page=96&amp;size=1%2C12&amp;page=35', 'crawler_id': u'zzz'} url_call = 'https://extraction.import.io/query/extractor/{0}?_apikey={1}&amp;url={2}'.format(row_dict['crawler_id'], auth_key, row_dict['url']) r = requests.get(url_call) rr = json.loads(r.content) </code></pre> <p>And when I print the reuslt:</p> <pre><code>"url" : "http://www.example.co.uk/items.php?sortby=Price_LH", </code></pre> <p>but when I print r.url:</p> <pre><code>https://extraction.import.io/query/extractor/zzz?_apikey=xxx&amp;url=http://www.example.co.uk/items.php?sortby=Price_LH&amp;per_page=96&amp;size=1%2C12&amp;page=35 </code></pre> <p>So in the URL it all seems to be fine but not in the response.</p> <p>I tried this with other URLs and all get cut after the first parameter.</p>
2
2016-07-20T08:53:28Z
38,477,032
<p>you will need to <a href="http://www.w3schools.com/tags/ref_urlencode.asp">URL encode</a> the URL you are sending to the API.</p> <p>The reason for this is that the ampersands are interpretted by the server as markers for parameters for the URL <a href="https://extraction.import.io/query/extractor/XXX">https://extraction.import.io/query/extractor/XXX</a>?</p> <p>This is why they are getting stripped in the url:</p> <pre><code>http://www.example.co.uk/items.php?sortby=Price_LH </code></pre> <p>Try the following using <code>urllib.quote(row_dict['url'])</code>:</p> <pre><code>import requests import json import urllib row_dict = {'url': u'http://www.example.co.uk/items.php?sortby=Price_LH&amp;per_page=96&amp;size=1%2C12&amp;page=35', 'crawler_id': u'zzz'} url_call = 'https://extraction.import.io/query/extractor/{0}?_apikey={1}&amp;url={2}'.format(row_dict['crawler_id'], auth_key, urllib.quote(row_dict['url'])) r = requests.get(url_call) rr = json.loads(r.content) </code></pre>
5
2016-07-20T09:11:19Z
[ "python", "python-requests", "import.io" ]
Django middleware 'module' object is not callable
38,476,711
<p>I have problem with middleware I found a lot of questions about it but nothing help in my case.</p> <p>I use middleware to get current_user to use in my model to save modified user in save method without write this in view.</p> <p>Here is <a href="http://stackoverflow.com/questions/862522/django-populate-user-id-when-saving-a-model">original post</a> with this code: </p> <p><strong>Middleware</strong></p> <pre><code>from threading import local _user = local() class CurrentUserMiddleware(object): def process_request(self, request): _user.value = request.user def get_current_user(): return _user.value </code></pre> <p><strong>There is something wrong in this code because I'm getting error like:</strong></p> <pre><code>Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\Lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\contrib\staticfiles\handlers.py", line 63, in __call__ return self.application(environ, start_response) File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\core\handlers\wsgi.py", line 158, in __call__ self.load_middleware() File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\core\handlers\base.py", line 53, in load_middleware mw_instance = mw_class() TypeError: 'module' object is not callable [20/Jul/2016 10:51:44] "GET /panel/ HTTP/1.1" 500 59 Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\Lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\contrib\staticfiles\handlers.py", line 63, in __call__ return self.application(environ, start_response) File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\core\handlers\wsgi.py", line 158, in __call__ self.load_middleware() File "C:\Users\loc\dJangoEnvironment\lib\site-packages\django\core\handlers\base.py", line 53, in load_middleware mw_instance = mw_class() TypeError: 'module' object is not callable [20/Jul/2016 10:51:44] "GET /favicon.ico HTTP/1.1" 500 59 </code></pre> <p><strong>My middleware settings:</strong></p> <pre><code>MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'reversion.middleware.RevisionMiddleware', 'task.current_user', ) </code></pre> <p>Can you give me some advice where is error or something? I don't have any other idea to try so I hope that you have some.</p>
-2
2016-07-20T08:56:41Z
38,477,514
<p>You must give the full path of your middleware <strong>class</strong>. Not the module containing the middleware.</p> <pre><code>MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'reversion.middleware.RevisionMiddleware', 'task.current_user.CurrentUserMiddleware', ) </code></pre> <p>Note that you had plenty of examples right above.</p>
2
2016-07-20T09:32:27Z
[ "python", "django", "django-middleware" ]
Pandas.read_excel: Accessing the home directory
38,476,733
<p><strong>[Solution Found]</strong></p> <p>I have encountered some unexpected behavior when trying to access my home directory using <code>pandas.read_excel</code>.</p> <p>The file I want to access can be found at</p> <pre><code>/users/isys/orsheridanmeth </code></pre> <p>which is where <code>cd ~/</code> takes me to. The file I would like to access is</p> <pre><code>'~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx' </code></pre> <p>The following works to read in the excel file (using <code>import pandas as pd</code>):</p> <pre><code>df = pd.read_excel('workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx', 'Sheet1') </code></pre> <p>whereas </p> <pre><code>df = pd.read_excel('~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx', 'Sheet1') </code></pre> <p>gives me the following error:</p> <pre><code>df = pd.read_excel('~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx', 'Sheet1') Traceback (most recent call last): File "/users/is/ahlpypi/egg_cache/i/ipython-3.2.0_1_ahl1-py2.7.egg/IPython/core/interactiveshell.py", line 3035, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-397-4412a9e7c128&gt;", line 1, in &lt;module&gt; df = pd.read_excel('~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx', 'Sheet1') File "/users/is/ahlpypi/egg_cache/p/pandas-0.16.2_ahl1-py2.7-linux-x86_64.egg/pandas/io/excel.py", line 151, in read_excel return ExcelFile(io, engine=engine).parse(sheetname=sheetname, **kwds) File "/users/is/ahlpypi/egg_cache/p/pandas-0.16.2_ahl1-py2.7-linux-x86_64.egg/pandas/io/excel.py", line 188, in __init__ self.book = xlrd.open_workbook(io) File "/users/is/ahlpypi/egg_cache/x/xlrd-0.9.2-py2.7.egg/xlrd/__init__.py", line 394, in open_workbook f = open(filename, "rb") IOError: [Errno 2] No such file or directory: '~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx' </code></pre> <p><strong>pandas.read_csv</strong> however worked when I used <code>pd.read_csv('~/workspace/tip_rank/data/example_TRESS-2016-7-5.csv')</code>.</p> <p>I would like to continue to use this relative paths to files. Any explanation why this doesn't work with <code>pandas.read_excel</code>?</p> <p><strong>Using <code>xlrd</code></strong></p> <p>when using <code>xlrd</code> I get a similar error: </p> <pre><code>import xlrd xl = xlrd.open_workbook('~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx') Traceback (most recent call last): File "/users/is/ahlpypi/egg_cache/i/ipython-3.2.0_1_ahl1-py2.7.egg/IPython/core/interactiveshell.py", line 3035, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-403-90af31feff4b&gt;", line 1, in &lt;module&gt; xl = xlrd.open_workbook('~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx') File "/users/is/ahlpypi/egg_cache/x/xlrd-0.9.2-py2.7.egg/xlrd/__init__.py", line 394, in open_workbook f = open(filename, "rb") IOError: [Errno 2] No such file or directory: '~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx' </code></pre> <p><strong>[SOLUTION]</strong></p> <pre><code>from os.path import expanduser as ospath df = pd.read_excel(ospath('~/workspace/tip_rank/data/example_TipRanksBloggersRawDataFeed.xlsx'), 'Sheet1') </code></pre>
2
2016-07-20T08:57:33Z
38,476,908
<p>I believe <code>~</code> is expanded by the shell - in which case your code is literally trying to open a path starting with <code>~</code>. Oddly enough this doesn't work. :-)</p> <p>Try running the path through <code>os.path.expanduser()</code> first - that should work to expand the <code>~</code> variable to the real value.</p> <p>You may also want to look into <code>os.path.expandvars()</code>.</p> <p>Hope that helps</p>
4
2016-07-20T09:06:29Z
[ "python", "pandas", "path" ]
Finding all possible paths between two nodes in a large graph
38,476,795
<p>I'm using the following python code for finding all possible paths between two nodes but it return any thing, just waits for running.</p> <pre><code>def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [] if start not in graph: return [] paths = [] for node in graph[start]: if node not in path: print (node) newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths </code></pre> <p>My graph has about 4K nodes and 23K edges.</p>
-1
2016-07-20T09:00:52Z
38,477,060
<p>One solution is using dynamic programming which I don't know how to use that</p>
0
2016-07-20T09:12:47Z
[ "python", "graph", "path", "dfs" ]
Printing neutron ports
38,476,799
<p>When I do this: <code>neutron.list_ports()</code></p> <p>It gives me : </p> <blockquote> <p>{'ports': [{u'status': u'DOWN', u'name': u'', u'allowed_address_pairs': [], u'admin_state_up': True, u'network_id': u'-xxxx-84f2-e881c29879e2', u'dns_name': u'', xxxx': [], u'dns_assignment': [{u'hostname': u'host-134-xxxxx-xxx', u'ip_address': u'134.158.xx.xx', u'fqdn': u'host-134-158-75-xxx ... }</p> </blockquote> <p>I only want to display the <code>u'ip_address'</code> field.</p> <p>I hope you can help me :)</p> <p>Thank you.</p>
-1
2016-07-20T09:01:05Z
38,476,858
<p>It seems like there could be multiple ports but if you just need the first ip you should be able to do:</p> <pre><code>neutron.list_ports()["ports"][0]["dns_assignment"][0]["ip_addess"] </code></pre> <p>this will return the first ip you should probably check if any of this is null first though</p>
0
2016-07-20T09:04:41Z
[ "python", "django", "openstack" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? </p> <pre><code>&gt;&gt;&gt; text = 'the quick brown fox jumps over the lazy dog' &gt;&gt;&gt; adjectives = ['slow', 'quick', 'brown', 'lazy'] &gt;&gt;&gt; if any(word in text for word in adjectives): ... firstAdjective = word ... Traceback (most recent call last): File "&lt;interactive input&gt;", line 2, in &lt;module&gt; NameError: name 'word' is not defined </code></pre>
3
2016-07-20T09:05:19Z
38,476,971
<p>You can use <code>next</code> on a <em>generator expression</em>:</p> <pre><code>firstAdjective = next((word for word in adjectives if word in text), None) if firstAdjective: ... </code></pre> <p>A default value of <code>None</code> is returned when the word is not found (credit @Bakuriu)</p> <p><strong>Trial</strong>:</p> <pre><code>&gt;&gt;&gt; firstadjective = next((word for word in adjectives if word in text), None) &gt;&gt;&gt; firstadjective 'quick' </code></pre>
1
2016-07-20T09:09:00Z
[ "python", "scope", "any" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? </p> <pre><code>&gt;&gt;&gt; text = 'the quick brown fox jumps over the lazy dog' &gt;&gt;&gt; adjectives = ['slow', 'quick', 'brown', 'lazy'] &gt;&gt;&gt; if any(word in text for word in adjectives): ... firstAdjective = word ... Traceback (most recent call last): File "&lt;interactive input&gt;", line 2, in &lt;module&gt; NameError: name 'word' is not defined </code></pre>
3
2016-07-20T09:05:19Z
38,477,096
<p>Would something like</p> <pre><code>for word in filter(lambda x: x in adjectives, text.split()): print word </code></pre> <p>work?</p>
0
2016-07-20T09:14:12Z
[ "python", "scope", "any" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? </p> <pre><code>&gt;&gt;&gt; text = 'the quick brown fox jumps over the lazy dog' &gt;&gt;&gt; adjectives = ['slow', 'quick', 'brown', 'lazy'] &gt;&gt;&gt; if any(word in text for word in adjectives): ... firstAdjective = word ... Traceback (most recent call last): File "&lt;interactive input&gt;", line 2, in &lt;module&gt; NameError: name 'word' is not defined </code></pre>
3
2016-07-20T09:05:19Z
38,477,305
<p>Your example does not work because the <code>word</code> variable only exists during the evaluation of the condition. Once it is done finding whether the condition is true or false, the variable goes out of scope and does not exist anymore. </p> <p>Even declaring it first doesn't help, as it doesn't affect the existing variable:</p> <pre><code>text = 'the quick brown fox jumps over the lazy dog' adjectives = ['slow', 'quick', 'brown', 'lazy'] word = None if any(word in text for word in adjectives): print(word) </code></pre> <blockquote> <p>None</p> </blockquote> <p>Therefore, you have to do it differently, using the <code>next</code> function:</p> <pre><code>text = 'the quick brown fox jumps over the lazy dog' adjectives = ['slow', 'quick', 'brown', 'lazy'] word = next((word for word in adjectives if word in text), None) if word: print(word) </code></pre> <blockquote> <p>quick</p> </blockquote> <p>Note, perhaps <code>word</code> is a misleading variable name here, because it doesn't necessarily have to match a whole word. i.e.</p> <pre><code>text = 'the quick brown fox jumps over the lazy dog' adjectives = ['slo', 'uick', 'rown', 'azy'] word = next((word for word in adjectives if word in text), None) if word: print(word) </code></pre> <blockquote> <p>uick</p> </blockquote> <p>so it might be best to split the text into words first:</p> <pre><code>text = 'the quick brown fox jumps over the lazy dog' adjectives = ['slow', 'quick', 'brown', 'lazy'] word_list = text.split() word = next((word for word in adjectives if word in word_list), None) if word: print(word) </code></pre> <p>but note that if we change the adjectives order:</p> <pre><code>text = 'the quick brown fox jumps over the lazy dog' adjectives = ['brown', 'quick', 'slow', 'lazy'] word_list = text.split() word = next((word for word in adjectives if word in word_list), None) if word: print(word) </code></pre> <p>we get:</p> <blockquote> <p>brown</p> </blockquote> <p>which isn't the first adjective in the text.</p> <p>Therefore, we need to check in the order of the words in the text, not the order of adjectives in the list.</p> <pre><code>text = 'the quick brown fox jumps over the lazy dog' adjectives = ['brown', 'quick', 'slow', 'lazy'] word_list = text.split() # NOTE: this "optimization" is no longer necessary now word = next((word for word in word_list if word in adjectives), None) if word: print(word) </code></pre> <p><a href="http://stackoverflow.com/questions/38476877/python-expanding-the-scope-of-the-iterator-variable-in-the-any-function/38477305?noredirect=1#comment64357249_38477305">credit to HolyDanna for spotting this</a></p>
0
2016-07-20T09:22:52Z
[ "python", "scope", "any" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? </p> <pre><code>&gt;&gt;&gt; text = 'the quick brown fox jumps over the lazy dog' &gt;&gt;&gt; adjectives = ['slow', 'quick', 'brown', 'lazy'] &gt;&gt;&gt; if any(word in text for word in adjectives): ... firstAdjective = word ... Traceback (most recent call last): File "&lt;interactive input&gt;", line 2, in &lt;module&gt; NameError: name 'word' is not defined </code></pre>
3
2016-07-20T09:05:19Z
38,478,069
<pre><code>&gt;&gt;&gt; text = 'the quick brown fox jumps over the lazy dog' &gt;&gt;&gt; &gt;&gt;&gt; # 1. Case with no match among the adjectives: Result None as expected &gt;&gt;&gt; adjectives = ['slow', 'crippled'] &gt;&gt;&gt; firstAdjective = next((word for word in adjectives if word in text), None) &gt;&gt;&gt; firstAdjective &gt;&gt;&gt; &gt;&gt;&gt; # 2. Case with a match to 1st available in adjectives but actually 2nd in the text &gt;&gt;&gt; adjectives = ['slow', 'brown', 'quick', 'lazy'] &gt;&gt;&gt; firstAdjective = next((word for word in adjectives if word in text), None) &gt;&gt;&gt; firstAdjective 'brown' &gt;&gt;&gt; # 3. Case with a match to 1st available in the text, which is what is wanted &gt;&gt;&gt; firstAdjective = next((word for word in text.split() if word in adjectives), None) &gt;&gt;&gt; firstAdjective 'quick' &gt;&gt;&gt; # 4. Case where .split() is omitted. NOTE: This does not work. &gt;&gt;&gt; # In python 2.7 at least, .split() is required &gt;&gt;&gt; firstAdjective = next((word for word in text if word in adjectives), None) &gt;&gt;&gt; firstAdjective &gt;&gt;&gt; </code></pre>
-1
2016-07-20T09:58:05Z
[ "python", "scope", "any" ]
How to extract a certain string using RegEx (Python 3.5)
38,476,906
<p>I'm using Python to scrape some data in a website.I got the scraping part done but I need to extract the data I need. </p> <p>Here's a sample of the results I got:</p> <pre><code>{ 'thisversionrun': 'Mon Jul 18 2016 10:36:16 GMT+0000 (UTC)', 'lastrunstatus': 'success', 'name': 'Rudolph1', 'version': 3, 'count': 30, 'newdata': True, 'thisversionstatus': 'success', 'results': { 'collection1': [ { 'property1': "Ano ang 'Marginal Thinking' (Ekonomiks)" }, { 'property1': 'Saan matatagpuan ang caspian sea ano ang kahalagahan nito' }, { 'property1': 'ano-ano ang dalawang uri ng paghahambing ibigay ang kahulugan at ibigay ang 2halimbawa' }, { 'property1': 'mga halimbawa ng pantangi at pambalana tao' }, { 'property1': '10 halimbawa ng palaisipan pero hindi bugtong?' }, { 'property1': 'Ano ang kahinaan at kalakasan ni Psyche at Cupid?' }, { 'property1': 'Ano ang kahulugan ng incentives' }, { 'property1': 'Ano-ano ang limang tema ng heograpiya at ang kahulugan nito?' }, { 'property1': 'ano ang mga kultura ng mga taga-singapore' }, { 'property1': 'Buod ng akdang psyche at cupid sa tagalog' }, { 'property1': 'Ano ang ibig sabihin ng cañao, anito, bathala, pantas at sugo? :)' }, { 'property1': 'Ang Paraan ng Pamumuhay sa Singapore' }, { 'property1': 'Ano ang lahing austronesian?' }, { 'property1': 'What are usually made of wax?' }, { 'property1': 'ano ang kultura at tradisyon ng singapore?' }, { 'property1': 'Pwede magbigay ng 10 halimbawa ng tugmang bayan' }, { 'property1': 'What takes place when you inhale and exhale?' }, { 'property1': 'Anu-ano ang mga halimbawa ng karunungang-bayan' }, { 'property1': 'anu ano ang saklaw ng heograpiya' }, { 'property1': 'Who hired daedalus?' }, { 'property1': 'Kahalagahan ng ekonomiks bilang mag aaral, parte ng pamilya at sa lipunan' }, { 'property1': 'Ano ang pang abay at 5 halimbawa ng pang abay' }, { 'property1': 'What does each part of the bunch of grapes model represent in relation to the breathing system?' }, { 'property1': 'kahulugan ng alaala ng isang lasing na suntok sa bibig' }, { 'property1': 'Ano ang kahulugan ng makabanghay' }, { 'property1': 'Ano ano ang mga tuntunin at kayarian ng talata. ?' }, { 'property1': 'Ano ang kahulugan ng heograpiya' }, { 'property1': 'halimbawa ng recipe para sa matiwasay na lipunan' }, { 'property1': 'How will you describe the pathway of oxygen in the breathing system?' }, { 'property1': 'Anu-ano ang mga halimbawa o uri ng karunungang bayan' } ] } } </code></pre> <p>I need to extract all data matching my RegEx that means all the data between: <code>{'property1': and '}]}}</code></p> <p>the boldface text is a sample of the data I need</p> <p>{'property1': '<strong>Anu-ano ang mga halimbawa o uri ng karunungang bayan</strong>'}]}}</p>
-3
2016-07-20T09:06:28Z
38,477,581
<p>Try this :</p> <pre><code>data = re.findall(r'(?is)property1\':\s*\'(.*?)\'\}',str(input_text)) print(data) </code></pre>
3
2016-07-20T09:35:57Z
[ "python", "regex", "python-3.x" ]
How to extract a certain string using RegEx (Python 3.5)
38,476,906
<p>I'm using Python to scrape some data in a website.I got the scraping part done but I need to extract the data I need. </p> <p>Here's a sample of the results I got:</p> <pre><code>{ 'thisversionrun': 'Mon Jul 18 2016 10:36:16 GMT+0000 (UTC)', 'lastrunstatus': 'success', 'name': 'Rudolph1', 'version': 3, 'count': 30, 'newdata': True, 'thisversionstatus': 'success', 'results': { 'collection1': [ { 'property1': "Ano ang 'Marginal Thinking' (Ekonomiks)" }, { 'property1': 'Saan matatagpuan ang caspian sea ano ang kahalagahan nito' }, { 'property1': 'ano-ano ang dalawang uri ng paghahambing ibigay ang kahulugan at ibigay ang 2halimbawa' }, { 'property1': 'mga halimbawa ng pantangi at pambalana tao' }, { 'property1': '10 halimbawa ng palaisipan pero hindi bugtong?' }, { 'property1': 'Ano ang kahinaan at kalakasan ni Psyche at Cupid?' }, { 'property1': 'Ano ang kahulugan ng incentives' }, { 'property1': 'Ano-ano ang limang tema ng heograpiya at ang kahulugan nito?' }, { 'property1': 'ano ang mga kultura ng mga taga-singapore' }, { 'property1': 'Buod ng akdang psyche at cupid sa tagalog' }, { 'property1': 'Ano ang ibig sabihin ng cañao, anito, bathala, pantas at sugo? :)' }, { 'property1': 'Ang Paraan ng Pamumuhay sa Singapore' }, { 'property1': 'Ano ang lahing austronesian?' }, { 'property1': 'What are usually made of wax?' }, { 'property1': 'ano ang kultura at tradisyon ng singapore?' }, { 'property1': 'Pwede magbigay ng 10 halimbawa ng tugmang bayan' }, { 'property1': 'What takes place when you inhale and exhale?' }, { 'property1': 'Anu-ano ang mga halimbawa ng karunungang-bayan' }, { 'property1': 'anu ano ang saklaw ng heograpiya' }, { 'property1': 'Who hired daedalus?' }, { 'property1': 'Kahalagahan ng ekonomiks bilang mag aaral, parte ng pamilya at sa lipunan' }, { 'property1': 'Ano ang pang abay at 5 halimbawa ng pang abay' }, { 'property1': 'What does each part of the bunch of grapes model represent in relation to the breathing system?' }, { 'property1': 'kahulugan ng alaala ng isang lasing na suntok sa bibig' }, { 'property1': 'Ano ang kahulugan ng makabanghay' }, { 'property1': 'Ano ano ang mga tuntunin at kayarian ng talata. ?' }, { 'property1': 'Ano ang kahulugan ng heograpiya' }, { 'property1': 'halimbawa ng recipe para sa matiwasay na lipunan' }, { 'property1': 'How will you describe the pathway of oxygen in the breathing system?' }, { 'property1': 'Anu-ano ang mga halimbawa o uri ng karunungang bayan' } ] } } </code></pre> <p>I need to extract all data matching my RegEx that means all the data between: <code>{'property1': and '}]}}</code></p> <p>the boldface text is a sample of the data I need</p> <p>{'property1': '<strong>Anu-ano ang mga halimbawa o uri ng karunungang bayan</strong>'}]}}</p>
-3
2016-07-20T09:06:28Z
38,477,737
<p>Try this:</p> <pre><code># encoding: utf-8 import re scrappedString = """{'thisversionrun': 'Mon Jul 18 2016 10:36:16 GMT+0000 (UTC)', 'lastrunstatus': 'success', 'name': 'Rudolph1', 'version': 3, 'count': 30, 'newdata': True, 'thisversionstatus': 'success', 'results': {'collection1': [{'property1': "Ano ang 'Marginal Thinking' (Ekonomiks)"}, {'property1': 'Saan matatagpuan ang caspian sea ano ang kahalagahan nito'}, {'property1': 'ano-ano ang dalawang uri ng paghahambing ibigay ang kahulugan at ibigay ang 2halimbawa'}, {'property1': 'mga halimbawa ng pantangi at pambalana tao'}, {'property1': '10 halimbawa ng palaisipan pero hindi bugtong?'}, {'property1': 'Ano ang kahinaan at kalakasan ni Psyche at Cupid?'}, {'property1': 'Ano ang kahulugan ng incentives'}, {'property1': 'Ano-ano ang limang tema ng heograpiya at ang kahulugan nito?'}, {'property1': 'ano ang mga kultura ng mga taga-singapore'}, {'property1': 'Buod ng akdang psyche at cupid sa tagalog'}, {'property1': 'Ano ang ibig sabihin ng cañao, anito, bathala, pantas at sugo? :)'}, {'property1': 'Ang Paraan ng Pamumuhay sa Singapore'}, {'property1': 'Ano ang lahing austronesian?'}, {'property1': 'What are usually made of wax?'}, {'property1': 'ano ang kultura at tradisyon ng singapore?'}, {'property1': 'Pwede magbigay ng 10 halimbawa ng tugmang bayan'}, {'property1': 'What takes place when you inhale and exhale?'}, {'property1': 'Anu-ano ang mga halimbawa ng karunungang-bayan'}, {'property1': 'anu ano ang saklaw ng heograpiya'}, {'property1': 'Who hired daedalus?'}, {'property1': 'Kahalagahan ng ekonomiks bilang mag aaral, parte ng pamilya at sa lipunan'}, {'property1': 'Ano ang pang abay at 5 halimbawa ng pang abay'}, {'property1': 'What does each part of the bunch of grapes model represent in relation to the breathing system?'}, {'property1': 'kahulugan ng alaala ng isang lasing na suntok sa bibig'}, {'property1': 'Ano ang kahulugan ng makabanghay'}, {'property1': 'Ano ano ang mga tuntunin at kayarian ng talata. ?'}, {'property1': 'Ano ang kahulugan ng heograpiya'}, {'property1': 'halimbawa ng recipe para sa matiwasay na lipunan'}, {'property1': 'How will you describe the pathway of oxygen in the breathing system?'}, {'property1': 'Anu-ano ang mga halimbawa o uri ng karunungang bayan'}]}} """ regex = """'property1': ('|")([\w\d\ñ\.\-\,\?\'\(\) ]+)("|')""" searchedItems = re.findall(pattern=regex, string=scrappedString) for item in searchedItems: print item[1] </code></pre>
1
2016-07-20T09:43:35Z
[ "python", "regex", "python-3.x" ]
Handle multiprocess in python
38,476,912
<p>My code is processing some parallel perforce tasks while showing a progress bar and letting user to terminate the job whenever he wants, the problem is when user clicks the <code>close</code> button the thread function is not being killed but the lock is released and the main UI thread is being unlocked. The <code>p4.run_sync()</code> is not terminating when <code>Cancel</code> button is clicked.</p> <pre><code>def P4SyncLibrary(args, que): syncType = args[0] view = args[1] p4 = P4CreateConnection(disable_tmp_cleanup=True) try: p4.run_sync(view) except P4Exception: for e in p4.errors: print "SyncError: - %s" %e p4.disconnect() que.put(None) class CreateJob(QtGui.QDialog): def __init__(self, thread, args): QtGui.QDialog.__init__(self) self.ui=Ui_ProgressBar() self.ui.setupUi(self) self.ui.cancel.clicked.connect(self.closeEvent) self.ui.cancel.setIcon(QtGui.QIcon(QtGui.QPixmap("%s/delete.xpm" %resources))) self.threadControl = ThreadControl(thread=thread, args=args) self.connect(self.threadControl, QtCore.SIGNAL("__updateProgressBar(int)"), self.__updateProgressBar) self.threadControl.finished.connect(self.closeEvent) self.threadControl.start() @QtCore.pyqtSlot(int) def __updateProgressBar(self,val): self.ui.progressBar.setValue(val) self.setWindowTitle("Processing: {0}%".format(val)) def closeEvent(self, QCloseEvent=None): if self.threadControl.isRunning(): self.threadControl.stop() self.threadControl.wait() if QCloseEvent: QtGui.QDialog.closeEvent(self, QCloseEvent) else: self.close() def getResults(self): return self.threadControl.resultDict class ThreadControl(QtCore.QThread): stopFlag = 0 def __init__(self, thread=None, args=None): super(ThreadControl, self).__init__() self.args = args self.thread = thread self.resultDict = [] def run(self): threads = {} queue = multiprocessing.Queue() for arg in self.args: process = multiprocessing.Process(target=self.thread, args=(arg, queue)) process.start() threads[process] = 1 ## ACTIVE thread # WAIT TILL ALL PROCESSES COMPLETE completedThreads = 0 total = len(threads.keys()) while completedThreads != total: if self.stopFlag: for t in threads.keys(): if threads[t] == 1: t.terminate() t.join() threads[t] = 0 completedThreads += 1 else: for t in threads.keys(): if self.stopFlag: break ## Process threads termination elif threads[t] == 1 and not t.is_alive(): threads[t] = 0 completedThreads += 1 self.resultDict.append(queue.get()) self.emit(QtCore.SIGNAL('__updateProgressBar(int)'),(completedThreads*100)/total) sleep(0.5) ## Prevent CPU from overloading def stop(self): self.stopFlag=1 </code></pre> <p>a job is being created using instance of CreateJob</p> <pre><code>CreateJob(thread=P4SyncLibrary, args=P4Libraries).exec_() </code></pre>
1
2016-07-20T09:06:47Z
38,565,511
<p>The only solution I could give is to pass p4 object to calling thread as argument so that p4 server connection can disconnect when user wants to cancel the job.</p> <pre><code>def P4SyncLibrary(p4, args, que): syncType = args[0] view = args[1] try: p4.run_sync(view) except P4Exception: for e in p4.errors: print "SyncError: - %s" %e que.put(None) class ThreadControl(QtCore.QThread): ... def run(self): threads = {} queue = multiprocessing.Queue() for arg in self.args: connection = P4CreateConnection(disable_tmp_cleanup=True) if connection.connected(): process = multiprocessing.Process(target=self.thread, args=(connection, arg, queue)) process.start() threads[process] = { 'isAlive': True, 'connection': connection } # WAIT TILL ALL PROCESSES COMPLETE completedThreads = 0 total = len(threads.keys()) while completedThreads != total: if self._stop: for t in threads.keys(): if threads[t]['isAlive']: threads[t]['connection'].disconnect() t.terminate() t.join() threads[t]['isAlive'] = False completedThreads += 1 else: for t in threads.keys(): if self._stop: break ## Process threads termination elif threads[t]['isAlive'] and not t.is_alive(): threads[t]['connection'].disconnect() threads[t]['isAlive'] = False completedThreads += 1 self.results.append(queue.get()) self.emit(QtCore.SIGNAL('__updateProgressBar(int)'),(completedThreads*100)/total) sleep(0.5) ## Prevent CPU from overloading </code></pre>
0
2016-07-25T10:37:32Z
[ "python", "multithreading", "perforce" ]
How can I convert a list of hex colors (or RGB, sRGB) stored in a text file into an Image
38,477,123
<p>I have a list of approx. 1000 hex colors which I would like to convert into an image with (e.g. a grid of squares or rectangles) filled with these colors. Is there an easy way to achieve this in Imagemagick (or any other software: e.g. Processing/Python). </p> <p>Thanks for your help</p>
-1
2016-07-20T09:15:19Z
38,477,449
<p>Code is in python You can use the following steps:</p> <ol> <li><p>convert your list to numpy array </p> <p>import numpy as np </p> <p>myarray = np.asarray(mylist)</p></li> <li><p>Use scipy to save the numpy array you have just created</p> <p>from scipy.misc import toimage</p> <p>rgb = scipy.misc.toimage(myarray)</p> <p>toimage(rgb).show()</p></li> </ol> <p>Note: Scipy requres PIL to be installed pre-hand. </p> <p>Another Solution without Scipy is as follows, but you need to modify according to your needs. you will need PIL here:</p> <pre><code>import Image import numpy as np data = np.random.random((500,500)) #Rescale to 0-255 and convert to uint8 rescaled = (255.0 / data.max() * (data - data.min())).astype(np.uint8) im = Image.fromarray(rescaled) im.save('testing.png') </code></pre>
1
2016-07-20T09:29:19Z
[ "python", "imagemagick", "processing" ]
How can I convert a list of hex colors (or RGB, sRGB) stored in a text file into an Image
38,477,123
<p>I have a list of approx. 1000 hex colors which I would like to convert into an image with (e.g. a grid of squares or rectangles) filled with these colors. Is there an easy way to achieve this in Imagemagick (or any other software: e.g. Processing/Python). </p> <p>Thanks for your help</p>
-1
2016-07-20T09:15:19Z
38,481,950
<p>You've tagged this with the <a href="/questions/tagged/processing" class="post-tag" title="show questions tagged &#39;processing&#39;" rel="tag">processing</a> tag, so here is the Processing solution:</p> <p><strong>Step 1:</strong> Load the file. You can use the <code>loadStrings()</code> functions for this. This gives you an array of <code>String</code> values, which in your case will hold your hex values. More info can be found in <a href="https://processing.org/reference/loadStrings_.html" rel="nofollow">the reference</a>.</p> <p><strong>Step 2:</strong> Loop through those hex values. Use a regular <code>for</code> loop or an enhanced <code>for</code> loop.</p> <p><strong>Step 3:</strong> Convert each hex <code>String</code> into an <code>int</code> color using the <code>unhex()</code> function. This gives you an <code>int</code> that can be passed into any color function, such as <code>fill()</code>. More info can be found in <a href="https://processing.org/reference/unhex_.html" rel="nofollow">the reference</a>.</p> <p><strong>Step 4:</strong> Use those colors to draw your image. You haven't said how the lines in the file map to a coordinate on-screen, so you'll have to do that mapping. Then just change the fill color and draw a rectangle at that coordinate.</p> <p>It's hard to answer general "how do I do this" type questions other than to point you to <a href="https://processing.org/reference/" rel="nofollow">the reference</a> and tell you to break your problem down into smaller steps and just try something. Then if you get stuck on one of those specific steps, you can ask a more specific "I tried X, expected Y, but got Z instead" type question, which is more what Stack Overflow was designed for. Good luck.</p>
0
2016-07-20T12:56:01Z
[ "python", "imagemagick", "processing" ]
How can I convert a list of hex colors (or RGB, sRGB) stored in a text file into an Image
38,477,123
<p>I have a list of approx. 1000 hex colors which I would like to convert into an image with (e.g. a grid of squares or rectangles) filled with these colors. Is there an easy way to achieve this in Imagemagick (or any other software: e.g. Processing/Python). </p> <p>Thanks for your help</p>
-1
2016-07-20T09:15:19Z
38,482,684
<p>I would use <code>bash</code> and <code>ImageMagick</code> like this:</p> <pre><code>while read h; do convert xc:"$h" miff:- ; done &lt; colours | montage -geometry +0+0 miff:- result.png </code></pre> <p>So, if your file <code>colours</code> looks like this:</p> <pre><code>#000000 #ffffff #ff0000 #00ff00 #0000ff pink yellow navy rgb(128,128,128) rgb(64,64,64) rgb(200,200,200) </code></pre> <p>you will get this:</p> <p><a href="http://i.stack.imgur.com/UjPvY.png" rel="nofollow"><img src="http://i.stack.imgur.com/UjPvY.png" alt="enter image description here"></a></p> <p>If you want the squares bigger than their current size of 1x1, just change the <code>convert</code> command to specify the size of the square, to say 10x10:</p> <pre><code>while read h; do convert -size 10x10 xc:"$h" miff:- done &lt; colours | montage -geometry +0+0 miff:- result.png </code></pre>
0
2016-07-20T13:28:18Z
[ "python", "imagemagick", "processing" ]
Django how to iterate through a list of objects in a view?
38,477,153
<p>So I have a view that asks the user for input and I cannot figure out what to do to somehow iterate through the list and get the user input on all the objects...</p> <pre><code>def get(self, request, language, word): '''Get reqeust to edit taken in steps''' context = cache.get(word) form_class = DefinitionInfoForm context['form_class'] = form_class return render(request, 'study/add_info.html', context_instance=RequestContext(request, context)) </code></pre> <p>Here is my get that is inside a CBV. I have loaded a cache of objects and I would like to somehow iterate through them one at a time making a new <code>get</code> for every one if possible </p> <p>OR</p> <p>do a bulk ad and render them all with forms and modify all the objects in the post method</p> <p>I am using this form to add the info and I can not figure out how to do it with a bulk or one at a time...</p> <pre><code>class DefinitionInfoForm(forms.Form): part_of_speech = forms.CharField(required=True, label=_(u'Part of Speech')) pronunciation = forms.CharField(required=True, label=_(u'Pronunciation')) </code></pre>
0
2016-07-20T09:16:35Z
38,514,721
<p>In this case the answer for me was to use <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#model-formsets" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#model-formsets</a> and add a queryset as an argument. </p> <p>I could then pass it to the template as context and iterate through the formset there</p>
0
2016-07-21T21:32:07Z
[ "python", "django" ]
Tkinter GUI is not responding
38,477,336
<p>I have only one while loop and the Tkonter say: GUI is not responding. What I'm doing wrong ? I would like with button "Pause" break and again with "button "Start" continue the program.</p> <pre><code>import Tkinter, time root = Tkinter.Tk class InterfaceApp(root): def __init__ (self, parent): root.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.but_state = 0 self.but_start = Tkinter.Button(self, text='Start', command=lambda: self.Start(), width=10) self.but_pause = Tkinter.Button(self, text="Pause", command=lambda: self.Pause(), width=10) self.but_stop = Tkinter.Button(self, text='Stop', command=lambda: self.Stop(), width=10) self.but_start.grid(row=1, column=1, sticky='W') self.but_pause.grid(row=1, column=2, sticky='W') self.but_stop.grid(row=1, column=3, sticky='W') def Start(self): while True: print "X" time.sleep(2) if self.but_state == 1: break else: continue def Stop(self): self.but_state = 1 def Pause(self): pass if __name__ == "__main__": app = InterfaceApp(None) app.title("MPW4 microHP - Long Term Test") app.mainloop() </code></pre>
-2
2016-07-20T09:23:59Z
38,478,012
<p>Your code is nonsense. You have to figure out how to define functions and use them properly first. I wrote a little example for you:</p> <pre><code>from tkinter import * class App: def __init__(self, master): self.master = master self.startb = Button(master, text="Start", command=self.startf) self.startb.pack() self.pauseb = Button(master, text="Pause", command=self.pausef) self.pauseb.pack() self.stopb = Button(master, text="Stop", command=self.stopf) self.stopb.pack() def startf(self): print("Started") self.after_id = self.master.after(1000, self.startf) def pausef(self): if self.startf is not None: # to handle any exception self.master.after_cancel(self.after_id) # this will pause startf function -- you can start again print("Paused") def stopf(self): if self.startf is not None: self.master.after_cancel(self.after_id) self.startf = None # this will stop startf function -- you cannot start again print("Stopped") root = Tk() myapp = App(root) root.mainloop() </code></pre> <p>Then you can modify this code -- change the behaviors of the functions etc. If you have a working piece of code which will behave as the "motor" function that does the core idea of your program, include that function in as well, and return it in the <code>startf</code> function, pause it in the <code>pausef</code> function, and finally, stop it in the <code>stopf</code> function.<br> P.S.: My code was written in <b>Python 3</b>.<br> <b>EDIT:</b> I completed the code and above is a working program that starts, pauses and stops depending on the button you click.</p>
1
2016-07-20T09:55:43Z
[ "python", "tkinter" ]
Tkinter GUI is not responding
38,477,336
<p>I have only one while loop and the Tkonter say: GUI is not responding. What I'm doing wrong ? I would like with button "Pause" break and again with "button "Start" continue the program.</p> <pre><code>import Tkinter, time root = Tkinter.Tk class InterfaceApp(root): def __init__ (self, parent): root.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.but_state = 0 self.but_start = Tkinter.Button(self, text='Start', command=lambda: self.Start(), width=10) self.but_pause = Tkinter.Button(self, text="Pause", command=lambda: self.Pause(), width=10) self.but_stop = Tkinter.Button(self, text='Stop', command=lambda: self.Stop(), width=10) self.but_start.grid(row=1, column=1, sticky='W') self.but_pause.grid(row=1, column=2, sticky='W') self.but_stop.grid(row=1, column=3, sticky='W') def Start(self): while True: print "X" time.sleep(2) if self.but_state == 1: break else: continue def Stop(self): self.but_state = 1 def Pause(self): pass if __name__ == "__main__": app = InterfaceApp(None) app.title("MPW4 microHP - Long Term Test") app.mainloop() </code></pre>
-2
2016-07-20T09:23:59Z
38,479,109
<h3>First issue:</h3> <p>Using the while loop. To call a function again after it finished use </p> <p><code>self.after(&lt;time in ms&gt;, &lt;function to call&gt;)</code></p> <p>at the end of your <code>def Start(self)</code></p> <p>Would look like this:</p> <pre><code> # ... def Start(self): print("X") if self.but_state == 0: self.after(2000, self.Start) # ... </code></pre> <h3>Second Issue:</h3> <p>Do not use lambdas for simple calls. Use the name for the binding instead, just like @Parviz_Karimli pointed out.</p> <pre><code>def initialize(self): self.but_state = 0 self.but_start = Tkinter.Button(self, text='Start', command=self.Start, width=10) self.but_pause = Tkinter.Button(self, text="Pause", command=self.Pause, width=10) self.but_stop = Tkinter.Button(self, text='Stop', command=self.Stop, width=10) self.but_start.grid(row=1, column=1, sticky='W') self.but_pause.grid(row=1, column=2, sticky='W') self.but_stop.grid(row=1, column=3, sticky='W') </code></pre>
3
2016-07-20T10:45:37Z
[ "python", "tkinter" ]
load data in exact order from json string(python, django)
38,477,439
<p>I have json data coming from ajax,jquery as below</p> <pre><code>json_data_from_ajax = u'{"1_sd":{"name":"unicode","data_type_choices":"Unicode"},"2_sd":{"name":"unicode_secret","data_type_choices":"Unicode"},"3_sd":{"name":"unicode_mandatory","data_type_choices":"Unicode"},"4_sd":{"name":"boolean","data_type_choices":"Unicode"},"5_sd":{"name":"boolean_secret","data_type_choices":"Unicode"},"6_sd":{"name":"boolean_mandatory","data_type_choices":"Unicode"},"7_sd":{"name":"integer","data_type_choices":"Unicode"},"8_sd":{"name":"integer_value","data_type_choices":"Unicode"},"9_sd":{"name":"integer_mandatory","data_type_choices":"Unicode"}}' </code></pre> <p>And i am trying to load(convert json string in to actual data) the above data as below</p> <p>import json as simplejson settings_records = simplejson.loads(json_data_from_ajax) print settings_records</p> <p><strong><em>output</em></strong></p> <pre><code>{u'8_sd': {u'data_type_choices': u'Unicode'}, u'3_sd': {u'name': u'unicode_mandatory', u'data_type_choices': u'Unicode'}, u'1_sd': {u'name': u'unicode', u'data_type_choices': u'Unicode'}, u'6_sd': {u'name': u'boolean_mandatory', u'data_type_choices': u'Unicode'}, u'9_sd': {u'name': u'integer_mandatory', u'data_type_choices': u'Unicode'}, u'4_sd': {u'name': u'boolean', u'data_type_choices': u'Unicode'}, u'7_sd': {u'name': u'integer', u'data_type_choices': u'Unicode'}, u'2_sd': {u'name': u'unicode_secret', u'data_type_choices': u'Unicode'}, u'5_sd': {u'name': u'boolean_secret', u'data_type_choices': u'Unicode'}} </code></pre> <p>So from the above output you can able to see that the keys from dictionary are ordered randomly like <code>u'8_sd', u'3_sd', u'1_sd'......</code>, but i need to them as it is from json string which i received from ajax like <code>"1_sd", "2_sd", "3_sd", "4_sd"......</code></p> <p>So how can we load the json string in an order ?</p>
0
2016-07-20T09:28:36Z
38,477,800
<p>This might help (doesn't work for python &lt;2.7):</p> <pre><code>import simplejson as json from collections import OrderedDict settings_records = json.loads(json_data_from_ajax, object_pairs_hook=OrderedDict) </code></pre>
0
2016-07-20T09:46:56Z
[ "jquery", "python", "json", "ajax", "django" ]
load data in exact order from json string(python, django)
38,477,439
<p>I have json data coming from ajax,jquery as below</p> <pre><code>json_data_from_ajax = u'{"1_sd":{"name":"unicode","data_type_choices":"Unicode"},"2_sd":{"name":"unicode_secret","data_type_choices":"Unicode"},"3_sd":{"name":"unicode_mandatory","data_type_choices":"Unicode"},"4_sd":{"name":"boolean","data_type_choices":"Unicode"},"5_sd":{"name":"boolean_secret","data_type_choices":"Unicode"},"6_sd":{"name":"boolean_mandatory","data_type_choices":"Unicode"},"7_sd":{"name":"integer","data_type_choices":"Unicode"},"8_sd":{"name":"integer_value","data_type_choices":"Unicode"},"9_sd":{"name":"integer_mandatory","data_type_choices":"Unicode"}}' </code></pre> <p>And i am trying to load(convert json string in to actual data) the above data as below</p> <p>import json as simplejson settings_records = simplejson.loads(json_data_from_ajax) print settings_records</p> <p><strong><em>output</em></strong></p> <pre><code>{u'8_sd': {u'data_type_choices': u'Unicode'}, u'3_sd': {u'name': u'unicode_mandatory', u'data_type_choices': u'Unicode'}, u'1_sd': {u'name': u'unicode', u'data_type_choices': u'Unicode'}, u'6_sd': {u'name': u'boolean_mandatory', u'data_type_choices': u'Unicode'}, u'9_sd': {u'name': u'integer_mandatory', u'data_type_choices': u'Unicode'}, u'4_sd': {u'name': u'boolean', u'data_type_choices': u'Unicode'}, u'7_sd': {u'name': u'integer', u'data_type_choices': u'Unicode'}, u'2_sd': {u'name': u'unicode_secret', u'data_type_choices': u'Unicode'}, u'5_sd': {u'name': u'boolean_secret', u'data_type_choices': u'Unicode'}} </code></pre> <p>So from the above output you can able to see that the keys from dictionary are ordered randomly like <code>u'8_sd', u'3_sd', u'1_sd'......</code>, but i need to them as it is from json string which i received from ajax like <code>"1_sd", "2_sd", "3_sd", "4_sd"......</code></p> <p>So how can we load the json string in an order ?</p>
0
2016-07-20T09:28:36Z
38,478,296
<p>This will work for you :</p> <pre><code>from django.core import serializers import json data = serializers.serialize('json', json_data_from_ajax) result = json.dumps(data) </code></pre>
-1
2016-07-20T10:08:01Z
[ "jquery", "python", "json", "ajax", "django" ]