title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Django 1.9 Bulk Create New Users Not hashing Passswords Correctly
37,836,882
<p>I want to read in some data from a file to quickly create many test accounts. I'd prefer to use the bulk_create method since this is typically much faster for adding many records to a model. However, when using the bulk_create method with Django's User model the passwords aren't being hashed correctly meaning I'm th...
1
2016-06-15T13:28:16Z
37,837,194
<p>That's because password are encrypted in the database and you're saving the original. You simply need to use <code>make_password</code> to encrypt it.</p> <p>Please try:</p> <pre><code>from django.contrib.auth.hashers import make_password User.objects.bulk_create([ User( username=name, email='...
0
2016-06-15T13:41:03Z
[ "python", "django" ]
Python- performance issue with mysql and google play subscription
37,837,076
<p>I am trying to extract the <code>purchase_state</code> from google play, following the steps bellow: </p> <pre><code> import base64 import requests import smtplib from collections import OrderedDict import mysql.connector from mysql.connector import errorcode ...... </code></pre> <blockq...
0
2016-06-15T13:36:01Z
37,879,754
<p>I hope I'm right about this, but the bottleneck seems to be the connection to the playstore. Doing it sequentially will take a long time, whereas the server is able to take a million requests at a time. So here's a way to process your jobs with executors (you need the "concurrent" package installed) In that example,...
1
2016-06-17T10:52:08Z
[ "python", "performance", "google-play-developer-api" ]
Replaces spaces with NAN in pandas dataframe
37,837,148
<p>I have a pandas dataframe with three columns:</p> <pre><code>Name Name2 DateTime 2016-06-10 05:22 2016-06-10 05:23 2016-06-10 14:25 Guest Guest1 2016-06-10 15:32 </code></pre> <p>I have to replace em...
1
2016-06-15T13:39:15Z
37,837,438
<p>If you're sure there won't be spaces between the names, you could use <code>.strip()</code> to remove any whitespace (or anything, really) off the ends of the string.</p> <pre><code> df3['Name'] = df3['Name'].strip().replace(r'[^\s+]',np.nan, regex=True) </code></pre>
0
2016-06-15T13:50:26Z
[ "python", "pandas", "ipython" ]
Replaces spaces with NAN in pandas dataframe
37,837,148
<p>I have a pandas dataframe with three columns:</p> <pre><code>Name Name2 DateTime 2016-06-10 05:22 2016-06-10 05:23 2016-06-10 14:25 Guest Guest1 2016-06-10 15:32 </code></pre> <p>I have to replace em...
1
2016-06-15T13:39:15Z
37,837,953
<p>Since you dont need the spaces, this should work. </p> <pre><code>df3['Name'] = df3['Name'].replace('[\s]+',"", regex=True) #Gets rid of all blank spaces df3['Name'] = df3['Name'].replace('',np.nan, regex=True) #Replace completely empty cells with nan </code></pre>
0
2016-06-15T14:12:18Z
[ "python", "pandas", "ipython" ]
Replaces spaces with NAN in pandas dataframe
37,837,148
<p>I have a pandas dataframe with three columns:</p> <pre><code>Name Name2 DateTime 2016-06-10 05:22 2016-06-10 05:23 2016-06-10 14:25 Guest Guest1 2016-06-10 15:32 </code></pre> <p>I have to replace em...
1
2016-06-15T13:39:15Z
37,838,363
<p>Another solution which found <code>length</code> of data and then by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> replacing all data with length <code>0</code> or <code>1</code>:</p> <pre><code>print (df.applymap(len)) Name ...
1
2016-06-15T14:30:52Z
[ "python", "pandas", "ipython" ]
Is it actually possible to pass data (callback) from mpld3 to ipython?
37,837,210
<p>There is a lot of amazing possibilities to create animated pictures using <code>mpld3</code>. However, it seems that all the "moving parts" are responsibility of JavaScript. Moreover, there are lots of requests on the internet and Stack Overflow where people directly ask for that possibility.</p> <p><a href="http:/...
1
2016-06-15T13:41:48Z
38,833,244
<p>You can do this with the new <code>bqplot</code> <code>Scatter</code> and <code>Label</code> both of them have an <code>enable_move</code> parameter, that when you set to <code>True</code> they allow points to be dragged. Furthermore, when you <code>drag</code> you can <code>observe</code> a change in the <code>x</c...
1
2016-08-08T15:33:02Z
[ "javascript", "python", "mpld3", "ipywidgets" ]
Python mysql error with cursor
37,837,311
<p>Hi I get an error when I try to connect to a mysql database.</p> <pre><code>import threading from mysql.connector import MySQLConnection, Error from python_mysql_dbconfig import read_db_config class Queue (threading.Thread): def __init__(self, threadID, lock): threading.Thread.__init__(self) se...
0
2016-06-15T13:45:56Z
37,838,201
<p>So ... after a bit of troubleshooting ...</p> <p>The solution was to <a href="http://stackoverflow.com/a/1810760/3259125">set the current working directory</a> when calling the script from outside the folder in which the config file was located.</p>
2
2016-06-15T14:23:45Z
[ "python", "mysql" ]
Python mysql error with cursor
37,837,311
<p>Hi I get an error when I try to connect to a mysql database.</p> <pre><code>import threading from mysql.connector import MySQLConnection, Error from python_mysql_dbconfig import read_db_config class Queue (threading.Thread): def __init__(self, threadID, lock): threading.Thread.__init__(self) se...
0
2016-06-15T13:45:56Z
37,838,280
<p>I've ran your code from read_db_config and everything it`s okay. I think that the problem is the path of the config file. If you just from the root path of your application, I mean:</p> <pre><code>- root_dir - parser.py - config.ini </code></pre> <p>your function will work well, but when you run as an impo...
1
2016-06-15T14:27:09Z
[ "python", "mysql" ]
Export tables from Postgresql to Excel using Python interface
37,837,328
<p>I am trying to develop a form in python using tkinter to export tables from postgresql to excel files. or export the result of sql query to excel </p> <p>Ps: i'm a python beginner</p>
-1
2016-06-15T13:46:40Z
37,837,444
<p>There are 2 parts to the problem, (i) read the table from the database (you can use psycopg2 library for that) (ii) Write the table to to a csv file (which can be read in excel). </p> <p>1) Read the table : <a href="https://wiki.postgresql.org/wiki/Psycopg2_Tutorial" rel="nofollow">https://wiki.postgresql.org/wiki/...
0
2016-06-15T13:50:46Z
[ "python", "tkinter" ]
Getting ImportError even though module is installed
37,837,337
<p>installed :</p> <pre><code> pip install google-python-cloud-debugger Requirement already satisfied (use --upgrade to upgrade): google-python-cloud-debugger in /usr/local/lib/python2.7/dist-packages Requirement already satisfied (use --upgrade to upgrade): google-api-python-client in /usr/local/lib/python2.7/dist-pa...
1
2016-06-15T13:46:55Z
37,842,057
<p>Are you invoking python2.7 or python3 when you import cloud debugger, or uritemplate directly? </p> <pre><code>$ python2.7 &gt;&gt;&gt; import uritemplate &gt;&gt;&gt; $ python3 &gt;&gt;&gt; import uritemplate Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No mo...
0
2016-06-15T17:32:29Z
[ "python", "google-cloud-platform", "stackdriver", "google-cloud-debugger" ]
Getting ImportError even though module is installed
37,837,337
<p>installed :</p> <pre><code> pip install google-python-cloud-debugger Requirement already satisfied (use --upgrade to upgrade): google-python-cloud-debugger in /usr/local/lib/python2.7/dist-packages Requirement already satisfied (use --upgrade to upgrade): google-api-python-client in /usr/local/lib/python2.7/dist-pa...
1
2016-06-15T13:46:55Z
37,842,472
<p>I have the same problem. <code>uritemplate</code> was downloaded to my files system. after solving that , the same goes for <code>oauth2client</code> which I had to update . downloaded from <a href="https://github.com/google/oauth2client" rel="nofollow">https://github.com/google/oauth2client</a></p> <p>so I down...
0
2016-06-15T17:53:35Z
[ "python", "google-cloud-platform", "stackdriver", "google-cloud-debugger" ]
Alex-Net for feature extraction
37,837,406
<p>I try to get reliable features for ImageNet to do further classification on them. To achieve that I would like to use tensorflow with Alexnet, for feature extraction. That means I would like to get the values from the last layer in the CNN. Could someone write a piece of Python code that explains how that works?</p>...
0
2016-06-15T13:49:26Z
37,839,687
<p>As <a href="http://stackoverflow.com/users/3001761/jonrsharpe">jonrsharpe</a> mentioned, that's not really stackoverflow's MO, but in practice, many people do choose to write code to help explain answers (because it's often easier). So I'm going to assume that this was just miscommunication, and you really intended ...
0
2016-06-15T15:28:14Z
[ "python", "classification", "tensorflow", "feature-extraction" ]
Implement packing/unpacking in an object
37,837,520
<p>I have a class that only contains attributes and I would like packing/unpacking to work on it. What <code>collections.abc</code> should I implement to get this behaviour?</p> <pre><code>class Item(object): def __init__(self, name, age, gender) self.name = name self.age = age self.gender...
-1
2016-06-15T13:53:18Z
37,837,754
<p>You can unpack any <a href="https://docs.python.org/2/library/collections.html#collections.Iterable" rel="nofollow"><code>Iterable</code></a>. This means you need to implement the <code>__iter__</code> method, and return an iterator. In your case, this could simply be:</p> <pre><code>def __iter__(self): return ...
2
2016-06-15T14:04:13Z
[ "python", "python-2.7" ]
Convert string to epoch time?
37,837,562
<p>I have a string in this format <strong>'2016-06-15T12:52:05.623Z'</strong>. I want to calculate the number of seconds of this time since epoch.</p> <p>How can I do that?</p>
0
2016-06-15T13:55:26Z
37,837,740
<p>In Python 3:</p> <pre><code>import dateutil.parser t = dateutil.parser.parse("2016-06-15T12:52:05.623Z") print(t.timestamp()) </code></pre>
1
2016-06-15T14:03:37Z
[ "python" ]
Convert string to epoch time?
37,837,562
<p>I have a string in this format <strong>'2016-06-15T12:52:05.623Z'</strong>. I want to calculate the number of seconds of this time since epoch.</p> <p>How can I do that?</p>
0
2016-06-15T13:55:26Z
37,837,803
<pre><code>from datetime import datetime my_date = '2016-06-15T12:52:05.623Z' dtformat = '%Y-%m-%dT%H:%M:%S.%fZ' d = datetime.strptime(my_date, dtformat) epoch = datetime.utcfromtimestamp(0) print (d - epoch).total_seconds() # OUT: 1465995125.62 </code></pre>
1
2016-06-15T14:05:59Z
[ "python" ]
Convert string to epoch time?
37,837,562
<p>I have a string in this format <strong>'2016-06-15T12:52:05.623Z'</strong>. I want to calculate the number of seconds of this time since epoch.</p> <p>How can I do that?</p>
0
2016-06-15T13:55:26Z
37,837,855
<p>Use time to return the timestamp from datetime:</p> <pre><code>import datetime import time date = datetime.datetime.strptime('2016-06-15T12:52:05.623Z', "%Y-%m-%dT%H:%M:%S.%fZ") print time.mktime(date.timetuple()) &gt;&gt; 1466005925.0 </code></pre>
0
2016-06-15T14:08:05Z
[ "python" ]
Why is pprofile giving no output?
37,837,566
<p>I'm new to python and I'd like to use pprofile, but I don't get it running. For example</p> <pre><code>#pprofile --threads 0 test.py </code></pre> <p>gives me the error</p> <pre><code>bash: pprofile: Command not found. </code></pre> <p>I've tried to run pprofiler as a module, like described here: <a href="https:...
1
2016-06-15T13:55:34Z
37,879,662
<p>pprofile author here.</p> <p>To use pprofile as a command, you would have to install it. The only packaging I have worked on so far is <a href="https://pypi.python.org/pypi/pprofile" rel="nofollow">via pypi</a>. Unless you are using a dependency-gathering tool (like buildout), the easiest is probably to setup a <a ...
1
2016-06-17T10:47:16Z
[ "python", "facebook" ]
Selenium Python Binding can't pass variable into function
37,837,628
<p>I have been searching for the solution to this problem for a while with no luck.</p> <p>I am using selenium and BeautifulSoup4. </p> <p>I pass the container_number variable into this function:</p> <pre><code>find_container_number=wait.until(EC.presence_of_element_located((By.LINK_TEXT,container_number))) </code><...
1
2016-06-15T13:58:32Z
37,838,167
<p>It is a guess, but you may need to <em>trim the value</em> before using:</p> <pre><code>container_number = temp.find(text=True).strip() find_container_number = wait.until(EC.presence_of_element_located((By.LINK_TEXT,container_number))) </code></pre> <p>Or, just use <code>.get_text()</code>:</p> <pre><code>temp = ...
1
2016-06-15T14:22:13Z
[ "python", "python-2.7", "firefox", "selenium-webdriver", "beautifulsoup" ]
Django templates and whitespace
37,837,674
<p>I started using custom <a href="https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#inclusion-tags" rel="nofollow">inclusion tags</a> within my django templates. For example I have a <code>{% profilelink profile %}</code> tag that inserts a link to a user profile together with a small version of the p...
4
2016-06-15T14:00:22Z
37,929,027
<p>This is the best I came up with so far. I still hope for a better solution, but for now it will do.</p> <p>I defined a custom filter like this in <em>base/templatetags/basetags.yp</em> (<a href="http://stackoverflow.com/a/10361276/424381">taken from this answer</a>):</p> <pre><code>from django import template fro...
1
2016-06-20T18:05:22Z
[ "python", "django", "django-templates" ]
Django templates and whitespace
37,837,674
<p>I started using custom <a href="https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#inclusion-tags" rel="nofollow">inclusion tags</a> within my django templates. For example I have a <code>{% profilelink profile %}</code> tag that inserts a link to a user profile together with a small version of the p...
4
2016-06-15T14:00:22Z
37,929,632
<p>I believe one solution is to use a <a href="https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#django.template.Library.simple_tag" rel="nofollow"><strong><code>simple_tag</code></strong></a> instead of an inclusion tag, hopefully without to much clutter.</p> <p>I assume your tag is something like thi...
2
2016-06-20T18:44:09Z
[ "python", "django", "django-templates" ]
python execute exe file with script, enter username, password, etc
37,837,679
<p>I want to call an exe-file and already input parameters/input-data.</p> <pre><code>cmd = dir_path + 'file.exe do something test' p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT) </code></pre> <p>This is already working fine. If you do that by using the exe-file you would press enter to execute the next step ...
2
2016-06-15T14:00:46Z
37,838,086
<p>You're almost there!</p> <p>You can do the following:</p> <pre><code>import subprocess p = subprocess.Popen(cmd, stdin=subprocess.PIPE, shell=True) p.communicate(input='\r') </code></pre> <p>You may need to use \n instead of \r if there are any problems. \r is a carriage return, and \n is a newline.</p>
1
2016-06-15T14:18:37Z
[ "python", "pipe", "subprocess", "popen" ]
Python class input argument
37,837,682
<p>I am new to OOP. My idea was to implement the following class:</p> <pre><code>class name(object, name): def __init__(self, name): print name </code></pre> <p>Then the idea was to create two instances of that class:</p> <pre><code>person1 = name("jean") person2 = name("dean") </code></pre> <p>I know, ...
-1
2016-06-15T14:00:50Z
37,837,766
<pre><code>&gt;&gt;&gt; class name(object): ... def __init__(self, name): ... self.name = name ... &gt;&gt;&gt; person1 = name("jean") &gt;&gt;&gt; person2 = name("dean") &gt;&gt;&gt; person1.name 'jean' &gt;&gt;&gt; person2.name 'dean' &gt;&gt;&gt; </code></pre> <p>Is this what you are looking for?</p>
5
2016-06-15T14:04:43Z
[ "python", "oop" ]
Python class input argument
37,837,682
<p>I am new to OOP. My idea was to implement the following class:</p> <pre><code>class name(object, name): def __init__(self, name): print name </code></pre> <p>Then the idea was to create two instances of that class:</p> <pre><code>person1 = name("jean") person2 = name("dean") </code></pre> <p>I know, ...
-1
2016-06-15T14:00:50Z
37,837,782
<p>Remove the <code>name</code> param from the class declaration. The init method is used to pass arguments to a class at creation.</p> <pre><code>class Person(object): def __init__(self, name): self.name = name me = Person("TheLazyScripter") print me.name </code></pre>
2
2016-06-15T14:05:17Z
[ "python", "oop" ]
Python class input argument
37,837,682
<p>I am new to OOP. My idea was to implement the following class:</p> <pre><code>class name(object, name): def __init__(self, name): print name </code></pre> <p>Then the idea was to create two instances of that class:</p> <pre><code>person1 = name("jean") person2 = name("dean") </code></pre> <p>I know, ...
-1
2016-06-15T14:00:50Z
37,837,793
<p>You just need to do it in correct syntax. Let me give you a minimal example I just did with Python interactive shell:</p> <pre><code>&gt;&gt;&gt; class MyNameClass(): ... def __init__(self, myname): ... print myname ... &gt;&gt;&gt; p1 = MyNameClass('John') John </code></pre>
0
2016-06-15T14:05:39Z
[ "python", "oop" ]
Python class input argument
37,837,682
<p>I am new to OOP. My idea was to implement the following class:</p> <pre><code>class name(object, name): def __init__(self, name): print name </code></pre> <p>Then the idea was to create two instances of that class:</p> <pre><code>person1 = name("jean") person2 = name("dean") </code></pre> <p>I know, ...
-1
2016-06-15T14:00:50Z
37,837,840
<p><a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">Python Classes</a> </p> <pre><code>class name: def __init__(self, name): self.name = name print("name: "+name) </code></pre> <p>Somewhere else: </p> <p><code>john = name("john")</code></p> <p>Output:<br> <code>name: jo...
1
2016-06-15T14:07:29Z
[ "python", "oop" ]
Python class input argument
37,837,682
<p>I am new to OOP. My idea was to implement the following class:</p> <pre><code>class name(object, name): def __init__(self, name): print name </code></pre> <p>Then the idea was to create two instances of that class:</p> <pre><code>person1 = name("jean") person2 = name("dean") </code></pre> <p>I know, ...
-1
2016-06-15T14:00:50Z
37,837,910
<p>The problem in your initial definition of the class is that you've written:</p> <pre><code>class name(object, name): </code></pre> <p>This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you nee...
1
2016-06-15T14:10:41Z
[ "python", "oop" ]
Selenium not working on server as it works on local machine
37,837,705
<p>I have recently completed my Selenium Python scraper. It works totally fine when I run it on my personal machine but the results are not same when I run it on the server. On the server I am running headless using <code>pyvirtualdisplay</code></p> <pre><code>browser.get('https://example.com') html = browser.page_s...
2
2016-06-15T14:01:59Z
37,840,663
<p>This sounds like an issue with your OS or Browser configuration. The first thing you should do is screenshot the results in your framebuffer and make sure that firefox is loading JS content properly. If it is not then you may need to check your browser/OS configurations. </p> <p>pyvirtualdisplay has a way of screen...
1
2016-06-15T16:13:17Z
[ "python", "selenium", "centos", "pyvirtualdisplay" ]
Drawing lines between clicks on image with Matplotlib
37,837,760
<p>I am trying to allow for a user to right click on an image once, and then again, and then the program will draw a line from the first click to the second.</p> <p>However, what I have now, inserts lines into my image seemingly randomly. They pop up and they are nowhere near my clicks, and are of random lengths and a...
1
2016-06-15T14:04:25Z
37,843,861
<p>I created a dressed-down version attached below, but in the end there was only a very minor mistake in your code:</p> <pre><code>plt.plot((linepoints[0], linepoints[1]), (linepoints[2], linepoints[3]), '-') </code></pre> <p>needed to be:</p> <pre><code>plt.plot((linepoints[0], linepoints[2]), (linepoints[1], line...
1
2016-06-15T19:09:11Z
[ "python", "matplotlib" ]
Executing remote command in Vertica using Python
37,837,843
<p>I'm trying to execute a remote command like this:</p> <pre><code>ssh root@192.168.1.2 'su - vertica -c "vsql -c \"select * from tableName where timestamp &gt; '2016-05-15 00:00:00' limit 1 \" "'" </code></pre> <p>It gives me an error </p> <pre><code>ERROR 4856: Syntax error at or near "00" at character 61 LINE 1...
0
2016-06-15T14:07:36Z
38,104,426
<p>You don't need those outside quotes on the ssh command. This should work fine (I also fixed some quoting mistake you had at the end): </p> <pre><code>ssh root@192.168.1.2 su - vertica -c "vsql -c \"select * from tableName where timestamp &gt; '2016-05-15 00:00:00' limit 1 \" " </code></pre> <p>I feel like I really...
0
2016-06-29T15:46:41Z
[ "python", "ssh", "vertica" ]
match csv data with RegExp, Python
37,838,023
<p>I have a csv file which contains lines like:</p> <pre><code>{"Books \u3009 Arts &amp; Photography \u3009 Sculpture \u3009 Appreciation": 342444, "Books": 4244234234875} {"Books \u3009 Science": 342864, "Books": 44242875} {"Books \u3009 Politics": 342444, "Books": 4135875} </code></pre> <p>I need to read csv file ...
0
2016-06-15T14:15:40Z
37,838,376
<p>That is not a CSV file but a bunch of JSON objects put together. They all appear valid, so you can just parse them and extract the data that way:</p> <pre><code>import csv import json with open('input.csv', 'r') as infile, open('output.csv', 'w') as outfile: writer = csv.writer(outfile) for line in infile:...
0
2016-06-15T14:31:24Z
[ "python", "regex", "csv" ]
Python code to swap first and last letters in string
37,838,032
<p>Given a string, return a new string where the first and last chars have been exchanged.</p> <pre><code>front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' </code></pre> <p>The above is one of the problems provided on www.codingBat.com I was attempting to solve and below is the code I wr...
-1
2016-06-15T14:16:08Z
37,838,113
<p>Your problem is with 1 character, ie. <code>front_back('a') → 'a'</code>. Consider how you could adjust your function to account for this case.</p> <p>EDIT: I did not like the efficiency or generality of the other answers, so I'll post my solution below:</p> <pre><code>def front_back(str): return ''.join([x ...
1
2016-06-15T14:20:16Z
[ "python", "string" ]
Python code to swap first and last letters in string
37,838,032
<p>Given a string, return a new string where the first and last chars have been exchanged.</p> <pre><code>front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' </code></pre> <p>The above is one of the problems provided on www.codingBat.com I was attempting to solve and below is the code I wr...
-1
2016-06-15T14:16:08Z
37,838,124
<p>Your function won't work with 1-character strings as it'll just duplicate the character. You could add a special case for such strings:</p> <pre><code>def front_back(string): if len(string) == 1: return string return string[-1] + string[1:-1] + string[0] </code></pre> <p>As a side note, don't use <...
2
2016-06-15T14:20:45Z
[ "python", "string" ]
Python code to swap first and last letters in string
37,838,032
<p>Given a string, return a new string where the first and last chars have been exchanged.</p> <pre><code>front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' </code></pre> <p>The above is one of the problems provided on www.codingBat.com I was attempting to solve and below is the code I wr...
-1
2016-06-15T14:16:08Z
37,838,148
<p>I assume that the website uses a series of random/pseudorandom characters to determine if your code gives the correct output. If so then a string of <code>len() == 1</code> would return incorrectly. i.e. <code>'h' return 'hh'</code>. I have modified the code to correct this. Assuming that the website also asked you ...
0
2016-06-15T14:21:35Z
[ "python", "string" ]
Python code to swap first and last letters in string
37,838,032
<p>Given a string, return a new string where the first and last chars have been exchanged.</p> <pre><code>front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' </code></pre> <p>The above is one of the problems provided on www.codingBat.com I was attempting to solve and below is the code I wr...
-1
2016-06-15T14:16:08Z
37,846,176
<p>Keep it simple to avoid the special cases:</p> <pre><code>def front_back(string): array = list(string) array[0], array[-1] = array[-1], array[0] return "".join(array) </code></pre>
0
2016-06-15T21:34:52Z
[ "python", "string" ]
Use psycopg2 query to copy data from a table to a csv file
37,838,035
<p>I have a got the path to a csv file using</p> <pre><code>cur1.execute("select path from t2"); path = cur1.fetchone() </code></pre> <p>I know want to perform a copy to the csv file using psycopg2 which goes like :</p> <pre><code>cur2.execute("COPY (SELECT id,a,b,c FROM t1,t2 WHERE a &gt;= t2.d ) TO path[0] DELIMIT...
0
2016-06-15T14:16:17Z
37,838,777
<p>There is actually two problems here.</p> <p>The first is you have to surround your filename with ', that's what the error message indicates.</p> <p>The second is that if you do that, your file will be named path[0], which is probably not what you want, because your database can't know what path is and access it (t...
1
2016-06-15T14:48:58Z
[ "python", "sql", "postgresql", "psycopg2" ]
Reading Caffe vector extracted features, reshape vector in python
37,838,036
<p>I've used the tutorial of <a href="http://caffe.berkeleyvision.org/gathered/examples/feature_extraction.html" rel="nofollow">Caffe</a> to extract successfully features from a set of images. Then, I used this code to convert the results stored in features file under leveldb format to npy file :</p> <pre><code>input_...
0
2016-06-15T14:16:22Z
37,838,233
<p>If I understand you correctly, you want the <code>shape</code> of <code>arr</code> to be 4096 dim, instead of <code>(1, 4096, 1)</code>?<br> In that case, you might want to use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ndarray.flatten.html" rel="nofollow"><code>flatten</code></a>:</p>...
0
2016-06-15T14:25:21Z
[ "python", "arrays", "vector", "caffe" ]
Switching between frames in tkinter instead of stacking in eachother
37,838,159
<p>I have been trying all the many examples in this website about switching windows in tkinter, but all I get is the buttons from the raised frame to be stacked on top, without "hiding" the other frames</p> <p>Main screen :</p> <pre><code>import tkinter as tk import Controller.ProdutoController as viewProduto class ...
0
2016-06-15T14:22:01Z
37,838,344
<p>You aren't using the "sticky" attribute to force <code>ProdutoView</code> to fill the row and column that it is in.</p> <pre><code>class ProdutoView(tk.Frame): def __init__(self, root, ct): ... self.grid(row = 0, column = 0, sticky="nsew") </code></pre>
1
2016-06-15T14:29:50Z
[ "python", "tkinter" ]
Python: listing all the URLs of a website without index
37,838,271
<p>I can access each of the following URLs individually: <code>http://www.example.com/{.*}.html</code></p> <p>However the access to the main page <code>http://www.example.com</code> is somehow restricted and I am redirected to an error page displaying: <code>Erreur 403 - Refus de traitement de la requête (Interdit - ...
1
2016-06-15T14:26:53Z
37,838,888
<p>The short answer is no. You can't just list out all of the HTML pages in that domain like you list a directory. Assuming the website's robots.txt allows it, your best bet is to crawl the website using a web crawling module, like <a href="http://scrapy.org/" rel="nofollow">http://scrapy.org/</a></p>
1
2016-06-15T14:52:58Z
[ "python", "url", "web-crawler" ]
Python: listing all the URLs of a website without index
37,838,271
<p>I can access each of the following URLs individually: <code>http://www.example.com/{.*}.html</code></p> <p>However the access to the main page <code>http://www.example.com</code> is somehow restricted and I am redirected to an error page displaying: <code>Erreur 403 - Refus de traitement de la requête (Interdit - ...
1
2016-06-15T14:26:53Z
37,841,274
<p>Thanks to Brian: I managed to do it starting crawling from a list of accessible HTML pages hosted under the domain.</p> <pre><code># scrap.py from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class MySpider(CrawlSpider): name = 'example.com' allowed_domains = ['e...
0
2016-06-15T16:46:41Z
[ "python", "url", "web-crawler" ]
Xvfb and Selenium temp files are not automatically deleted from /tmp (Ubuntu)
37,838,335
<p>We have Buildbot on remote server to run python selenium tests. After a couple of days the tmp rubbish from XVFB and Selenium totaly consume all empty space and freeze the Buildbot activity. I used to clear /tmp it manualy with <code>sudo rm -rf *</code> in /tmp folder and then <code>sudo supervisorctl restart all<...
-1
2016-06-15T14:29:33Z
37,838,874
<ol> <li>Find source of /tmp bloating</li> <li>Make sure only /tmp is bloating</li> <li>Try to use <a href="http://manpages.ubuntu.com/manpages/wily/man8/tmpreaper.8.html" rel="nofollow">http://manpages.ubuntu.com/manpages/wily/man8/tmpreaper.8.html</a></li> </ol>
0
2016-06-15T14:52:25Z
[ "python", "selenium", "ubuntu", "xvfb", "buildbot" ]
withColumn not allowing me to use max() function to generate a new column
37,838,361
<p>I have a dataset like this:</p> <pre><code>a = sc.parallelize([[1,2,3],[0,2,1],[9,8,7]]).toDF(["one", "two", "three"]) </code></pre> <p>I want to have a dataset that adds a new column that is equal to the largest value in the other three columns. The output would look like this:</p> <pre><code>+----+----+-----+--...
1
2016-06-15T14:30:50Z
37,839,502
<p>If I understand it right, you mismatch max of a column and max of a row. In fact .withColumn needs to receive a column, what you need is a row operation.</p> <pre><code>b=a.map(lambda row: (row.one, row.two, row.three, max(row))) </code></pre> <p>b is then a rdd, you can convert it to dataframe</p> <pre><code>b.t...
1
2016-06-15T15:19:46Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
withColumn not allowing me to use max() function to generate a new column
37,838,361
<p>I have a dataset like this:</p> <pre><code>a = sc.parallelize([[1,2,3],[0,2,1],[9,8,7]]).toDF(["one", "two", "three"]) </code></pre> <p>I want to have a dataset that adds a new column that is equal to the largest value in the other three columns. The output would look like this:</p> <pre><code>+----+----+-----+--...
1
2016-06-15T14:30:50Z
37,839,854
<p>You cannot use <code>max</code> from python as it doesn't return the expected <code>pyspark.sql.Column</code>. An example of pyspark DataFrame functions is <code>array</code> which builds a list from a few columns, note the return:</p> <p><a href="http://spark.apache.org/docs/latest/api/python/_modules/pyspark/sql/...
0
2016-06-15T15:35:40Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
withColumn not allowing me to use max() function to generate a new column
37,838,361
<p>I have a dataset like this:</p> <pre><code>a = sc.parallelize([[1,2,3],[0,2,1],[9,8,7]]).toDF(["one", "two", "three"]) </code></pre> <p>I want to have a dataset that adds a new column that is equal to the largest value in the other three columns. The output would look like this:</p> <pre><code>+----+----+-----+--...
1
2016-06-15T14:30:50Z
37,842,157
<p>Actually what you need here is <code>greatest</code> not <code>max</code>:</p> <pre><code>from pyspark.sql.functions import greatest a.withColumn("max_col", greatest(a["one"], a["two"], a["three"])) </code></pre> <p>And just for completeness you can use <code>least</code> to find the minimum:</p> <pre><code>from...
2
2016-06-15T17:37:48Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
Binning a python pandas dataframe: extracting bin centers and the sum of another column
37,838,431
<p>I am having a bit of trouble binning a pandas dataframe and then extracting the necessary plotting variables.</p> <p>I have a pandas dataframe like the following:</p> <pre><code> a ad td price result profit_loss 12935 10809 -1181 2363 262 1.0 616743.0 13025 -18771 696 1390...
1
2016-06-15T14:33:37Z
37,839,961
<h1>Add <em>bin</em> column to the dataframe and then <em>groupby</em></h1> <p>A <em>bin</em> shall be <code>td - td%binsize</code> (<code>+ binsize/2</code> if you want centers).</p> <p>Then just <em>groupby</em> over <em>bin</em> and you can plot</p> <pre><code>&gt;&gt;&gt; df['bin'] = df.td - df.td % 2000 + 1000 ...
1
2016-06-15T15:40:08Z
[ "python", "pandas", "group-by", "binning" ]
Binning a python pandas dataframe: extracting bin centers and the sum of another column
37,838,431
<p>I am having a bit of trouble binning a pandas dataframe and then extracting the necessary plotting variables.</p> <p>I have a pandas dataframe like the following:</p> <pre><code> a ad td price result profit_loss 12935 10809 -1181 2363 262 1.0 616743.0 13025 -18771 696 1390...
1
2016-06-15T14:33:37Z
37,840,123
<p>if you want to show all the empty bins on the X-axis - you can do it this way:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') new = pd.DataFrame({'td':range(0, int(round(df.td.max() / 100) * 100) + 100, 100)}) (pd.merge(new, df.groupby(df.td//100*100)['profit_loss'...
1
2016-06-15T15:47:10Z
[ "python", "pandas", "group-by", "binning" ]
Modifying a file in-place inside nested for loops
37,838,508
<p>I am iterating directories and files inside of them while I modify in place each file. I am looking to have the <strong>new modified</strong> file being read right after. Here is my code with descriptive comments: </p> <pre><code># go through each directory based on their ids for id in id_list: id_dir = os.p...
2
2016-06-15T14:37:06Z
37,839,102
<p>I am not saying that the way you are going about doing this is incorrect but I feel that you are overcomplicating it. Here is my super simple solution.</p> <pre><code>import glob, fileinput for filename in glob('*' + ext): f_in = (x.rstrip() for x in open(filename, 'rb').readlines()) #instead of trying to modi...
1
2016-06-15T15:02:32Z
[ "python", "python-3.x", "for-loop", "in-place" ]
Modifying a file in-place inside nested for loops
37,838,508
<p>I am iterating directories and files inside of them while I modify in place each file. I am looking to have the <strong>new modified</strong> file being read right after. Here is my code with descriptive comments: </p> <pre><code># go through each directory based on their ids for id in id_list: id_dir = os.p...
2
2016-06-15T14:37:06Z
37,839,293
<p>For me it works with this code:</p> <pre><code>#!/usr/bin/env python3 import os from glob import glob import fileinput id_list=['1'] ouput_dir='.' ext = '.txt' # go through each directory based on their ids for id in id_list: id_dir = os.path.join(ouput_dir, id) os.chdir(id_dir) # go through all files...
1
2016-06-15T15:09:53Z
[ "python", "python-3.x", "for-loop", "in-place" ]
How to read depot's folders structure by p4python without syncing?
37,838,526
<p>I'd like to read folders and files structure inside a specified folder path on the P4 depot without syncing it. Is it possible?</p>
0
2016-06-15T14:37:40Z
37,859,207
<p>To get subfolders of specified depot path one should use this code</p> <pre><code>p4.run("dirs", path+'*') </code></pre> <p>The result will be a list of single-item dictionaries</p> <pre><code>[{'dir': '//Depot/path/dirname1'}, {'dir': '//Depot/path/dirname2'}] </code></pre> <p>In order to get all files containe...
3
2016-06-16T12:26:33Z
[ "python", "python-2.7", "perforce", "p4python" ]
Scipy's quad fails on "pretty smooth" function
37,838,668
<p><em>The data generating functions are quite messy, so I'll try to be as clear as I can be. Please comment if not good enough at doing so.</em></p> <p>I'm having a function in several variables and try to integrate it, holding the other one constant. However, for different values of that secondary variable, the inte...
1
2016-06-15T14:44:19Z
37,839,290
<p><code>quad</code> has a somewhat funky convention for the return value when <code>full_output</code> is True. If <code>quad</code> doesn't detect any problems, it returns <code>y, abserr, infodict</code>. If <code>quad</code> detects a failure of some form, it returns <code>y, abserr, infodict, message</code>. <c...
2
2016-06-15T15:09:34Z
[ "python", "numpy", "scipy", "integrate" ]
Python Unicode issues with .txt file
37,838,682
<p>To make a long story short, I am writing a Python script that asks for the user to drop a .docx file and the file converts to .txt. Python looks for keywords within the .txt file and displays them to the shell. I was running into UnicodeDecodeError codec charmap etc..... I overcame that by writing within my for loop...
0
2016-06-15T14:44:43Z
37,840,065
<p>Maybe posting the code producing the traceback would be easier to fix.</p> <p>I'm not sure this is the only problem, maybe this would work better:</p> <pre><code>with open(filename, "rb") as file: for line in file: for word in line.split(): file_words.append(word.decode("charmap")) </code><...
-1
2016-06-15T15:44:46Z
[ "python", "python-3.x", "unicode", "utf-8" ]
Python Unicode issues with .txt file
37,838,682
<p>To make a long story short, I am writing a Python script that asks for the user to drop a .docx file and the file converts to .txt. Python looks for keywords within the .txt file and displays them to the shell. I was running into UnicodeDecodeError codec charmap etc..... I overcame that by writing within my for loop...
0
2016-06-15T14:44:43Z
37,840,226
<p>In Python 3, don't open text files in binary mode. The default is the file will decode to Unicode using <code>locale.getpreferredencoding(False)</code> (<code>cp1252</code> on US Windows):</p> <pre><code>with open(filename) as file: for line in file: for word in line.split(): file_words.app...
1
2016-06-15T15:51:39Z
[ "python", "python-3.x", "unicode", "utf-8" ]
Python Unicode issues with .txt file
37,838,682
<p>To make a long story short, I am writing a Python script that asks for the user to drop a .docx file and the file converts to .txt. Python looks for keywords within the .txt file and displays them to the shell. I was running into UnicodeDecodeError codec charmap etc..... I overcame that by writing within my for loop...
0
2016-06-15T14:44:43Z
37,841,047
<p>Alright I figured it out. Here is my code, but I tried a docx file that seemed to be more complex and when converted to .txt the entire file consisted of special characters. So now I am thinking that I should go to the python-docx module, since it deals with xml files like Word documents. I added "encoding = 'charma...
-1
2016-06-15T16:34:48Z
[ "python", "python-3.x", "unicode", "utf-8" ]
Multiprocessing with pool in python: About several instances with same name at the same time
37,838,789
<p>I'm kind of new to multiprocessing. However, assume that we have a program as below. The program seems to work fine. Now to the question. In my opinion we will have 4 instances of <code>SomeKindOfClass</code> with the same name (<code>a</code>) at the same time. How is that possible? Moreover, is there a potential r...
4
2016-06-15T14:49:28Z
38,130,961
<p>The name <code>a</code> is only local in scope within your <code>work</code> function, so there is no conflict of names here. Internally python will keep track of each class instance with a unique identifier. If you wanted to check this you could check the object id using the <code>id</code> function:</p> <pre><c...
3
2016-06-30T18:42:34Z
[ "python", "memory", "multiprocessing", "pool" ]
Multiprocessing with pool in python: About several instances with same name at the same time
37,838,789
<p>I'm kind of new to multiprocessing. However, assume that we have a program as below. The program seems to work fine. Now to the question. In my opinion we will have 4 instances of <code>SomeKindOfClass</code> with the same name (<code>a</code>) at the same time. How is that possible? Moreover, is there a potential r...
4
2016-06-15T14:49:28Z
38,131,148
<p>You can declare class instances inside the pool workers, because each instance has a separate place in memory so they don't conflict. The problem is if you declare a class instance first, then try to pass that one instance into multiple pool workers. Then each worker has a pointer to the same place in memory, and ...
1
2016-06-30T18:53:22Z
[ "python", "memory", "multiprocessing", "pool" ]
Multiprocessing with pool in python: About several instances with same name at the same time
37,838,789
<p>I'm kind of new to multiprocessing. However, assume that we have a program as below. The program seems to work fine. Now to the question. In my opinion we will have 4 instances of <code>SomeKindOfClass</code> with the same name (<code>a</code>) at the same time. How is that possible? Moreover, is there a potential r...
4
2016-06-15T14:49:28Z
38,131,284
<p>If you are using multiprocessing you shouldn't worry - process doesn't share memory (by-default). So, there is no any risk to have several <strong>independent</strong> objects of class <code>SomeKindOfClass</code> - each of them will live in own process. How it works? Python runs your program and after that it runs ...
1
2016-06-30T19:01:18Z
[ "python", "memory", "multiprocessing", "pool" ]
Multiprocessing with pool in python: About several instances with same name at the same time
37,838,789
<p>I'm kind of new to multiprocessing. However, assume that we have a program as below. The program seems to work fine. Now to the question. In my opinion we will have 4 instances of <code>SomeKindOfClass</code> with the same name (<code>a</code>) at the same time. How is that possible? Moreover, is there a potential r...
4
2016-06-15T14:49:28Z
38,173,757
<p>Actually, you will have <code>8</code> instances of <code>SomeKindOfClass</code> (one for each worker), but only 4 will ever be active at the same time.</p> <h3><code>multiprocessing</code> vs <code>multiprocessing.dummy</code></h3> <p>Your program will only work if you continue to use the <code>multiprocessing.du...
2
2016-07-03T19:47:39Z
[ "python", "memory", "multiprocessing", "pool" ]
How can I find the groups with size more than a value in python?
37,838,830
<p>I read the data into a DataFrame and called it data. I have the following query in python:</p> <pre><code>data[data["gender"]=="male"].groupby('age').city.nunique().sort_values(ascending=False) age 29 86 24 85 21 81 25 81 20 81 28 78 27 78 </code></pre> <p>now I want to find those groups who...
0
2016-06-15T14:50:51Z
37,838,926
<p>The result of your aggregation and sorting call is a pandas series whose index are the groups you are looking for. So to find the groups with greater than a certain <code>cutOffvalue</code></p> <pre><code>cutOffValue = 80 counts = data[data["gender"]=="male"].groupby('age').city.nunique().sort_values(ascending=Fals...
0
2016-06-15T14:54:35Z
[ "python", "pandas" ]
Don't understand why this Python function returns a None while it's definitely not a None locally
37,838,856
<p>I have a Python function that traverses a sentence parsed as a tree looking for adjective/noun pairs (such as "good cat"), creates a list of such pairs, and returns it. Here it is:</p> <pre><code>def traverse(t): thelist = list() try: t.label() except AttributeError: return e...
0
2016-06-15T14:51:52Z
37,839,018
<p>I'm guessing that your first time through the <code>traverse</code> function, you are hitting the last line which recursively calls <code>traverse</code>. However, you don't do anything with the output of that call. My guess is that you should need to modify the last line to capture the output of the traverse call...
0
2016-06-15T14:58:50Z
[ "python", "recursion", "scope" ]
nested defaultdict based on a key inside dictionary
37,838,939
<p>I'm trying to create a defaultdict within a defaultdict based on a key value. My thinking may be completely wrong here, but here's the code for a basic defaultdict;</p> <pre><code>def record(): return { 'count': 0, 'key1': Counter(), } 1_record = defaultdict(record) </code></pre> <p>...
0
2016-06-15T14:54:54Z
37,839,057
<p>You definitely can have a "recursive" defaultdict:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; def record(): ... return { ... 'key': defaultdict(record) ... } ... &gt;&gt;&gt; d = defaultdict(record) &gt;&gt;&gt; &gt;&gt;&gt; d['foo'] {'key': defaultdict(&lt;function recor...
0
2016-06-15T15:00:38Z
[ "python", "dictionary", "nested", "defaultdict" ]
Edit a .txt file, then convert to valid xml with python
37,838,960
<p>I have lots of text files that I need to convert to .xml in order to be able to work with more efficiently (I am supposed to be doing a couple of language models to analyze English dialects)</p> <p>the files go like this:</p> <pre><code>&lt;I&gt; &lt;IFL-IDN W2C-001 #1:1&gt; &lt;#&gt; &lt;h&gt; &lt;bold&gt; Some S...
0
2016-06-15T14:56:00Z
37,907,633
<p>First, you don't have to load the file and split lines, you can iterate over the lines. An xml parser can be applied to each line separatly.</p> <pre><code>Korpus = open("w2c-001.txt") for line in Korpus: ... </code></pre> <p>If you want to parse it yourself, use regular expressions to find the tags</p> <pre>...
0
2016-06-19T13:14:03Z
[ "python", "xml", "converter", "txt2tags" ]
Is Django login redirect stripping my url parameters?
37,838,968
<p>In my URLconf I have the following url (where <code>login</code> is the built-in login view function from <code>django.contrib.auth.views</code>):</p> <pre><code>url(r'^login/', login, name='login', kwargs={ 'template_name': 'topspots/login.html', 'redirect_field_name': 'next', }) </code></pre> <p>Then in ...
1
2016-06-15T14:56:25Z
37,839,135
<p>What happens is that your generated url ends up being parsed like so:</p> <pre><code>next=/spots/search/?search_query=South+Oak+Park%2C+KCMO%2C+MO%2C+United+States searchtype=default latitude=38.97600750000001 longitude=-94.58623399999999 </code></pre> <p>The additional parameters are no longer part of the <code>n...
5
2016-06-15T15:03:46Z
[ "python", "django", "url-parameters" ]
Getting Grade from Score Range using statistics.mean
37,838,986
<p>I'm doing a CodeWars kata and am still new to python. The exercise requires one to complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.</p> <p>I've tried to do this in my text editor and running it doesn't produce any results. I've...
0
2016-06-15T14:57:16Z
37,839,341
<p>You have a couple minor problems, I'm pretty sure you meant <code>&gt;=</code> instead of <code>&lt;=</code> on the first clause of all the conditions. Also, when running a python script using <code>python script.py</code> the script needs to have a call to the method at the end in order for it to execute. Here's th...
1
2016-06-15T15:12:04Z
[ "python", "statistics" ]
When do I need a * character in function definition in Python?
37,839,032
<p>I have the two functions I defined as below,</p> <pre><code>def sumit(func,*args): return func(*args) def sumitt(*args): return sum(args) sumit(sumitt,2,3,4) </code></pre> <p>I experimented a bit by changing the second line to <code>return func(args)</code> and I got an error. But why in the 4th line, it's...
2
2016-06-15T14:59:32Z
37,839,159
<p>If you look at the documentation <code>sum</code> is defined as - </p> <pre><code>`sum(iterable[, start])` </code></pre> <p>which means it is taking an iterable object, which will traverse the arguments itself. </p> <p>So </p> <pre><code>def sumit(func,*args): return func(*args) def sumitt(*args): print...
2
2016-06-15T15:04:19Z
[ "python", "function" ]
When do I need a * character in function definition in Python?
37,839,032
<p>I have the two functions I defined as below,</p> <pre><code>def sumit(func,*args): return func(*args) def sumitt(*args): return sum(args) sumit(sumitt,2,3,4) </code></pre> <p>I experimented a bit by changing the second line to <code>return func(args)</code> and I got an error. But why in the 4th line, it's...
2
2016-06-15T14:59:32Z
37,839,204
<p>To apply the function on each of its arguments, you need the <code>*</code> to <em>unpack</em> the arguments of the function. </p> <p>So <code>func(*args)</code> is synomnymous to <code>func(arg1, arg2,...,argn)</code></p> <p>Have a look at <em>unpacking</em> in action:</p> <pre><code>&gt;&gt;&gt; first, second, ...
2
2016-06-15T15:05:40Z
[ "python", "function" ]
When do I need a * character in function definition in Python?
37,839,032
<p>I have the two functions I defined as below,</p> <pre><code>def sumit(func,*args): return func(*args) def sumitt(*args): return sum(args) sumit(sumitt,2,3,4) </code></pre> <p>I experimented a bit by changing the second line to <code>return func(args)</code> and I got an error. But why in the 4th line, it's...
2
2016-06-15T14:59:32Z
37,839,280
<p>If your function is expecting individual arguments but you have a sequence (a list, for example), you must specify the character <code>*</code> so that the list gets expanded (unpacked) into the sequence (otherwise it would be treated as one parameter)</p> <p>On the other hand, because the function <code>sum</code>...
1
2016-06-15T15:09:16Z
[ "python", "function" ]
When do I need a * character in function definition in Python?
37,839,032
<p>I have the two functions I defined as below,</p> <pre><code>def sumit(func,*args): return func(*args) def sumitt(*args): return sum(args) sumit(sumitt,2,3,4) </code></pre> <p>I experimented a bit by changing the second line to <code>return func(args)</code> and I got an error. But why in the 4th line, it's...
2
2016-06-15T14:59:32Z
37,839,800
<p><code>*args</code> in a function signature accepts an arbitrary list of of arguments and makes it available in the function's scope in a variable named <code>args</code></p> <p>for example</p> <pre><code>def my_print(*args): """print all arguments passed in""" for arg in args: try: print(arg) exc...
2
2016-06-15T15:33:01Z
[ "python", "function" ]
Convert dictionary of dictionaries into DataFrame Python
37,839,136
<p>I am trying to convert the following dictionary of dictionaries into pandas DataFrame. </p> <p>My dictionary looks like this: </p> <pre><code>mydata = {1965:{1:52, 2:54, 3:67, 4:45}, 1966:{1:34, 2:34, 3:35, 4:76}, 1967:{1:56, 2:56, 3:54, 4:34}} </code></pre> <p>And I need to get a resulting...
2
2016-06-15T15:03:48Z
37,839,175
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow"><code>DataFrame.from_records</code></a>:</p> <pre><code>import pandas as pd ydata = {1965:{1:52, 2:54, 3:67, 4:45}, 1966:{1:34, 2:34, 3:35, 4:76}, 1967:{1:56, 2:56, 3:...
2
2016-06-15T15:04:56Z
[ "python", "dictionary", "pandas", "dataframe" ]
Patch/update custom fields for users via Google Directory API in Python
37,839,160
<p>I am not able to patch/update custom fields for my users via Google Directory API in Python. I am using google-api-python-client/1.5.1.</p> <p>I am able to patch/update custom fields via <a href="https://developers.google.com/admin-sdk/directory/v1/reference/users/patch" rel="nofollow">https://developers.google.com...
0
2016-06-15T15:04:22Z
38,118,783
<p>Try sending just customSchemas instead of patchg. </p> <p>I ran into something similar where I shouldn't have dumped to a string. </p> <p>In my current code where I change customSchema, I'm currently just sending the patch dict in the submission body and that seems to work fine.</p>
0
2016-06-30T09:17:45Z
[ "python", "json", "google-admin-sdk", "google-directory-api" ]
How to plot data while it's being processed
37,839,265
<p>I'm in the process of converting a large (several GBs) bin file to csv format using Python so the resulting data can be plotted. I'm doing this conversion because the bin file is not in a format that a plotting tool/module could understand, so there needs to be some decoding/translation. Right now it seems like Gnup...
1
2016-06-15T15:08:27Z
37,839,374
<p>You can plot the data as it is being processed, but there's a couple of issues that come along with it in terms of efficiency.</p> <ol> <li>Gnuplot needs to do work each time to process your data</li> <li>Gnuplot needs to wait for your operating system to paint your screen whenever it updates</li> <li>Your program ...
0
2016-06-15T15:13:33Z
[ "python", "plot", "gnuplot" ]
Is it good idea to change variable to 0 to save memory in python?
37,839,298
<p>I've searched and couldn't find any good answer. Let's say that I have some list that have thousands of entries or something else that consumes a lot of memory. Is it good idea to change this list/etc. value to 0...</p> <pre><code>oldlst = 0 </code></pre> <p>...if it's no longer needed (or won't be updated in a ve...
0
2016-06-15T15:10:01Z
37,839,368
<p>You need to think on releasing memory rather than making list to 0 once not required.</p> <p>Please <a href="http://stackoverflow.com/questions/15455048/releasing-memory-in-python">refer</a></p>
-3
2016-06-15T15:13:20Z
[ "python", "memory-management" ]
How can I quickly filter a large dataset?
37,839,361
<p>I have a large data set with global latitudes and longitudes. However, I am only interested in looking at a specific region, so I want to filter out all lat/lons that are outside of this region. The problem is that I am using if statements to parse the data, however, this takes too long. Is there a faster way to a...
0
2016-06-15T15:13:03Z
37,839,461
<p>Is there any reason you need your data sorted? Sorting is an expensive operation <code>O(nlogn)</code> whereas filtering is just <code>O(n)</code>. If sorting isn't a requirement, you can do it like so with 1 filtering operation. (Keep in mind, I don't know your data, so you may need to modify this a bit)</p> <pre>...
0
2016-06-15T15:17:55Z
[ "python", "numpy" ]
Pandas: Get SettingWithCopyWarning when using set_categories
37,839,389
<p>I have two data frame. Both have the same set of columns but some columns are categorical typed (based on the actual containing values). In order to combine them I refresh the categorical type of the categorical columns with the union of both values.</p> <pre class="lang-py prettyprint-override"><code>def appendDFs...
1
2016-06-15T15:14:29Z
37,839,872
<p>This is most likely happening because of the objects you are passing to your function.</p> <p>If I set up the following example:</p> <pre><code>cats1 = pd.Series(['a', 'a', 'b', 'b'], name='cat', dtype="category") data1 = pd.Series([1, 2, 3, 4], name='val', dtype=np.int64) df1 = pd.concat([cats1, data1], axis=1) <...
1
2016-06-15T15:36:17Z
[ "python", "pandas", "dataframe", "categorical-data" ]
Python, tkinter: Bind all buttons to <Return>, so their callback will be triggered?
37,839,403
<p>Is it possible to bind all instances of <code>ttk.Button</code> in my app in a single bind to <code>'&lt;Return&gt;'</code> event, so when Enter button is pressed, <code>ttk.Button</code> callback will be triggered.</p> <p>In addition, some buttons may have a <code>lambda</code> callback, so is there a generalised ...
0
2016-06-15T15:15:15Z
37,839,759
<p>You can manually invoke a button using their <code>.invoke()</code> method, since you are making a binding you will have access to the specific widget in question with <code>e.widget</code> and invoke that specific button:</p> <pre><code>import tkinter as tk root = tk.Tk() button1 = tk.Button(root, text="button1"...
1
2016-06-15T15:31:22Z
[ "python", "python-3.x", "tkinter" ]
YouTube API v3 - get video title by url in Python
37,839,431
<p>I'd like to know how can I simply get the title or other information about a video using Youtube API, in case the only thing I know is the url of the video (so basically the video ID).</p> <p>What other info can I get about a video? eg: Length, Category, Uploader name, Country of origin, ... ??? </p> <p>Can somebo...
0
2016-06-15T15:16:42Z
37,839,635
<p>There are plenty of examples and documentation about what you can get using the YouTube API's Python bindings.</p> <p>Here are Python code samples as provided by YouTube: <a href="https://developers.google.com/youtube/v3/code_samples/python#create_and_manage_youtube_video_caption_tracks" rel="nofollow">https://deve...
1
2016-06-15T15:26:00Z
[ "python", "api", "video", "youtube", "metadata" ]
Remove replace pipe (|) symbol with comma (,) symbol in spark using python
37,839,549
<p>this <code>myRDD</code> data for 2 <code>rows</code>:</p> <pre><code>[u'#fields:excDate|schedDate|TZ|custID|muID|tvID|acdID|logonID|agentName|modify|exception|start|stop|LS Oracle Emp ID|Team Lead', u'06152016|06152016|CET|3|3000|1688|87||Ali, AbdElaziz|1465812004|Open|08:00|09:00|101021021|ElDeleify,Hisham'] </cod...
-1
2016-06-15T15:21:52Z
37,839,623
<pre><code>&gt;&gt;&gt; data = [u'#fields:excDate|schedDate|TZ|custID|muID|tvID|acdID|logonID|agentName|modify|exception|start|stop|LS Oracle Emp ID|Team Lead', u'06152016|06152016|CET|3|3000|1688|87||Ali, AbdElaziz|1465812004|Open|08:00|09:00|101021021|ElDeleify,Hisham'] &gt;&gt;&gt; data = [item.replace("|", ",") for...
2
2016-06-15T15:25:22Z
[ "python", "apache-spark" ]
Remove replace pipe (|) symbol with comma (,) symbol in spark using python
37,839,549
<p>this <code>myRDD</code> data for 2 <code>rows</code>:</p> <pre><code>[u'#fields:excDate|schedDate|TZ|custID|muID|tvID|acdID|logonID|agentName|modify|exception|start|stop|LS Oracle Emp ID|Team Lead', u'06152016|06152016|CET|3|3000|1688|87||Ali, AbdElaziz|1465812004|Open|08:00|09:00|101021021|ElDeleify,Hisham'] </cod...
-1
2016-06-15T15:21:52Z
37,839,901
<p>It doesn't even need a for loop, suppose your string is called 'data':</p> <pre><code>data[0] = data[0].replace('|',',') </code></pre> <p>Done nice and easy in one line. </p>
0
2016-06-15T15:37:45Z
[ "python", "apache-spark" ]
Remove replace pipe (|) symbol with comma (,) symbol in spark using python
37,839,549
<p>this <code>myRDD</code> data for 2 <code>rows</code>:</p> <pre><code>[u'#fields:excDate|schedDate|TZ|custID|muID|tvID|acdID|logonID|agentName|modify|exception|start|stop|LS Oracle Emp ID|Team Lead', u'06152016|06152016|CET|3|3000|1688|87||Ali, AbdElaziz|1465812004|Open|08:00|09:00|101021021|ElDeleify,Hisham'] </cod...
-1
2016-06-15T15:21:52Z
37,842,396
<p>according to <a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.SQLContext.createDataFrame" rel="nofollow">spark doc on <code>createDataFrame</code></a> one way to create a frame is to pass it data as a list of list and the header as a list.</p> <pre><code>data = [u'#fields:excDate...
2
2016-06-15T17:50:00Z
[ "python", "apache-spark" ]
How to restart Flask process by refreshing page
37,839,551
<p>I have a simple <code>Flask</code> application that queries a database using a set of parameters and then plots the result. This works fine, but how do I restart process(querying database, plotting data) whenever its still running and I do a refresh of the page or I click the submit button again?</p> <pre><code>app...
0
2016-06-15T15:21:58Z
38,146,003
<p>You should use queues For example Celery + Redis or Celery + RabbitMq as mentioned by others. You can examples here: <a href="http://eon01.com/blog/celery-worker-rabbitmq-broker-step-by-step-introduction/" rel="nofollow">http://eon01.com/blog/celery-worker-rabbitmq-broker-step-by-step-introduction/</a></p>
1
2016-07-01T12:55:08Z
[ "python", "flask" ]
Window does not close when Python script on Windows is finished, until launched program exits
37,839,657
<p>The follwing python script works fine, exept that the shell window remains open. </p> <pre><code>file = open("C:\\Documents and Settings\\User1\\Desktop\\BPanel\BadePanel\\SteelUsage.bsu", "a+") input = raw_input("Please enter project name:") input = input.upper () for line in file.readlines(): if input in...
0
2016-06-15T15:27:13Z
37,840,140
<p>From the doc:</p> <blockquote> <p>subprocess.call() </p> <blockquote> <p>Run the command described by args. Wait for command to complete, then return the returncode attribute.</p> </blockquote> </blockquote> <p>So the <code>.call()</code> function only ever returns after BadePanael.exe finishes.</p> ...
1
2016-06-15T15:47:44Z
[ "python", "shell", "exit" ]
Threads vd processes in parallel computing
37,839,688
<p>I am implementing two algotihms that run in a multi-agent framework, so each agent should run the algorithm. The first algorithm is sequential, each agent should wait for the previous one, but the second one is concurrent. </p> <p>I implemented both with threads and the running time is more or less the same for bot...
0
2016-06-15T15:28:15Z
37,840,125
<p>Threads vs. Processes</p> <p>Why threads could be faster:</p> <blockquote> <ul> <li>Spawning a new process is much slower than starting a new thread.</li> <li>Communicating between processes is much slower than communicating between threads.</li> <li>Threads need less memory than processes.</li> <li>I...
1
2016-06-15T15:47:12Z
[ "python", "multithreading", "multiprocessing", "multi-agent" ]
Python - Swap a value for a dictionary item
37,839,709
<p>So basically, I have my dictionary, which looks like this: </p> <pre><code>{'my': 2, 'Phil.': 10, 'name': 3, 'Andy.': 5, 'Hello': 1, 'is': 4} </code></pre> <p>and a string that looks like this: </p> <pre><code>1 2 3 4 5 1 2 3 4 10 </code></pre> <p>How can I make it so each number in the string is replaced b...
-4
2016-06-15T15:29:30Z
37,839,983
<p>First make from your string a list. </p> <pre><code>list_name = string_name.split(' ') </code></pre> <p>Then switch the keys and the values from your dict (if using python 3.x use iter instead of iteritems)</p> <pre><code>my_dict = {y:x for x,y in my_dict.iteritems()} </code></pre> <p>Then you can iter tro your ...
0
2016-06-15T15:41:06Z
[ "python", "dictionary" ]
Python - Deleting all files in Temp
37,839,728
<p>How delete all files in temp?</p> <p>thanks to kevin i improved it to :</p> <pre><code>tmp = os.environ.get("TMP") def remc(tmp): if tmp: try: for f in os.listdir(tmp): ntmp = os.path.join(tmp,f) os.remove(ntmp) except OSError: pass </cod...
-1
2016-06-15T15:30:16Z
37,840,156
<p>I have not found a <em>great</em> way of getting the default temporary directory, but I have seen platform dependent search lists of where it is supposed to try. On windows, for the active user, the "TMP" environment variable seems to have the path.</p> <p>Given that, something like this may suit your needs:</p> <...
0
2016-06-15T15:48:23Z
[ "python", "windows" ]
Python - Deleting all files in Temp
37,839,728
<p>How delete all files in temp?</p> <p>thanks to kevin i improved it to :</p> <pre><code>tmp = os.environ.get("TMP") def remc(tmp): if tmp: try: for f in os.listdir(tmp): ntmp = os.path.join(tmp,f) os.remove(ntmp) except OSError: pass </cod...
-1
2016-06-15T15:30:16Z
37,870,654
<pre><code>tmp = os.environ.get("TMP") def remc(tmp): if tmp: for f in os.listdir(tmp): ntmp = os.path.join(tmp,f) try: os.remove(ntmp) except OSError as errf: print errf else: try: os.removedir(ntmp) except...
0
2016-06-16T22:54:39Z
[ "python", "windows" ]
Parsing a file as an array with eval/exec in python
37,839,761
<p>I am trying to read a line from a file, that already looks like an array, and convert it to an array using this:</p> <pre><code>eval('points='+lineFromFile) print(points) </code></pre> <p>It works, when I try this:</p> <pre><code>points=[(1, 0, 0, 0), (4752/8677, 7260/8677, 0, -35/8677)] print(points) </code></pr...
0
2016-06-15T15:31:28Z
37,840,053
<p>I'm going to answer the "how can I fix it" part of the question and suggest that you use <code>ast.literal_eval</code>:</p> <pre><code>import ast points = ast.literal_eval(lineFromFile) </code></pre> <p>This has the side benefit that it should be <em>safe</em> from malicious code execution and is generally cleaner...
2
2016-06-15T15:44:14Z
[ "python", "file" ]
Django error. Cannot assign must be an instance
37,839,867
<p>I get the following error when I try to run an insert into one of my tables.</p> <blockquote> <p>Cannot assign "1": "Team.department_id" must be a "Department" instance</p> </blockquote> <p>Admittedly I'm slightly unsure if I'm using the foreign key concept correctly. The insert I'm trying to run and a snippet f...
0
2016-06-15T15:36:08Z
37,840,037
<p>You don't need to pass the department id, the instance itself is enough. The following should work just fine:</p> <pre><code>new_team = Team( nickname = team_name, employee_id = employee_id, department_id = Department.objects.get(password = password, department_name = department_name) ) </code></pre> <...
2
2016-06-15T15:43:36Z
[ "python", "django", "foreign-keys", "models" ]
Remove following duplicates in a numpy array
37,839,928
<p>I would like to remove duplicates which follow each other, but not duplicates along the whole array. Also I want to keep the ordering unchanged.</p> <p>So if the input is <code>[0 0 1 3 2 2 3 3]</code> the output should be <code>[0 1 3 2 3]</code></p> <p>I found a way using <code>itertools.groupby()</code> but I a...
1
2016-06-15T15:38:49Z
37,840,247
<p>For pure python wich also works with numpy arrays use this:</p> <pre><code>def modify(l): last = None for e in l: if e != last: yield e last = e pure = modify([0, 0, 1, 3, 2, 2, 3, 3]) import numpy num = numpy.array(modify(numpy.array([0, 0, 1, 3, 2, 2, 3, 3]))) </code></pre> ...
0
2016-06-15T15:52:24Z
[ "python", "numpy" ]
Remove following duplicates in a numpy array
37,839,928
<p>I would like to remove duplicates which follow each other, but not duplicates along the whole array. Also I want to keep the ordering unchanged.</p> <p>So if the input is <code>[0 0 1 3 2 2 3 3]</code> the output should be <code>[0 1 3 2 3]</code></p> <p>I found a way using <code>itertools.groupby()</code> but I a...
1
2016-06-15T15:38:49Z
37,840,467
<pre><code>a[np.insert(np.diff(a).astype(np.bool),0,True)] Out[99]: array([0, 1, 3, 2, 3]) </code></pre> <p>The general idea is to use <code>diff</code> to find the difference between two consecutive elements in the array. Then we only index those which give <code>non-zero</code> differences elements. But since the le...
3
2016-06-15T16:01:40Z
[ "python", "numpy" ]
Can Python launch Firefox with a specific profile?
37,839,963
<p>I'm trying to write some automated tests for Firefox using Marionette and its Python client, but Python doesn't seem to be able to launch Python with a specified profile. This is a problem because I need two Firefox profiles for the test. I'm trying to use <code>subprocess.call(['C:\\Program Files (x86)\\Mozilla Fir...
0
2016-06-15T15:40:22Z
37,840,622
<p><code>"-P Marionette"</code> must be two different entries in the list. so use</p> <pre><code>subprocess.call([firefox_fullpath, "-p", "Marionette"]) </code></pre> <p>"-P Marionette" are technically two arguments (applies for any OS I know of).</p>
0
2016-06-15T16:10:17Z
[ "python", "python-2.7", "firefox", "firefox-marionette" ]
self.encoding_errors & I/O operation on closed file
37,839,971
<p>The below problem is temporarily fixed. I figured out that the input file (csv) has special characters (e.g. Aimí©) that resulted in the error. I now manually change the characters (e.g. Aimí© --> Aime).</p> <p>Previous question:</p> <p>I am using <code>unicodecsv</code> while writing to a csv file. My program...
-1
2016-06-15T15:40:40Z
37,840,479
<p>Try the following:</p> <pre><code>import unicodecsv as csv with open(csv_file_name_write, "wb") as f: writer = csv.writer(f, encoding="utf-8") writer.writerow(["A", "B", "C"]) </code></pre> <p>If that does not solve your problem, unfortunately, I cannot help you because this is working on my machine.</p>
1
2016-06-15T16:02:06Z
[ "python", "csv", "python-unicode" ]
Pandas - unstack column values into new columns
37,840,043
<p>I have a large dataframe and I am storing a lot of redundant values that are making it hard to handle my data. I have a dataframe of the form:</p> <pre><code>import pandas as pd df = pd.DataFrame([["a","g","n1","y1"], ["a","g","n2","y2"], ["b","h","n1","y3"], ["b","h","n2","y4"]], columns=["meta1", "meta2", "name"...
1
2016-06-15T15:43:58Z
37,840,079
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and <a href="htt...
2
2016-06-15T15:45:25Z
[ "python", "pandas", "dataframe" ]
Pandas - unstack column values into new columns
37,840,043
<p>I have a large dataframe and I am storing a lot of redundant values that are making it hard to handle my data. I have a dataframe of the form:</p> <pre><code>import pandas as pd df = pd.DataFrame([["a","g","n1","y1"], ["a","g","n2","y2"], ["b","h","n1","y3"], ["b","h","n2","y4"]], columns=["meta1", "meta2", "name"...
1
2016-06-15T15:43:58Z
37,840,494
<p>If you group your meta columns into a list then you can do this:</p> <pre><code>metas = ['meta1', 'meta2'] new_df = df.set_index(['name'] + metas).unstack('name') print new_df data name n1 n2 meta1 meta2 a g y1 y2 b h y3 y4 </code></pre> <p>Which gets you ...
1
2016-06-15T16:03:00Z
[ "python", "pandas", "dataframe" ]
Maintaining numpy subclass inside a container after applying ufunc
37,840,097
<p>I have created a class derived from numpy's ndarray following <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.subclassing.html" rel="nofollow">numpy's documentation</a>, and it looks like (reduce the number of attributes to make it more readable): </p> <pre><code>import numpy as np class Atom3D( np.nda...
0
2016-06-15T15:46:15Z
37,840,862
<p>There's no such thing as <code>dtype=Atom3D</code>. The same goes for <code>dtype=list</code> and <code>dtype=np.ndarray</code>. It creates a <code>dtype=object</code> array, where each element is a pointer to objects elsewhere in memory.</p> <p>Creating an object array with <code>np.array(...)</code> can be tric...
1
2016-06-15T16:25:07Z
[ "python", "numpy", "subclass" ]
Google Appengine Hello World gets HTTP 500 Error
37,840,104
<p>I created a new project in Google Appengine but when I try to access it through localhost I get a HTTP 500 Error. My browser says 'localhost is currently unable to handle this request.' The following is my code for the new project:</p> <p>app.yaml:</p> <pre><code>application: hello-world version: 1 runtime: pyth...
1
2016-06-15T15:46:25Z
37,904,385
<p>Update: the issue was fixed in SDK version 1.9.40.</p> <p>There is <a href="https://code.google.com/p/googleappengine/issues/detail?id=12963" rel="nofollow">a GAE issue</a> causing exactly this behaviour introduced in SDK version 1.9.37, see <a href="http://stackoverflow.com/questions/37755195/importerror-no-module...
0
2016-06-19T05:55:22Z
[ "python", "google-app-engine", "web-development-server" ]
How to avoid flake8's "F821 undefined name '_'" when _ has been installed by gettext?
37,840,142
<h2>Problem overview:</h2> <p>In my project's main script, <code>gettext</code> installs the function <code>_()</code> that is used in other modules for translations (like in <code>print(_('Something to translate'))</code>).</p> <p>As stated by <a href="https://docs.python.org/3/library/gettext.html#gettext.install" ...
2
2016-06-15T15:47:54Z
37,840,774
<p>You could specify the <code>--builtins="_"</code> which is more specific than <code>--ignore F821</code>.</p> <p>You should be able to specify this in a configuration file as well if you don't like command line arguments.</p>
3
2016-06-15T16:19:35Z
[ "python", "python-3.x", "gettext", "pyflakes", "flake8" ]
How do I read this stringified javascript variable into Python?
37,840,185
<p>I'm trying to read _pageData from <a href="https://www.simpliowebstudio.com/wp-content/uploads/2014/07/aWfyh1" rel="nofollow">https://www.simpliowebstudio.com/wp-content/uploads/2014/07/aWfyh1</a> into Python 2.7.11 so that I can process it, using this code:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 ...
0
2016-06-15T15:49:39Z
37,841,118
<p>It seems like there are three kinds of syntactic errors in your string:</p> <ul> <li><code>,</code> followed by <code>,</code></li> <li><code>[</code> followed by <code>,</code></li> <li><code>,</code> followed by <code>]</code></li> </ul> <p>Assuming that those are supposed to be <code>null</code> elements (or <c...
2
2016-06-15T16:38:30Z
[ "python", "json", "parsing", "yaml", "abstract-syntax-tree" ]
How do I read this stringified javascript variable into Python?
37,840,185
<p>I'm trying to read _pageData from <a href="https://www.simpliowebstudio.com/wp-content/uploads/2014/07/aWfyh1" rel="nofollow">https://www.simpliowebstudio.com/wp-content/uploads/2014/07/aWfyh1</a> into Python 2.7.11 so that I can process it, using this code:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 ...
0
2016-06-15T15:49:39Z
37,841,232
<p>I started off using <code>ast.literal.eval(...)</code> because I was under the (mistaken?) impression that javascript arrays and Python lists were mutually compatible, so all I had to do was destringify _pageData.</p> <p>However, I hadn't noticed that Python doesn't like <code>,,</code> <code>true</code>, <code>fal...
0
2016-06-15T16:44:33Z
[ "python", "json", "parsing", "yaml", "abstract-syntax-tree" ]
tkinter destroy button after click
37,840,196
<p>I created Hangman game for python and I want create gui for my code. I try create 26 buttons (one for each letter in alphabet). After I clicked the button, I want destroyed it. But I don't know how define specific button to destroy. I have tried destroy() to click function but it just delete last button(z).</p> <pr...
1
2016-06-15T15:50:14Z
37,840,549
<p>You can separate out the assignment of <code>command</code> to another line so that you can pass a reference of the button widget itself to your <code>click()</code> function:</p> <pre><code>... for l in alphabet: self.button = Button(self.frame_let, text=l, bg='orange', width=5) self.button['co...
1
2016-06-15T16:06:13Z
[ "python", "python-3.x", "tkinter" ]
Having problems with Python rounding
37,840,328
<p>I'm creating a python program and when I have a variable which is a float (3.14) it changes it to an integer (3). How can I prevent the variable changes from 3.14 to 3 and make it round to 4?</p> <p>For example:</p> <ul> <li>2.8458 rounds down to 2, but I want it to round up to 3</li> <li>4.1 rounds down to 4, but...
-1
2016-06-15T15:55:29Z
37,840,488
<p>You can use ceil(ceiling)</p> <pre><code>import math math.ceil(5.2) 6 </code></pre>
1
2016-06-15T16:02:40Z
[ "python", "python-3.x" ]
python - split iterable according string and make splits of same length
37,840,406
<p>I have a generator object like the following:</p> <pre><code>a = ["ab", "fasj", "sfk", "sfsfg", "ab", "gwre", "ab", "werwe", "fsfj", "lke"] </code></pre> <p>Using python, how do I split this according the occurrence of "ab" into chunks of the same length?</p> <p>I am looking for something like:</p> <pre><code>b ...
1
2016-06-15T15:58:53Z
37,840,782
<p>The following code is not perfect but gets the job done (if I understood your problem correctly):</p> <pre><code>array = ["ab", "fasj", "sfk", "sfsfg", "ab", "gwre", "ab", "werwe", "fsfj", "lke"] def split(l): def internal(): stack = [] for v in l: if v == "ab": if s...
2
2016-06-15T16:20:01Z
[ "python", "split", "generator" ]
python - split iterable according string and make splits of same length
37,840,406
<p>I have a generator object like the following:</p> <pre><code>a = ["ab", "fasj", "sfk", "sfsfg", "ab", "gwre", "ab", "werwe", "fsfj", "lke"] </code></pre> <p>Using python, how do I split this according the occurrence of "ab" into chunks of the same length?</p> <p>I am looking for something like:</p> <pre><code>b ...
1
2016-06-15T15:58:53Z
37,841,215
<p>This code isn't very clean, but it may do the trick. Definitely verify it for yourself and see if it answers your question correctly.</p> <pre><code>listOfLists = [] newList = [] count = 0 for i in a: if i == "ab": if newList: listOfLists.append(newList) count = 0 newList = [...
1
2016-06-15T16:43:53Z
[ "python", "split", "generator" ]