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 |
|---|---|---|---|---|---|---|---|---|---|
From a guessing game in python, I can't get myself to get the correct one | 38,887,421 | <p>This is my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>from sys import exit
import random
number = random.randint(1, 10)
count = 0
def guess():
print ("Input a number 1 - 10")
guess = input()
if guess == "I give up":
print ("The correct number was", number,"!")
print ("You tried", count, "times before giving up!")
exit(0)
else:
if guess == (number):
print ("CORRECT!")
print (count, "failed attempts.")
exit(0)
else:
print ("WRONG!")
print ("Try again!")
global count
count += 1
while True:
guess()</code></pre>
</div>
</div>
</p>
<p>If I run this, I can keep guessing but never get the correct number. I said I gave up, and it gave me the correct number. But I already guessed that number, so I don't know what's the problem. </p>
| 0 | 2016-08-11T04:45:17Z | 38,887,429 | <p>You are taking the input as a string rather than an integer. Thus, you may be comparing <code>"5"</code> to <code>5</code>, which is false. Instead, call <code>if int(guess) == (number)</code></p>
| 0 | 2016-08-11T04:46:19Z | [
"python"
] |
Python what is the name of ':.' or what are search terms to bring up its meaning | 38,887,462 | <p>Following from this question <a href="http://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points">Stackoverflow question</a> the answer provided has ':.' character inside the print statement. i.e</p>
<pre><code>a=13.946
print("{0:.2f}".format(a))
</code></pre>
<p>My question is what is the ':.' called? i want to search it and learn what other options there are.</p>
| 1 | 2016-08-11T04:49:31Z | 38,887,492 | <p>They are separate things. </p>
<p>The <code>.2f</code> is a part of the format specifier which says print only the first two digits after the decimal point. </p>
<p>The <code>:</code> is another part of the format specifier as described <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow">here</a>: </p>
<p>"Each field can also specify an optional set of 'format
specifiers' which can be used to adjust the format of that field.
Format specifiers follow the field name, with a colon (':')
character separating the two:"</p>
<pre><code>"My name is {0:8}".format('Fred')
</code></pre>
<p>Outputs <code>'Fred'</code> plus 4 spaces to make 8 characters:</p>
<pre><code>'My name is Fred '
</code></pre>
| 2 | 2016-08-11T04:52:39Z | [
"python"
] |
Python what is the name of ':.' or what are search terms to bring up its meaning | 38,887,462 | <p>Following from this question <a href="http://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points">Stackoverflow question</a> the answer provided has ':.' character inside the print statement. i.e</p>
<pre><code>a=13.946
print("{0:.2f}".format(a))
</code></pre>
<p>My question is what is the ':.' called? i want to search it and learn what other options there are.</p>
| 1 | 2016-08-11T04:49:31Z | 38,887,496 | <p>There is no such character as <code>:.</code>. What you are seeing here is <code>:</code> followed by <code>.2f</code> which means a floating point number with 2 decimals.</p>
<p>In this code:</p>
<pre><code>a=13.946
print("{0:.2f}".format(a))
</code></pre>
<p>The command being given in the print is convert the float into a two decimal place string.
This would print <code>13.95</code></p>
| 0 | 2016-08-11T04:53:05Z | [
"python"
] |
Python what is the name of ':.' or what are search terms to bring up its meaning | 38,887,462 | <p>Following from this question <a href="http://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points">Stackoverflow question</a> the answer provided has ':.' character inside the print statement. i.e</p>
<pre><code>a=13.946
print("{0:.2f}".format(a))
</code></pre>
<p>My question is what is the ':.' called? i want to search it and learn what other options there are.</p>
| 1 | 2016-08-11T04:49:31Z | 38,887,563 | <p>According to <a href="https://docs.python.org/2/library/string.html" rel="nofollow">Pythong strings library</a> 7.1.3 - Format string syntax, shows that you can add a <em>format_spec</em> </p>
<blockquote>
<p>a format_spec, which is preceded by a colon ':' These specify a non-default format for the replacement value.</p>
</blockquote>
<p><a href="https://docs.python.org/2/library/string.html#formatspec" rel="nofollow"> Format Specification Mini-Language</a> shows you the whole list of options available and the context on how they can be used.</p>
<p><em>Python 2.7</em></p>
| 1 | 2016-08-11T04:59:55Z | [
"python"
] |
Python what is the name of ':.' or what are search terms to bring up its meaning | 38,887,462 | <p>Following from this question <a href="http://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points">Stackoverflow question</a> the answer provided has ':.' character inside the print statement. i.e</p>
<pre><code>a=13.946
print("{0:.2f}".format(a))
</code></pre>
<p>My question is what is the ':.' called? i want to search it and learn what other options there are.</p>
| 1 | 2016-08-11T04:49:31Z | 38,887,615 | <p>Test it with some more statements, then you will understand it more:-</p>
<pre><code>a = 13.946
print("{0:.2f}".format(a))
a = 13.946
print("{1:.2f}".format(a, 10))
a = 13.946
print("{2:.2f}".format(a, 10, 12))
a = 13.946
print("{3:.2f}".format(a, 10, 12))
</code></pre>
<p>Here is brief:-</p>
<pre><code>.2f means format your number with 2 decimal places.
0 says you need to select first item passed to format.
:. is nothing but these 2 are separate thing. : is separate between item and format
</code></pre>
| 0 | 2016-08-11T05:03:49Z | [
"python"
] |
Python what is the name of ':.' or what are search terms to bring up its meaning | 38,887,462 | <p>Following from this question <a href="http://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points">Stackoverflow question</a> the answer provided has ':.' character inside the print statement. i.e</p>
<pre><code>a=13.946
print("{0:.2f}".format(a))
</code></pre>
<p>My question is what is the ':.' called? i want to search it and learn what other options there are.</p>
| 1 | 2016-08-11T04:49:31Z | 38,888,595 | <p>:. is two separate thing.
Don't get confuse and be fool by its deception and theatric </p>
<p>Hint ':' follow by '.' </p>
<p>The colon is a format spec</p>
<p>The dot is a leading path to mini-language , in this case 2f </p>
| 1 | 2016-08-11T06:17:11Z | [
"python"
] |
xlwings error using caller from excel | 38,887,473 | <p>I am trying to call python code from excel using </p>
<pre><code>wb = xw.Book.caller()
</code></pre>
<p>If file path is in English, it works. However, if the path has other language, it raise below Error popup</p>
<pre><code>---------------------------
Error
---------------------------
C:\Anaconda2\lib\site-packages\xlwings\main.py:2692: UnicodeWarning: Unicode unequal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
throw = (os.path.normpath(os.path.realpath(impl.fullname.lower())) != os.path.normpath(fullname.lower()))
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "test.py", line 13, in plot_chart
wb = xw.Book.caller()
File "C:\Anaconda2\lib\site-packages\xlwings\main.py", line 545, in caller
return cls(impl=app.books.open(fullname).impl)
File "C:\Anaconda2\lib\site-packages\xlwings\main.py", line 2695, in open
"Cannot open two workbooks named '%s', even if they are saved in different locations." % name
ValueError: Cannot open two workbooks named 'test.xlsm', even if they are saved in different locations.
</code></pre>
<p>Guess this has something to do with unicode problem. I did not have this kind of problem with previous version. (e.g. 0.6 or 0.7) This is new problem after I updated to version 0.9.2.</p>
<p>Thank you for any help</p>
<p>p.s. I am using Python 2.7</p>
| 1 | 2016-08-11T04:51:08Z | 39,339,686 | <p>xlwings version 0.9.3 solve above problem. Self closing the question.</p>
| 0 | 2016-09-06T02:13:50Z | [
"python",
"excel",
"xlwings"
] |
ImportError: cannot import name _imaging Accessing from Django Admin Pillow | 38,887,626 | <p>I have been struggling with the error for two days, tried all the answers from stack overflow but no luck. I have a simple model which use Django image field</p>
<pre><code>class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
url = models.URLField(blank=True, null=True)
short_bio = models.TextField(max_length=200, blank=True, null=True)
long_bio = models.TextField(max_length=5000, blank=True, null=True)
role = models.ManyToManyField(AuthorRole)
facebook_link = models.URLField(blank=True, null=True)
linkedin_link = models.URLField(blank=True, null=True)
twitter_link = models.URLField(blank=True, null=True)
gplus_link = models.URLField(blank=True, null=True)
thumbnail = models.ImageField(upload_to='images/', default='images/user_default.jpg')
</code></pre>
<p>In production server when I am accessing the model from admin and select an image and try to save, its throwing the following error. I installed and uninstalled pillow several times. Tried different version of django and pillow. By the way its working fine in local environment.</p>
<pre><code>[:error] [pid 20256:tid 139822013380352] [remote 72.48.102.12:60881]
from PIL import Image
[:error] [pid 20256:tid 139822013380352] [remote 72.48.102.12:60881] File"/home/.virtualenvs/wcsenvpython3/lib/python3.4/sitepackages/PIL/Image.py", line 67, in <module>
[:error] [pid 20256:tid 139822013380352] [remote 72.48.102.12:60881]
from PIL import _imaging as core
[:error] [pid 20256:tid 139822013380352] [remote 72.48.102.12:60881] ImportError:cannot import name _imaging
</code></pre>
<p>I can do <code>from PIL import _imaging</code> from manage.py shell. So it looks like pythonpath is configured properly.<a href="http://i.stack.imgur.com/mWHW9.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/mWHW9.jpg" alt="enter image description here"></a></p>
<p>Inside my virtualenv I can see the _imaging.cpython-34m.so file, but there is no
_imaging.py file.<a href="http://i.stack.imgur.com/3CmfK.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/3CmfK.jpg" alt="enter image description here"></a></p>
<p>My server is hosted in linode. It's Ubuntu 14.04. I am using Apache2. Python 3.4.3. Django 1.10 Pillow 3.3.0. You kind help is very much appreciable. This error is bugging me for long time.</p>
<p><a href="http://i.stack.imgur.com/mWHW9.jpg" rel="nofollow">1</a>: <a href="http://i.stack.imgur.com/nH8O3.jpg" rel="nofollow">http://i.stack.imgur.com/nH8O3.jpg</a> <a href="http://i.stack.imgur.com/3CmfK.jpg" rel="nofollow">2</a>: <a href="http://i.stack.imgur.com/Vpdoe.jpg" rel="nofollow">http://i.stack.imgur.com/Vpdoe.jpg</a></p>
| 0 | 2016-08-11T05:04:37Z | 38,925,498 | <p>Alright, I got the answer at last. It has nothing to do with Pillow. I gave write permission for public to 'media' folder where images are saved and suddenly it solved the problem. I am not sure if it's a security vulnerability but it solves the error.</p>
<p><strong>How did I find it:</strong><br>
I decided to change the Image.py file from PIL. </p>
<pre><code> try:
# If the _imaging C module is not present, Pillow will not load.
# Note that other modules should not refer to _imaging directly;
# import Image and use the Image.core variable instead.
# Also note that Image.core is not a publicly documented interface,
# and should be considered private and subject to change.
from PIL import _imaging as core
if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None):
raise ImportError("The _imaging extension was built for another "
" version of Pillow or PIL")
except ImportError as v:
core = _imaging_not_installed()
# Explanations for ways that we know we might have an import error
if str(v).startswith("Module use of python"):
# The _imaging C module is present, but not compiled for
# the right version (windows only). Print a warning, if
# possible.
warnings.warn(
"The _imaging extension was built for another version "
"of Python.",
RuntimeWarning
)
elif str(v).startswith("The _imaging extension"):
warnings.warn(str(v), RuntimeWarning)
elif "Symbol not found: _PyUnicodeUCS2_" in str(v):
# should match _PyUnicodeUCS2_FromString and
# _PyUnicodeUCS2_AsLatin1String
warnings.warn(
"The _imaging extension was built for Python with UCS2 support; "
"recompile Pillow or build Python --without-wide-unicode. ",
RuntimeWarning
)
elif "Symbol not found: _PyUnicodeUCS4_" in str(v):
# should match _PyUnicodeUCS4_FromString and
# _PyUnicodeUCS4_AsLatin1String
warnings.warn(
"The _imaging extension was built for Python with UCS4 support; "
"recompile Pillow or build Python --with-wide-unicode. ",
RuntimeWarning
)
# Fail here anyway. Don't let people run with a mostly broken Pillow.
# see docs/porting.rst
raise
</code></pre>
<p>The except block is checking few conditions and last line is raising import error again. I commented out <code>raise</code> , and bingo it showed me permission error.
I don't know why in earth it shows import error while the problem is permission. I would expect the writers of pillow to look at the matter and try to generate relevant error message while problem is not really import error rather permission error.</p>
| 0 | 2016-08-12T19:48:30Z | [
"python",
"django",
"django-admin",
"importerror",
"pillow"
] |
Left join on multiple columns | 38,887,666 | <p>I'm used to using dplyr with R where I would do something like</p>
<pre><code>library(dplyr)
mtcars2=mtcars
mtcars3 = mtcars %>% left_join(mtcars2[,c("mpg","vs","hp")], by =c("mpg",'hp') )
# what this does is I do a left join with multiple columns and then bring over only *1* additional column. This means that mtcars3 only has one additional field - a duplicated 'vs'
</code></pre>
<p>I can't figure out how to use pd.merge to do the same thing.
I would want to join by two columns and then bring over <em>only</em> the 3rd column - not every column in the joined table except for the join-bys if that makes sense</p>
<pre><code>import pandas as pd
mtcars = pd.read_csv('mtcars.csv')
mtcars2=mtcars
mtcars3 = pd.merge(mtcars, mtcars2['vs','hp','mpg'],how='left', on = ['mpg','hp'])
</code></pre>
| 2 | 2016-08-11T05:08:15Z | 38,887,695 | <p>IIUC you can use subset by adding <code>[]</code> and omit <code>mtcars2</code> - you can use <code>mtcars</code> again:</p>
<pre><code>import pandas as pd
mtcars = pd.read_csv('mtcars.csv')
mtcars3 = pd.merge(mtcars, mtcars[['vs','hp','mpg']], how='left', on = ['mpg','hp'])
</code></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
mtcars = pd.DataFrame({'vs':[1,2,3],
'hp':[1,1,1],
'mpg':[7,7,9],
'aaa':[1,3,5]})
print (mtcars)
aaa hp mpg vs
0 1 1 7 1
1 3 1 7 2
2 5 1 9 3
mtcars3 = pd.merge(mtcars, mtcars[['vs','hp','mpg']], how='left', on = ['mpg','hp'])
print (mtcars3)
aaa hp mpg vs_x vs_y
0 1 1 7 1 1
1 1 1 7 1 2
2 3 1 7 2 1
3 3 1 7 2 2
4 5 1 9 3 3
</code></pre>
| 2 | 2016-08-11T05:10:39Z | [
"python",
"pandas",
"merge",
"left-join"
] |
why blank page opens in firefox when run with selenium for the first time? | 38,887,700 | <pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
#driver.set_preference("browser.startup.homepage_override.mstone", "ignore")
driver.get("https://url.aspx/")
username = driver.find_element_by_name("SchSel$txtUserName")
username.clear()
username.send_keys("username")
username.send_keys(Keys.RETURN)
password = driver.find_element_by_name("SchSel$txtPassword")
password.clear()
password.send_keys("pass")
password.send_keys(Keys.RETURN)
driver.get("https://.aspx")
assert "Welcome" in driver.page_source
driver.close()
</code></pre>
<p>I am running selenium for the first time .How many times I try blank page opens in fireFox</p>
<blockquote>
<p>selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.</p>
</blockquote>
| 0 | 2016-08-11T05:11:30Z | 38,887,886 | <p>I think I had a similar problem and used the info at this link to help:</p>
<p><a href="http://stackoverflow.com/a/30103931/6582364">http://stackoverflow.com/a/30103931/6582364</a></p>
<p>Basically it suggests using xvfb and pyvirtualdisplay which wraps the firefox browser. Link also contains sample code. Doesn't take too long to install and get running but worked for me.</p>
<p>Hope this works for you too.</p>
| 0 | 2016-08-11T05:27:50Z | [
"python",
"selenium",
"selenium-webdriver",
"python-3.4"
] |
ImportError: No module named app.models | 38,887,735 | <p>I'm learning Django and I keep bumping into obstacles and it takes time googling to overcome the hurdle. But this one took me over 20 minutes and I still don't know the answer.</p>
<p>I know this is simple but I tried many things and can't seem to get access to my models.py. I keep getting the same error</p>
<p><strong>Error</strong></p>
<blockquote>
<p>Traceback (most recent call last):
File "import_states.py", line 11, in
from app.models import State
ImportError: No module named app.models</p>
</blockquote>
<p><strong>Code in Context</strong></p>
<pre><code>#!/usr/bin/env python
import csv
import os
import sys
sys.path.append("..")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from app.models import State
states = State.objects.all()
for state in states:
print state.name
</code></pre>
<p>Here is the <strong>path to my script folder that contains the script</strong></p>
<pre><code>/Users/ahmedawayhan/Development/projects/states/project/scripts
</code></pre>
<p>and here is the <strong>path to the folder that contains the models.py</strong></p>
<pre><code>/Users/ahmedawayhan/Development/projects/states/app
</code></pre>
<p>Any help would be appreciated.</p>
| 1 | 2016-08-11T05:14:47Z | 38,888,681 | <p>Don't do this in ths way. Do it in the django-way. First read about <a href="https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/" rel="nofollow">custom management command</a></p>
<p>And add:</p>
<p><strong>app/management/commands/import_states.py</strong></p>
<pre><code>from django.core.management.base import BaseCommand
from app.models import State
class Command(BaseCommand):
def handle(self, *args, **options):
states = State.objects.all()
for state in states:
print state.name
</code></pre>
<p>and call it:</p>
<pre><code>python manage.py import_states
</code></pre>
<p>If You really need Your-way:</p>
<pre><code>sys.path.append("../..")
</code></pre>
<p>or call:</p>
<pre><code>python project/scripts/import_states.py
</code></pre>
| 1 | 2016-08-11T06:21:45Z | [
"python",
"django",
"importerror",
"file-not-found"
] |
converting string to date some values are missing python | 38,887,992 | <p>I want to be able to convert string to date format in python. But some of the day and month are assigned to 00.</p>
<pre><code>date = ['00-00-2001', '10-01-2014']
</code></pre>
<p>when I tried :</p>
<p><code>datetime.strptime(date[1], '%d-%m-%Y')</code>, of course it works fine,
but doing <code>datetime.strptime(date[0], '%d-%m-%Y')</code>, I get the following error. </p>
<blockquote>
<p>time data '00-00-2001' does not match format '%d-%m-%Y'</p>
</blockquote>
| -2 | 2016-08-11T05:35:57Z | 38,888,083 | <p>According to <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">Python Docs</a>:</p>
<blockquote>
<p>%d Day of the month as a zero-padded decimal number. 01, 02, ..., 31</p>
<p>%m Month as a zero-padded decimal number. 01, 02, ..., 12</p>
</blockquote>
<p>None of these accept <code>00</code> as valid string.</p>
<p>Also see my answer at <a href="http://stackoverflow.com/a/38801552/1005215">http://stackoverflow.com/a/38801552/1005215</a> which explains how you can use the <code>parser</code> from <code>dateutil</code> by passing a default parameter.</p>
| 1 | 2016-08-11T05:43:18Z | [
"python",
"string",
"date"
] |
converting string to date some values are missing python | 38,887,992 | <p>I want to be able to convert string to date format in python. But some of the day and month are assigned to 00.</p>
<pre><code>date = ['00-00-2001', '10-01-2014']
</code></pre>
<p>when I tried :</p>
<p><code>datetime.strptime(date[1], '%d-%m-%Y')</code>, of course it works fine,
but doing <code>datetime.strptime(date[0], '%d-%m-%Y')</code>, I get the following error. </p>
<blockquote>
<p>time data '00-00-2001' does not match format '%d-%m-%Y'</p>
</blockquote>
| -2 | 2016-08-11T05:35:57Z | 38,888,647 | <p>Execute:</p>
<pre><code>corrected_date = []
for d in dates:
components = d.split('-')
components = [str(c).zfill(2) if(int(c) > 0) else str(int(c) + 1).zfill(2) for c in components]
corrected_date.extend(['-'.join(components)])
</code></pre>
<p>Now try your <code>strftime</code> on <code>corrected_date</code>. </p>
| 0 | 2016-08-11T06:20:17Z | [
"python",
"string",
"date"
] |
'int' object is not iterable error (Project Euler 4) | 38,888,062 | <p>I am currently working on Project Euler Problem 4 (<a href="https://projecteuler.net/problem=4" rel="nofollow">https://projecteuler.net/problem=4</a>) and am consistently getting an error when I try to run my code. I have looked at other questions regarding the 'int' object is not iterable, but have not found one that has helped me so far. Here is my current code:</p>
<pre><code># Euler 4
# Find the largest palindrome made from the product of two 3-digit numbers
j = []
i = None
for x,y in range(1,1000):
j.append(x*y)
for i in range(1,j.length):
if (str(j[i]))[::-1] == str(j[i]):
print j
</code></pre>
<p>When I run this, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Daniel Bashir\Desktop\HMC\Projects\Python\Project Euler\PE4.py", line 5, in <module>
for x,y in range(1,1000):
TypeError: 'int' object is not iterable
</code></pre>
<p>Most of the fixes I have seen for this for loop issue involve changing "for a in b" to "for a in range...", but I already have that syntax here.</p>
<p>Could anyone help me figure out what is wrong?</p>
<p>Any general comments about my code are also welcome. I'm just a beginner!</p>
| 0 | 2016-08-11T05:41:03Z | 38,888,087 | <p>range(start, end) yields integers</p>
<p>using this</p>
<pre><code>for x,y in range(1,1000):
</code></pre>
<p>you are trying to iterate over an integer (1)
you can't iterate over an integer</p>
<p>you want</p>
<pre><code>for x in range(1,1000):
</code></pre>
| 1 | 2016-08-11T05:43:43Z | [
"python",
"typeerror",
"palindrome"
] |
'int' object is not iterable error (Project Euler 4) | 38,888,062 | <p>I am currently working on Project Euler Problem 4 (<a href="https://projecteuler.net/problem=4" rel="nofollow">https://projecteuler.net/problem=4</a>) and am consistently getting an error when I try to run my code. I have looked at other questions regarding the 'int' object is not iterable, but have not found one that has helped me so far. Here is my current code:</p>
<pre><code># Euler 4
# Find the largest palindrome made from the product of two 3-digit numbers
j = []
i = None
for x,y in range(1,1000):
j.append(x*y)
for i in range(1,j.length):
if (str(j[i]))[::-1] == str(j[i]):
print j
</code></pre>
<p>When I run this, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Daniel Bashir\Desktop\HMC\Projects\Python\Project Euler\PE4.py", line 5, in <module>
for x,y in range(1,1000):
TypeError: 'int' object is not iterable
</code></pre>
<p>Most of the fixes I have seen for this for loop issue involve changing "for a in b" to "for a in range...", but I already have that syntax here.</p>
<p>Could anyone help me figure out what is wrong?</p>
<p>Any general comments about my code are also welcome. I'm just a beginner!</p>
| 0 | 2016-08-11T05:41:03Z | 38,892,024 | <p>You are trying (without realizing it) to iterate over each integer yielded by the <code>range</code> function:</p>
<pre><code>for x,y in range (1,1000):
j.append(x*y)
</code></pre>
<p>The comma in <code>x,y</code> makes those three characters a single 2-tuple, which is <em>not</em> the same as two variables <code>x</code> and <code>y</code>... especially when they're on the left-hand side of an assignment statement. Yes, <code>for</code> is an assignment statement --- about a thousand of them, in your case --- with the <code>x,y</code> tuple on the left side and an integer on the right:</p>
<pre><code>(x, y) = 1 # TypeError: 'int' object is not iterable
(x, y) = 2 # It never gets this far...
#...
(x, y) = 1000 # ...but it's trying to.
</code></pre>
<p>Assigning to a tuple uses <strong>sequence unpacking</strong> (described at the end of the "<a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">Tuples and Sequences</a>" section), which iterates over the values and assigns them to the variables inside the tuple. But there is no sequence of values in your code, only an <code>int</code>, which leads directly to the "'int' object is not iterable" error message.</p>
<p>As <a href="https://stackoverflow.com/questions/38888087/4116239">luke_aus answered</a>, you can solve the immediate problem by replacing the tuple with a lone variable, but that means <code>y</code> never gets assigned:</p>
<pre><code>for x in range(1, 1000):
j.append(x * y) # NameError: name 'y' is not defined
</code></pre>
<p>In this case, though, you don't need <code>y</code> at all. It's always equal to <code>x</code>, so just use <code>x</code>:</p>
<pre><code>for x in range(1, 1000):
j.append(x * x)
</code></pre>
<p>Or, if you really <em>will</em> need that <code>y</code> later, just assign <code>y</code> whenever "later" happens:</p>
<pre><code>for x in range(1, 1000):
j.append(x * x)
#...
y = something_else() # Later is now!
do_something_with_both(x, y)
</code></pre>
| 0 | 2016-08-11T09:10:37Z | [
"python",
"typeerror",
"palindrome"
] |
calculate number of minutes by passing Milliseconds | 38,888,115 | <p><strong>Here i am adding solution for to calculate number of minutes by Milliseconds</strong></p>
<pre><code>def returnTimeString(miliSec):
returnVal = "%d" % ( ((miliSec / 1000) / 60) )
if returnVal == '0':
returnVal = 'N/A'
return returnVal
</code></pre>
<p><strong>But I want different way then this to fetch number of minutes by passing Milliseconds</strong></p>
| -3 | 2016-08-11T05:45:26Z | 38,888,145 | <p>milliseconds to minutes</p>
<pre><code>y = miliSec / 1000
y /= 60
minutes = y % 60
</code></pre>
<p>Oneliner</p>
<pre><code>minutes=(miliSec/(1000*60))%60
</code></pre>
<p>Final result:</p>
<pre><code>def returnTimeString(miliSec):
minutes=(miliSec/(1000*60))%60
return "%d" % (minutes) if minutes else 'N/A'
</code></pre>
| 0 | 2016-08-11T05:47:34Z | [
"python",
"django",
"time",
"minute"
] |
calculate number of minutes by passing Milliseconds | 38,888,115 | <p><strong>Here i am adding solution for to calculate number of minutes by Milliseconds</strong></p>
<pre><code>def returnTimeString(miliSec):
returnVal = "%d" % ( ((miliSec / 1000) / 60) )
if returnVal == '0':
returnVal = 'N/A'
return returnVal
</code></pre>
<p><strong>But I want different way then this to fetch number of minutes by passing Milliseconds</strong></p>
| -3 | 2016-08-11T05:45:26Z | 38,888,510 | <p>here is what you need</p>
<pre><code>minutes=float(miliSec/float(1000*60))%60.
</code></pre>
<p>simple and elegant </p>
| 0 | 2016-08-11T06:11:54Z | [
"python",
"django",
"time",
"minute"
] |
calculate number of minutes by passing Milliseconds | 38,888,115 | <p><strong>Here i am adding solution for to calculate number of minutes by Milliseconds</strong></p>
<pre><code>def returnTimeString(miliSec):
returnVal = "%d" % ( ((miliSec / 1000) / 60) )
if returnVal == '0':
returnVal = 'N/A'
return returnVal
</code></pre>
<p><strong>But I want different way then this to fetch number of minutes by passing Milliseconds</strong></p>
| -3 | 2016-08-11T05:45:26Z | 38,890,760 | <p>Here is another solution based on this <a href="http://stackoverflow.com/a/175576/6607630">post</a> that gives you the conversion from milliseconds to seconds, minutes, and days.</p>
<pre><code>def millitosec(milliseconds):
x = milliseconds / 1000
seconds = x % 60
x /= 60
minutes = x % 60
x /= 60
hours = x % 24
x /= 24
days = x
return seconds, minutes, hours, days
</code></pre>
| -1 | 2016-08-11T08:09:56Z | [
"python",
"django",
"time",
"minute"
] |
Match string with multiple patterns by regular expression | 38,888,377 | <p>I have a list of string:
How to return strings end with 'Low' or end with 'High' or start with 'NQ_'?</p>
<pre><code>list=[
'ES_Low',
'NQ_High',
'NQ_Low',
'NQ_Close',
'NQ_Volume',
'GC_Open',
'GC_High',
'GC_Volume']
AnswerDesired=[
'ES_Low',
'NQ_High',
'NQ_Low',
'NQ_Close',
'NQ_Volume',
'GC_High']
</code></pre>
| -3 | 2016-08-11T06:03:52Z | 38,889,297 | <p>Hope this code will do that,</p>
<pre><code>import re
list=['ES_Low','NQ_High','NQ_Low','NQ_Close','NQ_Volume','GC_Open','GC_High','GC_Volume']
for i in list:
if (re.search("^NQ_|Low$|High$", i)):
print i
</code></pre>
<p>Output:</p>
<pre><code>ES_Low
NQ_High
NQ_Low
NQ_Close
NQ_Volume
GC_High
</code></pre>
| 1 | 2016-08-11T06:55:43Z | [
"python",
"regex"
] |
Match string with multiple patterns by regular expression | 38,888,377 | <p>I have a list of string:
How to return strings end with 'Low' or end with 'High' or start with 'NQ_'?</p>
<pre><code>list=[
'ES_Low',
'NQ_High',
'NQ_Low',
'NQ_Close',
'NQ_Volume',
'GC_Open',
'GC_High',
'GC_Volume']
AnswerDesired=[
'ES_Low',
'NQ_High',
'NQ_Low',
'NQ_Close',
'NQ_Volume',
'GC_High']
</code></pre>
| -3 | 2016-08-11T06:03:52Z | 38,891,722 | <p>As said in the comments: not really a need for regular expressions here.</p>
<pre><code>lst=[
'ES_Low',
'NQ_High',
'NQ_Low',
'NQ_Close',
'NQ_Volume',
'GC_Open',
'GC_High',
'GC_Volume']
def cleanse(item):
if item.endswith('Low') \
or item.endswith('High') \
or item.startswith('NQ_'):
return True
desired = list(filter(cleanse, lst))
print(desired)
# ['ES_Low', 'NQ_High', 'NQ_Low', 'NQ_Close', 'NQ_Volume', 'GC_High']
</code></pre>
<p>See <a href="http://ideone.com/PJFVI2" rel="nofollow"><strong>a demo on ideone.com</strong></a> additionally.
<hr>
Of course, the same can be achieved with regular expression as well:</p>
<pre><code>import re
rx = re.compile(r'(?:^NQ_)|(?:(?:Low|High)$)')
desired = [item for item in lst if rx.search(item)]
print(desired)
# ['ES_Low', 'NQ_High', 'NQ_Low', 'NQ_Close', 'NQ_Volume', 'GC_High']
</code></pre>
| 1 | 2016-08-11T08:57:26Z | [
"python",
"regex"
] |
submitting a form on click of link in cherrypy | 38,888,383 | <p>Below is my cherrypy code:</p>
<pre><code>class MyApp:
def link_details(self, **params):
pass
link_details.exposed=True
</code></pre>
<p>The below is my html code:</p>
<pre><code><form name="form1">
<input type="text" name="username"> <a href="link_details">Click here</a>
</form>
</code></pre>
<p>The page gets redirected, but I am not able to access the form request parameters. I want the form to be submitted to the link_details method on the click of a link in the html page. How can I do this?</p>
| 1 | 2016-08-11T06:04:07Z | 38,891,424 | <p>You're not submitting the form, you're just linking to a different page.</p>
<p>The easiest way to submit a form is by using a submit button:</p>
<pre><code><form id="form1" action="/link_details" method="post">
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
</code></pre>
<p>If you want to submit the form with your <code><a></code> tag:</p>
<pre><code><form id="form1" action="/link_details" method="post">
<input type="text" name="username" />
<!-- you can omit the "return false;" part, but since we don't use a "href" attribute on the anchor it does not matter -->
<a onclick="document.getElementById('form1').submit();return false;" target="_self">Submit</a>
</form>
</code></pre>
<p>For more information on a form's attributes (such as <code>action</code> and <code>method</code>) please visit <a href="https://developer.mozilla.org/de/docs/Web/HTML/Element/form" rel="nofollow">https://developer.mozilla.org/de/docs/Web/HTML/Element/form</a></p>
| 1 | 2016-08-11T08:42:52Z | [
"python",
"cherrypy"
] |
Download a file from S3 Bucket using boto3 by passing credentials as parameters | 38,888,392 | <p>As per Boto3 official documentation, we can connect S3 bucket by passing credentials as a parameters. But I am facing issues. </p>
<p><strong>Working Scenario : Hardcoding Key ID & Secret Key</strong></p>
<pre><code>s3r = boto3.resource('s3', aws_access_key_id='XXXXXXXXXXXXXXXXXXXX',
aws_secret_access_key='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
buck = s3r.Bucket('bucket name')
buck.download_file(filename,filename)
</code></pre>
<p><strong>Non Working Scenario : Passing as parameters</strong></p>
<pre><code>AccessKey = 'XXXXXXXXXXXXXXXXXXXX'
SecretKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
s3r = boto3.resource('s3', aws_access_key_id=AccessKey, aws_secret_access_key=SecretKey)
buck = s3r.Bucket('bucket name')
buck.download_file(filename,filename)
</code></pre>
<p>I am facing below error for non-working scenario.</p>
<pre><code>botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden
</code></pre>
| 0 | 2016-08-11T06:04:17Z | 38,889,263 | <p><a href="http://boto3.readthedocs.io/en/latest/guide/configuration.html" rel="nofollow">http://boto3.readthedocs.io/en/latest/guide/configuration.html</a></p>
<pre><code>session = boto3.Session(aws_access_key_id=AccessKey, aws_secret_access_key=SecretKey)
s3 = session.resource('s3')
</code></pre>
| 0 | 2016-08-11T06:54:04Z | [
"python",
"python-3.x",
"amazon-s3",
"aws-sdk",
"boto3"
] |
Adding username in url after base url in django | 38,888,400 | <p>I am working on django project(which is at verge of completion) and I have structure like something below:
project name: Mysite
App name: myapp</p>
<p>project urls : 127.0.0.1/myapp/blog etc</p>
<p>my requirement is to exclude my app from website (through out) and adding usernames in profile page like:</p>
<ul>
<li>127.0.0.1/blog</li>
<li>127.0.0.1/products</li>
<li>127.0.0.1/search</li>
</ul>
<p>and for profile page:
127.0.0.1/simer123/myprofile</p>
<p>I have took from various SO questions and able to exclude the "myapp" part from my urls.
and Also able to include "username" in url for specific page.
<a href="http://stackoverflow.com/questions/28533096/django-how-to-implement-an-example-com-username-url-system">SO question1</a> <a href="http://stackoverflow.com/questions/3694795/facing-problem-with-user-profile-url-scheme-like-example-com-username-in-django">SO question2</a> these questions really helped and I found a way out to include user name in my url. </p>
<p>But now again I am stuck because throughout the project I have used things like:</p>
<pre><code> return HttpResponseRedirect(reverse_lazy('myapp:myprofile'))
</code></pre>
<p>And similarly in template part like:</p>
<pre><code><a href="{% url 'myapp:myprofile' %}">
</code></pre>
<p>How can I manage to convert them? </p>
<p>Can Anyone explain this with some example.</p>
<p>Thanks</p>
<p><strong>Update:</strong>
urls.py file in mysite folder looks like below:</p>
<pre><code>urlpatterns = [
url(r'^autocomplete/', include('autocomplete_light.urls')),
url(r'^$', 'myapp.views.index'),
url(r'^', include('myapp.urls', namespace="myapp")),
url(r'^myapp/', include('myapp.urls', namespace="myapp")),
url(r'^admin/login', adminLogin),
#url(r'^static/(?P<path>.*)$', views.serve),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^(?P<username>\w+)/', include('myapp.urls', namespace="myapp")),
url(r'^(?P<username>\w+)/myapp/', include('myapp.urls', namespace="myapp")),
]
</code></pre>
<p>urls.py in myapp folder includes urls like below:</p>
<pre><code>urlpatterns = [
# ex: /myapp/
url(r'^autocomplete/', include('autocomplete_light.urls')),
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='user_about'),
url(r'^login/$', views.login, name='login'),
url(r'^newaccount/(?P<uid>.*)/$', views.newaccount, name='newaccount'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^myprofile/$', views.profile, name='profile'),
]
</code></pre>
| 1 | 2016-08-11T06:04:46Z | 38,888,487 | <p>You can pass a <code>kwargs dict</code> to your <code>reverse</code> and <code>reverse_lazy</code> function in order to mapping it with your url pattern. </p>
<pre><code>reverse_lazy('myapp:profile', kwargs={'username': username})
</code></pre>
<p>And in your template, just pass it as positional argument </p>
<pre><code><a href="{% url 'myapp:profile' username %}">
</code></pre>
| 1 | 2016-08-11T06:10:16Z | [
"python",
"django"
] |
Adding username in url after base url in django | 38,888,400 | <p>I am working on django project(which is at verge of completion) and I have structure like something below:
project name: Mysite
App name: myapp</p>
<p>project urls : 127.0.0.1/myapp/blog etc</p>
<p>my requirement is to exclude my app from website (through out) and adding usernames in profile page like:</p>
<ul>
<li>127.0.0.1/blog</li>
<li>127.0.0.1/products</li>
<li>127.0.0.1/search</li>
</ul>
<p>and for profile page:
127.0.0.1/simer123/myprofile</p>
<p>I have took from various SO questions and able to exclude the "myapp" part from my urls.
and Also able to include "username" in url for specific page.
<a href="http://stackoverflow.com/questions/28533096/django-how-to-implement-an-example-com-username-url-system">SO question1</a> <a href="http://stackoverflow.com/questions/3694795/facing-problem-with-user-profile-url-scheme-like-example-com-username-in-django">SO question2</a> these questions really helped and I found a way out to include user name in my url. </p>
<p>But now again I am stuck because throughout the project I have used things like:</p>
<pre><code> return HttpResponseRedirect(reverse_lazy('myapp:myprofile'))
</code></pre>
<p>And similarly in template part like:</p>
<pre><code><a href="{% url 'myapp:myprofile' %}">
</code></pre>
<p>How can I manage to convert them? </p>
<p>Can Anyone explain this with some example.</p>
<p>Thanks</p>
<p><strong>Update:</strong>
urls.py file in mysite folder looks like below:</p>
<pre><code>urlpatterns = [
url(r'^autocomplete/', include('autocomplete_light.urls')),
url(r'^$', 'myapp.views.index'),
url(r'^', include('myapp.urls', namespace="myapp")),
url(r'^myapp/', include('myapp.urls', namespace="myapp")),
url(r'^admin/login', adminLogin),
#url(r'^static/(?P<path>.*)$', views.serve),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^(?P<username>\w+)/', include('myapp.urls', namespace="myapp")),
url(r'^(?P<username>\w+)/myapp/', include('myapp.urls', namespace="myapp")),
]
</code></pre>
<p>urls.py in myapp folder includes urls like below:</p>
<pre><code>urlpatterns = [
# ex: /myapp/
url(r'^autocomplete/', include('autocomplete_light.urls')),
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='user_about'),
url(r'^login/$', views.login, name='login'),
url(r'^newaccount/(?P<uid>.*)/$', views.newaccount, name='newaccount'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^myprofile/$', views.profile, name='profile'),
]
</code></pre>
| 1 | 2016-08-11T06:04:46Z | 38,888,575 | <p>Your base url doesn't need to mention <code>myapp</code> at all, just set your url that includes <code>myapp</code> to <code>r'^'</code>. You can still namespace the urls and everything the same as before.</p>
| 1 | 2016-08-11T06:15:55Z | [
"python",
"django"
] |
Certain variable not able to be defined? | 38,888,581 | <p>Just in case someone takes this down yes, I went looking for the answer before hand. So I am working on a small personal project and I became stuck (Just so you know I'm very new to Python). I'll show you what I mean</p>
<pre><code>joke = input("Want to hear a funny joke?\n")
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
else:
print("Awww..")
</code></pre>
<p>What I'm trying to get to happen here is python will ask you if you want to hear a joke, if you say no it will go "Awww.." and if you say yes it will ask you why did the chicken cross the road. It works when I say yes but when I say no it gives this</p>
<pre><code>Want to hear a funny joke?
no
Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\Python projects\Python Buddie.py", line 34, in <module>
if chicken in ["To get to the other side", "to get to the other side"]:
NameError: name 'chicken' is not defined
</code></pre>
<p>I have chicken defined as you can see. I feel like I'm getting an order wrong, could anyone help me?</p>
| 0 | 2016-08-11T06:16:19Z | 38,888,625 | <pre><code>if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
</code></pre>
<p>What happens if <code>joke</code> is <strong>not</strong> <code>in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']</code>?</p>
<p>Then <code>chicken</code> is not defined. You should either have the second <code>if</code> inside the first <code>if</code>, or define <code>chicken</code> beforehand:</p>
<pre><code>if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
</code></pre>
<p>or</p>
<pre><code>chicken = None
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
</code></pre>
| 2 | 2016-08-11T06:19:18Z | [
"python"
] |
Certain variable not able to be defined? | 38,888,581 | <p>Just in case someone takes this down yes, I went looking for the answer before hand. So I am working on a small personal project and I became stuck (Just so you know I'm very new to Python). I'll show you what I mean</p>
<pre><code>joke = input("Want to hear a funny joke?\n")
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
else:
print("Awww..")
</code></pre>
<p>What I'm trying to get to happen here is python will ask you if you want to hear a joke, if you say no it will go "Awww.." and if you say yes it will ask you why did the chicken cross the road. It works when I say yes but when I say no it gives this</p>
<pre><code>Want to hear a funny joke?
no
Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\Python projects\Python Buddie.py", line 34, in <module>
if chicken in ["To get to the other side", "to get to the other side"]:
NameError: name 'chicken' is not defined
</code></pre>
<p>I have chicken defined as you can see. I feel like I'm getting an order wrong, could anyone help me?</p>
| 0 | 2016-08-11T06:16:19Z | 38,888,689 | <p>You put the else in the wrong place, that's why</p>
<p>Your else statement is follow by when the user already say yes </p>
<p>To Fix this:</p>
<pre><code>joke = input("Want to hear a funny joke?\n")
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
else:
print("Awww..")
</code></pre>
| 0 | 2016-08-11T06:22:14Z | [
"python"
] |
Certain variable not able to be defined? | 38,888,581 | <p>Just in case someone takes this down yes, I went looking for the answer before hand. So I am working on a small personal project and I became stuck (Just so you know I'm very new to Python). I'll show you what I mean</p>
<pre><code>joke = input("Want to hear a funny joke?\n")
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
else:
print("Awww..")
</code></pre>
<p>What I'm trying to get to happen here is python will ask you if you want to hear a joke, if you say no it will go "Awww.." and if you say yes it will ask you why did the chicken cross the road. It works when I say yes but when I say no it gives this</p>
<pre><code>Want to hear a funny joke?
no
Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\Python projects\Python Buddie.py", line 34, in <module>
if chicken in ["To get to the other side", "to get to the other side"]:
NameError: name 'chicken' is not defined
</code></pre>
<p>I have chicken defined as you can see. I feel like I'm getting an order wrong, could anyone help me?</p>
| 0 | 2016-08-11T06:16:19Z | 38,888,957 | <p>Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.</p>
<p>And Error is just because of wrong indentation.</p>
<pre><code>joke = input("Want to hear a funny joke?\n")
if joke in ['yes', 'ya', 'sure', 'ok', 'fine', 'yeah']:
chicken = input("Why did the chicken cross the road?\n")
if chicken in ["To get to the other side", "to get to the other side"]:
print("HAHAHAHAHAHHAHH OMG LOLZZZ FUNNY JOKE RIGHT!!!!!!!")
else:
print("Awww..")
</code></pre>
| 0 | 2016-08-11T06:37:26Z | [
"python"
] |
Configure coverage.py to use no migrations | 38,888,628 | <p>I am using <a href="https://github.com/henriquebastos/django-test-without-migrations" rel="nofollow">Django Test Without Migrations</a> to make my unit tests faster and I run the tests the following way:</p>
<pre><code>python manage.py test --nomigrations
</code></pre>
<p>It significantly improved the speed. </p>
<p>I want to do the same with PyCharm and coverage.py in order to take advantage of visuals PyCharm creates.</p>
<p>I tried to add this to .coveragerc:</p>
<pre><code>[run]
omit =
*/migrations/*
</code></pre>
<p>But it turns out that it affects only reports.</p>
<p>How can I do this?</p>
| 1 | 2016-08-11T06:19:23Z | 38,888,846 | <p>Assuming you have professional version with django support:
<a href="http://i.stack.imgur.com/sNeXG.png" rel="nofollow"><img src="http://i.stack.imgur.com/sNeXG.png" alt="enter image description here"></a></p>
<p>Click on <code>Edit configurations</code></p>
<p><a href="http://i.stack.imgur.com/Zxwa2.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zxwa2.png" alt="enter image description here"></a></p>
<p>Choose Django tests from defaults and add --nomigrations to options input.</p>
<p>If you don't have django support in Pycharm it not that different</p>
<p>Also make sure to use correct python interpreter and refer to <a href="https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-django-test.html" rel="nofollow">awesome doc page</a>.</p>
| 2 | 2016-08-11T06:31:53Z | [
"python",
"django",
"unit-testing",
"coverage.py",
"test-coverage"
] |
Print string 32 characters at a time in Python | 38,888,646 | <p>I want to be able to print on the screen a large amount of data, but I want to make sure each line has only 32 characters, the string contains binary data and I want to be able to do do 32 bytes on one line but I dont know how to do this with python loops.</p>
<pre><code>for c in string_value:
print( hex(c) )
</code></pre>
<p>The above works, but only prints one character per line as it should. How can I iterate more than 1 character per for loop. I searched online but couldnt figure out a way.</p>
<p>Any help would be greatly appreciated. Thanks in advance</p>
| 0 | 2016-08-11T06:20:16Z | 38,888,840 | <p>You can create a list of strings by iterating over the string using range from 0 to 31 and after each iteration add to the new index 31, Then just iterate the new list and print the result:</p>
<pre><code> my_string = "this is my really long string, really really, string,
really really, string, really really, string, really really long..."
for elem in [my_string[i:i+31] for i in range(0, len(my_string), 31)]:
print elem
</code></pre>
<p>You can also read about <a href="https://docs.python.org/dev/library/itertools.html#itertools.islice" rel="nofollow">isslice</a> which can supply a more elegant solution.</p>
| 4 | 2016-08-11T06:31:38Z | [
"python",
"python-2.7"
] |
Print string 32 characters at a time in Python | 38,888,646 | <p>I want to be able to print on the screen a large amount of data, but I want to make sure each line has only 32 characters, the string contains binary data and I want to be able to do do 32 bytes on one line but I dont know how to do this with python loops.</p>
<pre><code>for c in string_value:
print( hex(c) )
</code></pre>
<p>The above works, but only prints one character per line as it should. How can I iterate more than 1 character per for loop. I searched online but couldnt figure out a way.</p>
<p>Any help would be greatly appreciated. Thanks in advance</p>
| 0 | 2016-08-11T06:20:16Z | 38,888,877 | <p>Another common way of grouping elements into n-length groups:</p>
<pre><code>for custom_string in map(''.join, zip(*[iter(really_long_string)]*32)):
print hex(custom_string)
</code></pre>
| 0 | 2016-08-11T06:33:33Z | [
"python",
"python-2.7"
] |
Print string 32 characters at a time in Python | 38,888,646 | <p>I want to be able to print on the screen a large amount of data, but I want to make sure each line has only 32 characters, the string contains binary data and I want to be able to do do 32 bytes on one line but I dont know how to do this with python loops.</p>
<pre><code>for c in string_value:
print( hex(c) )
</code></pre>
<p>The above works, but only prints one character per line as it should. How can I iterate more than 1 character per for loop. I searched online but couldnt figure out a way.</p>
<p>Any help would be greatly appreciated. Thanks in advance</p>
| 0 | 2016-08-11T06:20:16Z | 38,888,954 | <p>You can lazily slice the iterable into chunks</p>
<pre><code>from itertools import takewhile, count, islice
def slice_iterable(iterable, chunk):
_it = iter(iterable)
return takewhile(bool, (tuple(islice(_it, chunk)) for _ in count(0)))
for chunk in slice_iterable(it, 32):
print(chunk)
</code></pre>
| 1 | 2016-08-11T06:37:22Z | [
"python",
"python-2.7"
] |
Print string 32 characters at a time in Python | 38,888,646 | <p>I want to be able to print on the screen a large amount of data, but I want to make sure each line has only 32 characters, the string contains binary data and I want to be able to do do 32 bytes on one line but I dont know how to do this with python loops.</p>
<pre><code>for c in string_value:
print( hex(c) )
</code></pre>
<p>The above works, but only prints one character per line as it should. How can I iterate more than 1 character per for loop. I searched online but couldnt figure out a way.</p>
<p>Any help would be greatly appreciated. Thanks in advance</p>
| 0 | 2016-08-11T06:20:16Z | 38,889,008 | <pre><code>for i in range(0, len(string_value), 32):
print(string_value[i:i+32])
</code></pre>
| 0 | 2016-08-11T06:40:01Z | [
"python",
"python-2.7"
] |
Python insert a line break in a string after character "X" | 38,888,714 | <p>What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error </p>
<pre><code>for myItem in myList.split('X'):
myString = myString.join(myItem.replace('X','X\n'))
</code></pre>
| 0 | 2016-08-11T06:23:46Z | 38,888,769 | <p><strong>Python 3.X</strong></p>
<pre><code>myString.translate({ord('X'):'X\n'})
</code></pre>
<p><code>translate()</code> allows a dict, so, you can replace more than one different character at time. </p>
<p>Why <code>translate()</code> over <code>replace()</code> ? Check <a href="http://stackoverflow.com/questions/31143290/python-str-translate-vs-str-replace">translate vs replace</a></p>
<p><strong>Python 2.7</strong></p>
<pre><code>myString.maketrans('X','X\n')
</code></pre>
| 2 | 2016-08-11T06:27:52Z | [
"python",
"list"
] |
Python insert a line break in a string after character "X" | 38,888,714 | <p>What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error </p>
<pre><code>for myItem in myList.split('X'):
myString = myString.join(myItem.replace('X','X\n'))
</code></pre>
| 0 | 2016-08-11T06:23:46Z | 38,888,789 | <p>A list has no <code>split</code> method (as the error says).</p>
<p>Assuming <code>myList</code> is a list of strings and you want to replace <code>'X'</code> with <code>'X\n'</code> in each once of them, you can use list comprehension:</p>
<pre><code>new_list = [string.replace('X', 'X\n') for string in myList]
</code></pre>
| 1 | 2016-08-11T06:28:40Z | [
"python",
"list"
] |
Python insert a line break in a string after character "X" | 38,888,714 | <p>What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error </p>
<pre><code>for myItem in myList.split('X'):
myString = myString.join(myItem.replace('X','X\n'))
</code></pre>
| 0 | 2016-08-11T06:23:46Z | 38,888,795 | <pre><code>myString = '1X2X3X'
print (myString.replace ('X', 'X\n'))
</code></pre>
| 2 | 2016-08-11T06:29:08Z | [
"python",
"list"
] |
Python insert a line break in a string after character "X" | 38,888,714 | <p>What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error </p>
<pre><code>for myItem in myList.split('X'):
myString = myString.join(myItem.replace('X','X\n'))
</code></pre>
| 0 | 2016-08-11T06:23:46Z | 38,888,814 | <p>You can simply replace X by "X\n"</p>
<pre><code>myString.replace("X","X\n")
</code></pre>
| 1 | 2016-08-11T06:30:07Z | [
"python",
"list"
] |
Python insert a line break in a string after character "X" | 38,888,714 | <p>What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error </p>
<pre><code>for myItem in myList.split('X'):
myString = myString.join(myItem.replace('X','X\n'))
</code></pre>
| 0 | 2016-08-11T06:23:46Z | 38,890,258 | <p>Based on your question details, it sounds like the most suitable is str.replace, as suggested by @DeepSpace. @levi's answer is also applicable, but could be a bit of a too big cannon to use.
I add to those an even more powerful tool - regex, which is slower and harder to grasp, but in case this is not really "X" -> "X\n" substitution you actually try to do, but something more complex, you should consider:</p>
<pre><code>import re
result_string = re.sub("X", "X\n", original_string)
</code></pre>
<p>For more details: <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">https://docs.python.org/2/library/re.html#re.sub</a></p>
| 0 | 2016-08-11T07:44:03Z | [
"python",
"list"
] |
Better request.GET for multiple form fields? | 38,888,858 | <p>Right now I have this where I have 3 fields:</p>
<pre><code><form action="/calc/" method="get">
<input type="text" name="pv">
<input type="text" name="n">
<input type="text" name="r">
<input type="submit" value="Search">
</form>
</code></pre>
<p>And I'm defining it like so:</p>
<pre><code>def calc(request):
if 'pv' in request.GET and 'n' in request.GET and 'r' in request.GET:
pv = request.GET['pv']
n = request.GET['n']
r = request.GET['r']
return render(request, 'main/index.html',
{
'pv': pv,
'n': n,
'r': r,
})
return render(request, 'main/index.html')
</code></pre>
<p>Is there a better/shorter way to write the if condition statement? Instead of writing if 'pv' and 'n' and 'r', etc...?</p>
| 0 | 2016-08-11T06:32:40Z | 38,888,974 | <p>You could use <code>all</code></p>
<pre><code>if all(x in request.GET for x in ['pv', 'n', 'r']):
</code></pre>
<p>But then is it really likely that someone will call this url without all 3? it may be worth just checking one.</p>
<p>You could just use the <code>.get</code> dictionary lookup and provide a default where it doesn't exist, <code>.get</code> will return None by default</p>
<pre><code>request.GET.get('pv')
request.GET.get('pv', 'default')
</code></pre>
<p>Also, instead of referencing them directly, you should just make a form and let django handle all of this for you.</p>
| 1 | 2016-08-11T06:38:08Z | [
"python",
"django"
] |
Better request.GET for multiple form fields? | 38,888,858 | <p>Right now I have this where I have 3 fields:</p>
<pre><code><form action="/calc/" method="get">
<input type="text" name="pv">
<input type="text" name="n">
<input type="text" name="r">
<input type="submit" value="Search">
</form>
</code></pre>
<p>And I'm defining it like so:</p>
<pre><code>def calc(request):
if 'pv' in request.GET and 'n' in request.GET and 'r' in request.GET:
pv = request.GET['pv']
n = request.GET['n']
r = request.GET['r']
return render(request, 'main/index.html',
{
'pv': pv,
'n': n,
'r': r,
})
return render(request, 'main/index.html')
</code></pre>
<p>Is there a better/shorter way to write the if condition statement? Instead of writing if 'pv' and 'n' and 'r', etc...?</p>
| 0 | 2016-08-11T06:32:40Z | 38,891,247 | <p>I would suggest to use a Django Form class. <a href="https://docs.djangoproject.com/en/1.10/topics/forms/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/forms/</a></p>
<pre><code>from django import forms
class CalcForm(forms.Form):
pv = forms.CharField(max_length=100)
n = forms.CharField(max_length=100)
r = forms.CharField(max_length=100)
</code></pre>
<p>and the create an instance of this CalcForm in your view to render in template. </p>
<pre><code>def calc(request):
form = CalcForm(request.GET)
if form.is_valid():
# all fields are valid
data = form.cleaned_data
</code></pre>
<p>The advantage here is that Django does a validation for you. If your function hits the database, Django also prevents SQL injections.</p>
| 1 | 2016-08-11T08:34:38Z | [
"python",
"django"
] |
String, Int Differentiation and Looping in Python | 38,888,870 | <p>How to complete my program which repeatedly reads numbers until the user enters
âdoneâ. Once âdoneâ is entered, print out the total, count, and average of
the numbers. If the user enters anything other than a number, detect their mistake
using try and except and print an error message and skip to the next number.</p>
<pre><code>count = 0
total = 0
while True:
x = raw_input('Enter number')
x=int(x)
total = total + x
count = count + 1
average = total / count
print total, count, average
</code></pre>
| -5 | 2016-08-11T06:33:19Z | 39,360,012 | <p>The following code should be what you want.</p>
<pre><code>count = 0
total = 0
while True:
x = raw_input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print total, count, average
</code></pre>
<p>or in Python 3</p>
<pre><code>count = 0
total = 0
while True:
x = input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print(total, count, average)
</code></pre>
| 0 | 2016-09-07T01:30:08Z | [
"python"
] |
Python cross-file search with regexp | 38,888,925 | <p>I have 2 files, and I want to get all lines from file2(fsearch) that contain any given line from file1(forig)<br>
I wrote a simple python script that looks like this:</p>
<pre><code>def search_string(w, file):
global matches
reg = re.compile((r'(^|^.*\|)' + w.strip("\r\n") + r'(\t|\|).*$'), re.M)
match = reg.findall(file)
matches.extend(match)
fsearch_text = fsearch.read()
for fword in forig:
search_string(fword, fsearch_text)
</code></pre>
<p>There are about 100,000 lines in file1, and about 200,000 lines in file2, so my script takes about 6 hours to complete.<br>
Is there a better algorithm to achieve the same goal in less time?</p>
<p>Edit:
I should have provided example for why I need regexp:<br>
I am searching a list of words in file1 and trying to match them to translations from file2. If I do not use regexp to limit possible matches, I also match translations for words that only contain the word I search as part of itself, example:<br>
Word I search: 浸ã<br>
Matched word: ãæµ¸ã|御浸ã|御ããã &n boiled greens in bonito-flavoured soy sauce (vegetable side dish)<br>
So I have to limit start of match by either ^ or |, and end of match by \t or |, but capture the whole line</p>
| 1 | 2016-08-11T06:35:45Z | 38,889,718 | <p>Assuming you can have both files in memory. You can read them and sort them.</p>
<p>After that, you can compare linearly the lines.</p>
<pre><code>f1 = open('e:\\temp\\file1.txt')
lines1 = sorted([line for line in f1])
f2 = open('e:\\temp\\file2.txt')
lines2 = sorted([line for line in f2])
i1 = 0
i2 = 0
matchCount = 0
while (i1 < len(lines1) and i2 < len(lines2)):
line1 = lines1[i1]
line2 = lines2[i2]
if line1 < line2:
i1 += 1
elif line1 > line2:
i2 += 1
else:
matchCount += 1
i2 += 1
print('matchCount')
print(matchCount)
</code></pre>
| 0 | 2016-08-11T07:16:57Z | [
"python",
"regex",
"algorithm"
] |
Python cross-file search with regexp | 38,888,925 | <p>I have 2 files, and I want to get all lines from file2(fsearch) that contain any given line from file1(forig)<br>
I wrote a simple python script that looks like this:</p>
<pre><code>def search_string(w, file):
global matches
reg = re.compile((r'(^|^.*\|)' + w.strip("\r\n") + r'(\t|\|).*$'), re.M)
match = reg.findall(file)
matches.extend(match)
fsearch_text = fsearch.read()
for fword in forig:
search_string(fword, fsearch_text)
</code></pre>
<p>There are about 100,000 lines in file1, and about 200,000 lines in file2, so my script takes about 6 hours to complete.<br>
Is there a better algorithm to achieve the same goal in less time?</p>
<p>Edit:
I should have provided example for why I need regexp:<br>
I am searching a list of words in file1 and trying to match them to translations from file2. If I do not use regexp to limit possible matches, I also match translations for words that only contain the word I search as part of itself, example:<br>
Word I search: 浸ã<br>
Matched word: ãæµ¸ã|御浸ã|御ããã &n boiled greens in bonito-flavoured soy sauce (vegetable side dish)<br>
So I have to limit start of match by either ^ or |, and end of match by \t or |, but capture the whole line</p>
| 1 | 2016-08-11T06:35:45Z | 38,891,838 | <p>If it is possible for you to use UNIX/GNU/Linux commands you could do this:</p>
<pre class="lang-bash prettyprint-override"><code># fill example files
for i in {1..100000}; do echo $RANDOM; done > file1.txt
for i in {1..200000}; do echo $RANDOM; done > file2.txt
# get every line of file2.txt which is also in file1.txt
# for static string matching:
grep -F -x -f file1.txt file2.txt
# for regex matching use (regular expressions in file1.txt):
grep -f file1.txt file2.txt
</code></pre>
<p><code>grep</code> is optimized for such operations so the above call takes less than a second (have a look at <a href="http://lists.freebsd.org/pipermail/freebsd-current/2010-August/019310.html" rel="nofollow">this</a>).</p>
| 0 | 2016-08-11T09:02:23Z | [
"python",
"regex",
"algorithm"
] |
django how to make python script executed from bash write stdout to file? | 38,889,156 | <p>I am using Django and I am getting a ton of errors and deprecation warning when I run tests and unsilence the warnings with the command...</p>
<pre><code>python -Wall manage.py test
</code></pre>
<p>In regular bash I would usually do soemthing like this...</p>
<pre><code>command > log.log
</code></pre>
<p>but that is not working, or it is only writing a very small fraction of the output to a file. I could write a python script, but the output is likely soming from all over the Django frameword and I would really rather just get this output into a file.</p>
<p>I have also tried the <code>-u</code> option on the python comand and that did not work either</p>
| 1 | 2016-08-11T06:48:34Z | 38,889,238 | <p>If you're seeing errors written to stdout and stderr both, then you'll want to redirect both of them:</p>
<pre><code> python -Wall manage.py test >log.log 2>&1
</code></pre>
<p>There's (much) more here about shell redirection: <a href="http://stackoverflow.com/questions/818255/in-the-shell-what-does-21-mean">In the shell, what does " 2>&1 " mean?</a></p>
| 1 | 2016-08-11T06:52:44Z | [
"python",
"django",
"bash"
] |
recieving sqs message body without double quotes | 38,889,170 | <p>Hi I am using boto3 to send and receive sqs message .
I am sending below sqs message .
{"userid":1234,"ml_algorithm_type":1,"file_format":1,"file_path":"leu.gz"}</p>
<p>but while receiving the messages ,I receive below string .
{userid:1234,ml_algorithm_type:1,file_format:1,file_path:leu.gz}</p>
<p>I want to receive exact message what i have sent .</p>
| 0 | 2016-08-11T06:49:14Z | 38,936,632 | <p>The following test function verifies that in Amazon Simple Queuing Service (SQS), we can receive a message with JSON double quotes.</p>
<p>Note that in the code, it looks like the dictionary has single quotes on the keys and values. This is fine, as the <code>json.dumps()</code> function converts all keys and values to use the JSON standard double quotes.</p>
<h1>test_sqs.py</h1>
<pre><code>import json
import boto3
from moto import mock_sqs
@mock_sqs
def test_sqs():
sqs = boto3.resource('sqs', 'us-east-1')
queue = sqs.create_queue(QueueName='votes')
queue.send_message(MessageBody=json.dumps({'beer': 'tasty'}))
messages = queue.receive_messages()
assert len(messages)
assert messages[0].body == '{"beer": "tasty"}' # <- double quotes
</code></pre>
| 0 | 2016-08-13T20:17:27Z | [
"python",
"json",
"amazon-sqs",
"boto3"
] |
Is it possible to do object iteration without a separate iterator object? | 38,889,201 | <p>I am writing something similar to an array, but with some tweaks. Of course, it should be iterable. But I do not really want to make another object as an iterator, and 'for I in myObject.generator()' seems too clunky for me. Is there any way to make a generator function that would work for 'for I in myObject'?</p>
| 1 | 2016-08-11T06:50:35Z | 38,889,226 | <p>Just use a generator function for the <a href="https://docs.python.org/2/reference/datamodel.html#object.__iter__"><code>__iter__</code> method</a>:</p>
<pre><code>def __iter__(self):
for value in self._values:
yield value
</code></pre>
<p>This produces a new generator iterator object each time <a href="https://docs.python.org/2/library/functions.html#iter"><code>iter()</code></a> is called on the object (which is what <code>for</code> does <em>for you</em> when you use your object in a loop).</p>
| 7 | 2016-08-11T06:51:58Z | [
"python",
"iterator"
] |
Understanding the code python | 38,889,231 | <p>I am working on dynamically creating tables on the go. Came across the following code, please help me understand it.</p>
<p>Original question is posted here
<a href="http://stackoverflow.com/questions/2574105/sqlalchemy-dynamic-mapping/2575016#2575016">sqlalchemy dynamic mapping</a></p>
<p>In the following python code in SQLAlchemy, I can not understand the use of '*'
before (Column.............wordColumns))</p>
<pre><code>t = Table('words', metadata, Column('id', Integer, primary_key=True),
*(Column(wordCol, Unicode(255)) for wordCol in wordColumns))
</code></pre>
| 0 | 2016-08-11T06:52:16Z | 38,890,297 | <p>From the <a href="http://docs.sqlalchemy.org/en/latest/core/metadata.html" rel="nofollow">docs</a> there is an example:</p>
<pre><code>employees = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
Column('employee_name', String(60), nullable=False),
Column('employee_dept', Integer,))
</code></pre>
<p>which simplifies to</p>
<pre><code>t = Table(name, metadata, *args)
</code></pre>
<p>where *args is an arbitary number of arguments, so in this example, its adding a column for each <code>wordCol</code> in <code>wordColumns</code> after adding an id column.</p>
| 0 | 2016-08-11T07:46:17Z | [
"python",
"sqlalchemy"
] |
getent hosts to take initial 3 up digit+hostname unix | 38,889,291 | <p>I need first 3 octets of IP address and the myhosts name, while I am trying to make via cut command but unable to join the host name</p>
<pre><code>$ getent hosts myhosts
172.10.2.32 myhosts.lab.com
</code></pre>
<p>anything with awk, sed, cut, python will be okay</p>
<pre><code>$ getent hosts myhosts | cut -d "." -f1,2,3
172.10.2
</code></pre>
<p>The output should be:</p>
<pre><code>172.10.2 myhosts.lab.com
</code></pre>
| 1 | 2016-08-11T06:55:27Z | 38,889,406 | <p>On the first field, remove everything from the last dot:</p>
<pre><code>$ awk '{sub(/\.[^.]*$/,"",$1); print $1, $2}' <<< "172.10.2.32 myhosts.lab.com"
172.10.2 myhosts.lab.com
</code></pre>
<p>We have two fields: IP and hostname. The hostname is to be returned without any change, whereas for the IP we want to remove the last block.</p>
<p>To tune the first field <code>$1</code> we use <a href="https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html" rel="nofollow"><code>sub()</code></a>. This perform replacements using the syntax <code>sub(regexp, replacement [, target])</code>. To remove everything from the last dot, we replace it with the empty string.</p>
<p>And how do we match everything from the last dot? Using <code>/\.[^.]*$/</code>, which means: match a dot and then any kind of characters but a dot until the end of the field.</p>
| 2 | 2016-08-11T07:01:19Z | [
"python",
"awk",
"sed",
"cut"
] |
getent hosts to take initial 3 up digit+hostname unix | 38,889,291 | <p>I need first 3 octets of IP address and the myhosts name, while I am trying to make via cut command but unable to join the host name</p>
<pre><code>$ getent hosts myhosts
172.10.2.32 myhosts.lab.com
</code></pre>
<p>anything with awk, sed, cut, python will be okay</p>
<pre><code>$ getent hosts myhosts | cut -d "." -f1,2,3
172.10.2
</code></pre>
<p>The output should be:</p>
<pre><code>172.10.2 myhosts.lab.com
</code></pre>
| 1 | 2016-08-11T06:55:27Z | 38,899,248 | <pre><code>$ sed -E 's/\.[0-9]+ +/ /' <<< '172.10.2.32 myhosts.lab.com'
172.10.2 myhosts.lab.com
</code></pre>
<p>or if the white space in your command output can contain tabs or other invisible chars:</p>
<pre><code>$ sed -E 's/\.[0-9]+[[:blank:]]+/ /' <<< '172.10.2.32 myhosts.lab.com'
172.10.2 myhosts.lab.com
</code></pre>
| 1 | 2016-08-11T14:31:17Z | [
"python",
"awk",
"sed",
"cut"
] |
Python Flask- using Iframe in my template in my project | 38,889,478 | <p>I stuck at here,
I am doing a project in Banana Pi board and installed Debian related OS
Using Python 2.7.
I had four html pages they are:</p>
<ul>
<li>main.html</li>
<li>motor1.html</li>
<li>motor2.html</li>
<li>sensor1.html</li>
<li>sensor2.html</li>
</ul>
<hr>
<p>I am using Flask application to run the main.html which contains all the other pages in iframe's in main.html</p>
<p>my code for app.py is</p>
<pre><code> from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('main.html')
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>main.html is as follows:</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<title>Pi Board</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script>
function myFunc(){
setTimeout("location.reload(true);",60000);
}
myFunc();
</script>
<style>
body {background-color : lightgray;}
#frame1,#frame2{width: 300px; height : 200px; float: absolute;}
</style>
</head>
<body >
<header><h2>XYZ Automation</h2></header>
<iframe id="frame1" src="motor1.html"></iframe>
<iframe id="frame1" src="sensor1.html"></iframe><br>
<iframe id="frame2" src="motor2.html"></iframe>
<iframe id="frame2" src="sensor2.html"></iframe>
</body>
</html>
</code></pre>
<p>and I kept all the files in folders as follows:
project(MainFolder):->
templates
app.py
templates(Subfolder):->
main.html
, motor1.html
, motor2.html
, sensor1.html
, sensor2.html
, script.js.
, style(folder)
style(folder):->
styles.css,</p>
<p>Here are the images while I am running the code:
<a href="http://i.stack.imgur.com/iVbZI.png" rel="nofollow">in commandline</a>
<a href="http://i.stack.imgur.com/jZBu9.png" rel="nofollow">in browser</a></p>
<p>PS: I started working with Flask for the first time and I had no knowledge in these server things.. and this is a project given by my sir.. please help me.</p>
<p>Regards,</p>
<p>Krishna.</p>
| -1 | 2016-08-11T07:05:01Z | 38,892,602 | <p>You need to create app.route entries for the pages motor1, motor2, sensor1 and sensor2 in app.py file like this:</p>
<pre><code>@app.route('motor1')
def motor1():
return render_template('motor1.html')
@app.route('motor2')
def motor2():
return render_template('motor2.html')
@app.route('sensor1')
def sensor1():
return render_template('sensor1.html')
@app.route('sensor2')
def sensor2():
return render_template('sensor2.html')
</code></pre>
<p>Iframe sources in main.html don't need .html endings:</p>
<pre><code><iframe id="frame1" src="motor1"></iframe>
<iframe id="frame2" src="sensor1"></iframe>
<iframe id="frame3" src="motor2"></iframe>
<iframe id="frame4" src="sensor2"></iframe>
</code></pre>
| 0 | 2016-08-11T09:37:10Z | [
"jquery",
"python",
"html",
"iframe",
"flask"
] |
How to remove %07 from url in Python/Django | 38,889,542 | <p>This is the url I build in the code logic.</p>
<pre><code>redirect_url = "%s?first_variable=%s&second_variable=%s"%(response_url,first_value,second_value)
</code></pre>
<p>The response URL is built using the following code</p>
<pre><code>response_url = request.build_absolute_uri(reverse('workshop:ccavenue_payment_response'))
</code></pre>
<p>output of this response_url is
<a href="http://localhost:8000/workshop/ccavenue/payment-response/" rel="nofollow">http://localhost:8000/workshop/ccavenue/payment-response/</a></p>
<p>This is the output URL(redirect url)</p>
<p><a href="http://localhost:8000/workshop/ccavenue/payment-response/%07%07%07%07%07%07%07?first_variable=xxxxxxxxxxxxxxxxxxxxxxxxxx&second_variable=encrypted_data" rel="nofollow">http://localhost:8000/workshop/ccavenue/payment-response/%07%07%07%07%07%07%07?first_variable=xxxxxxxxxxxxxxxxxxxxxxxxxx&second_variable=encrypted_data</a></p>
<p>How can I remove %07 from my url ?
Thank You in advance.</p>
| 0 | 2016-08-11T07:08:52Z | 38,889,796 | <p>Is that what you are looking after?</p>
<pre><code>payload = {'first_variable': first_value, 'second_variable': second_value}
r = requests.get(response_url, params=payload)
</code></pre>
<p>try with <code>print(r.url)</code></p>
| 0 | 2016-08-11T07:20:54Z | [
"python",
"django",
"url"
] |
Groupby() and aggregation in pandas | 38,889,558 | <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>In [149]: df
Out[149]:
AMOUNT DATE ORDER_ID UID
0 1001 2014-01-02 101 1
1 1002 2014-01-03 102 3
2 1003 2014-01-04 103 4
3 1004 2014-01-05 104 5
4 1005 2014-01-09 105 5
5 1006 2014-01-07 106 7
6 1007 2014-01-08 107 8
7 1008 2014-01-09 108 5
8 1009 2014-01-10 109 10
9 1500 2014-01-09 110 5
</code></pre>
<p>and I want to truncate all rows that correspond to the same UID and DATE to one row and use the sum of the values in the <code>AMOUNT</code> column for the one row that remains.</p>
<p>In short, the desired output would be:</p>
<blockquote>
<pre><code>In [149]: df
Out[149]:
AMOUNT DATE ORDER_ID UID
0 1001 2014-01-02 101 1
1 1002 2014-01-03 102 3
2 1003 2014-01-04 103 4
3 1004 2014-01-05 104 5
4 3513 2014-01-09 105 5 ## <- Rows that previously had index [7,9,4] are now truncated to this one row and the AMOUNT is the sum of of the AMOUNT values of those three rows
5 1006 2014-01-07 106 7
6 1007 2014-01-08 107 8
8 1009 2014-01-10 109 10
</code></pre>
</blockquote>
<p><strong>In essence, what I want to do is 'aggregate' all rows that correspond to the same user UID and DATE to one row and leave all other rows intact.</strong></p>
<p>What I've tried so far is this:</p>
<pre><code>In [154]: df.groupby(['UID','DATE'])['AMOUNT'].sum()
Out[154]:
UID DATE
1 2014-01-02 1001
3 2014-01-03 1002
4 2014-01-04 1003
5 2014-01-05 1004
2014-01-09 3513
7 2014-01-07 1006
8 2014-01-08 1007
10 2014-01-10 1009
Name: AMOUNT, dtype: int64
</code></pre>
<p><strong><em>but</em></strong> I'm not sure where to start in order to either go back to original <code>df</code> and remove the 'extra' rows nor how to assign the new sum value of <code>AMOUNT</code> to the one remaining row.</p>
<p>Any help is very appreciated!</p>
| 1 | 2016-08-11T07:09:41Z | 38,889,667 | <p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>aggregate</code></a> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.sum.html" rel="nofollow"><code>sum</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>first</code></a>:</p>
<pre><code>print (df.groupby(['UID','DATE'], as_index=False).agg({'AMOUNT': sum, 'ORDER_ID': 'first'}))
UID DATE AMOUNT ORDER_ID
0 1 2014-01-02 1001 101
1 3 2014-01-03 1002 102
2 4 2014-01-04 1003 103
3 5 2014-01-05 1004 104
4 5 2014-01-09 3513 105
5 7 2014-01-07 1006 106
6 8 2014-01-08 1007 107
7 10 2014-01-10 1009 109
</code></pre>
| 1 | 2016-08-11T07:14:44Z | [
"python",
"pandas",
"dataframe",
"group-by",
"aggregate"
] |
Groupby() and aggregation in pandas | 38,889,558 | <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>In [149]: df
Out[149]:
AMOUNT DATE ORDER_ID UID
0 1001 2014-01-02 101 1
1 1002 2014-01-03 102 3
2 1003 2014-01-04 103 4
3 1004 2014-01-05 104 5
4 1005 2014-01-09 105 5
5 1006 2014-01-07 106 7
6 1007 2014-01-08 107 8
7 1008 2014-01-09 108 5
8 1009 2014-01-10 109 10
9 1500 2014-01-09 110 5
</code></pre>
<p>and I want to truncate all rows that correspond to the same UID and DATE to one row and use the sum of the values in the <code>AMOUNT</code> column for the one row that remains.</p>
<p>In short, the desired output would be:</p>
<blockquote>
<pre><code>In [149]: df
Out[149]:
AMOUNT DATE ORDER_ID UID
0 1001 2014-01-02 101 1
1 1002 2014-01-03 102 3
2 1003 2014-01-04 103 4
3 1004 2014-01-05 104 5
4 3513 2014-01-09 105 5 ## <- Rows that previously had index [7,9,4] are now truncated to this one row and the AMOUNT is the sum of of the AMOUNT values of those three rows
5 1006 2014-01-07 106 7
6 1007 2014-01-08 107 8
8 1009 2014-01-10 109 10
</code></pre>
</blockquote>
<p><strong>In essence, what I want to do is 'aggregate' all rows that correspond to the same user UID and DATE to one row and leave all other rows intact.</strong></p>
<p>What I've tried so far is this:</p>
<pre><code>In [154]: df.groupby(['UID','DATE'])['AMOUNT'].sum()
Out[154]:
UID DATE
1 2014-01-02 1001
3 2014-01-03 1002
4 2014-01-04 1003
5 2014-01-05 1004
2014-01-09 3513
7 2014-01-07 1006
8 2014-01-08 1007
10 2014-01-10 1009
Name: AMOUNT, dtype: int64
</code></pre>
<p><strong><em>but</em></strong> I'm not sure where to start in order to either go back to original <code>df</code> and remove the 'extra' rows nor how to assign the new sum value of <code>AMOUNT</code> to the one remaining row.</p>
<p>Any help is very appreciated!</p>
| 1 | 2016-08-11T07:09:41Z | 38,889,768 | <pre><code>df['AMOUNT'] = df.groupby(['UID','DATE'])['AMOUNT'].transform('sum')
df = df.drop_duplicates(['UID', 'DATE'])
df
Out[21]:
AMOUNT DATE ORDER_ID UID
0 1001 2014-01-02 101 1
1 1002 2014-01-03 102 3
2 1003 2014-01-04 103 4
3 1004 2014-01-05 104 5
4 3513 2014-01-09 105 5
5 1006 2014-01-07 106 7
6 1007 2014-01-08 107 8
8 1009 2014-01-10 109 10
</code></pre>
| 2 | 2016-08-11T07:19:00Z | [
"python",
"pandas",
"dataframe",
"group-by",
"aggregate"
] |
Groupby() and aggregation in pandas | 38,889,558 | <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>In [149]: df
Out[149]:
AMOUNT DATE ORDER_ID UID
0 1001 2014-01-02 101 1
1 1002 2014-01-03 102 3
2 1003 2014-01-04 103 4
3 1004 2014-01-05 104 5
4 1005 2014-01-09 105 5
5 1006 2014-01-07 106 7
6 1007 2014-01-08 107 8
7 1008 2014-01-09 108 5
8 1009 2014-01-10 109 10
9 1500 2014-01-09 110 5
</code></pre>
<p>and I want to truncate all rows that correspond to the same UID and DATE to one row and use the sum of the values in the <code>AMOUNT</code> column for the one row that remains.</p>
<p>In short, the desired output would be:</p>
<blockquote>
<pre><code>In [149]: df
Out[149]:
AMOUNT DATE ORDER_ID UID
0 1001 2014-01-02 101 1
1 1002 2014-01-03 102 3
2 1003 2014-01-04 103 4
3 1004 2014-01-05 104 5
4 3513 2014-01-09 105 5 ## <- Rows that previously had index [7,9,4] are now truncated to this one row and the AMOUNT is the sum of of the AMOUNT values of those three rows
5 1006 2014-01-07 106 7
6 1007 2014-01-08 107 8
8 1009 2014-01-10 109 10
</code></pre>
</blockquote>
<p><strong>In essence, what I want to do is 'aggregate' all rows that correspond to the same user UID and DATE to one row and leave all other rows intact.</strong></p>
<p>What I've tried so far is this:</p>
<pre><code>In [154]: df.groupby(['UID','DATE'])['AMOUNT'].sum()
Out[154]:
UID DATE
1 2014-01-02 1001
3 2014-01-03 1002
4 2014-01-04 1003
5 2014-01-05 1004
2014-01-09 3513
7 2014-01-07 1006
8 2014-01-08 1007
10 2014-01-10 1009
Name: AMOUNT, dtype: int64
</code></pre>
<p><strong><em>but</em></strong> I'm not sure where to start in order to either go back to original <code>df</code> and remove the 'extra' rows nor how to assign the new sum value of <code>AMOUNT</code> to the one remaining row.</p>
<p>Any help is very appreciated!</p>
| 1 | 2016-08-11T07:09:41Z | 38,889,863 | <p>Alternatively you can use <code>aggregate</code>:</p>
<pre><code>In [10]: df.groupby(['UID', 'DATE']).agg({'AMOUNT': np.sum, 'ORDER_ID': lambda x: x.iloc[0]}).reset_index()
Out[10]:
UID DATE AMOUNT ORDER_ID
0 1 2014-01-02 1001 101
1 3 2014-01-03 1002 102
2 4 2014-01-04 1003 103
3 5 2014-01-05 1004 104
4 5 2014-01-09 3513 105
5 7 2014-01-07 1006 106
6 8 2014-01-08 1007 107
7 10 2014-01-10 1009 109
</code></pre>
<p>Assuming you only want the "first" <code>ORDER_ID</code> from your expected output, ie. <code>lambda x: x.iloc[0]</code></p>
| 1 | 2016-08-11T07:23:25Z | [
"python",
"pandas",
"dataframe",
"group-by",
"aggregate"
] |
Error: wxWindow::SetLayoutDirection(): layout direction must be set after window creation | 38,889,612 | <p>I have a function (WxPython 2.8.12 & Python 2.7) which creates combos in a recursion:</p>
<pre><code> self.resultsCtrl = wx.combo.ComboCtrl(self,-1)
self.results = ListBoxCombo(self.resultsCtrl)
</code></pre>
<p>It creates as many as needed. </p>
<pre><code>class ListBoxCombo(wx.ListBox, wx.combo.ComboPopup):
def __init__(self, comboCtrl, choices=None, readonly=True):
self.PostCreate(wx.PreListBox())
wx.combo.ComboPopup.__init__(self)
comboCtrl.SetPopupControl(self)
self.SetLayoutDirection(comboCtrl.GetLayoutDirection())
</code></pre>
<p>Sometimes I get this error:</p>
<blockquote>
<p>wx._core.PyAssertionError: C++ assertion "hwnd" failed at
....\src\msw\window.cpp(1084) in wxWindow::SetLayoutDirection():
layout direction must be set after window creation</p>
</blockquote>
<p>This happens only on Windows.
I don't understand why it thinks that the layout is set before the window and why sometimes it works and sometimes not.
Please help.</p>
| 0 | 2016-08-11T07:12:05Z | 38,911,069 | <p>When you use 2-phase create (like with <code>wx.PreListBox</code> above) there is no UI object yet, just the C++ part of the object. In MSW Windows terms, there is no window handle yet, a.k.a HWND. The UI object is not created until the class' <code>Create</code> method is called. So when there is no native UI object, methods which need to operate on it will fail.</p>
<p>The <code>PostCreate</code> method is a Python-only helper that just adjusts some things in the Python class, it does not call the Create method either. You should delay calling anything that deals directly with the native widget until after you call <code>wx.ListBox.Create</code>.</p>
| 0 | 2016-08-12T06:10:55Z | [
"python",
"wxpython"
] |
400 Bad Request With urllib2 for POST | 38,889,691 | <p>I am struggling from 2 days with a post request to be made only using urllib & urllib2. I have limitations in using curl or requests library, as the machine I would need to deploy my code doesn't support any of these.</p>
<p>The post call would be accompanied with a Header and json Body. I am able to make any get call, but POST with Data & Header throws 400 bad requests. Tried and applied all the options available in google/stackoverflow, but nothing solved!</p>
<p>Below is the sample code:--</p>
<pre><code>import urllib
import urllib2
url = 'https://1.2.3.4/rest/v1/path'
headers = {'X-Auth-Token': '123456789sksksksk111',
'Content-Type': 'application/json'}
body = {'Action': 'myaction',
'PressType': 'Format1', 'Target': '/abc/def'}
data = urllib.urlencode(body)
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request, data)
</code></pre>
<p>And on setting debug handler, below is the format of the request that can be traced:--</p>
<pre><code>send: 'POST /rest/v1/path HTTP/1.1\r\nAccept-Encoding: identity\r\nContent-Length: 52\r\nHost: 1.2.3.4\r\nUser-Agent: Python-urllib/2.7\r\nConnection: close\r\nX-Auth-Token: 123456789sksksksk111\r\nContent-Type: application/json\r\n\r\nAction=myaction&PressType=Format1&Target=%2Fabc%2Fdef'
reply: 'HTTP/1.1 400 Bad Request\r\n'
</code></pre>
<p>Please note, the same post request works perfectly fine with any REST client and with Requests library. In the debug handler output, if we see, the json structure is Content-Type: <code>application/json\r\n\r\nAction=myaction&PressType=Format1&Target=%2Fabc%2Fdef</code>, can that be a problem!</p>
| 1 | 2016-08-11T07:16:04Z | 38,891,372 | <p>You can dump the json instead of encoding it. I was facing the same and got solved with it!</p>
<p>Remove <code>data = urllib.urlencode(body)</code> and use <code>urllib2.urlopen(req, json.dumps(data))</code></p>
<p>That should solve.</p>
| 1 | 2016-08-11T08:40:26Z | [
"python",
"rest",
"http-post",
"urllib2",
"urllib"
] |
How to plot percentage of points in each "cell" of pyplot.hist2d? | 38,889,884 | <p>I want each "cell" of the histogram to have a number representing the percentage of total points in that "cell" instead of colors. Is there any way other than programmatically generating the matrix?
<a href="http://i.stack.imgur.com/BnyDH.png" rel="nofollow">2D histogram of my data</a></p>
<p>On <a href="http://stackoverflow.com/users/5422525/m-thttp://">M.T</a> 's suggestion, I think seaborn.heatmap() asks for a 2D data array. But I have two 1D arrays (say height and weight and each data point will be a person with (height, weight) value. Code is here:) and the array values have no particular order. Sample code here:</p>
<pre><code>plt.hist2d(height, weight, (20, 50), range=np.array([(0, 200), (0, 500)]), cmap=plt.cm.Paired)
plt.colorbar()
plt.show()
</code></pre>
| 2 | 2016-08-11T07:24:30Z | 38,896,660 | <p>You could use text and loop through the output to the normed <code>hist2d</code>, as follows,</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
height = [102, 99, 153, 98, 142, 198, 99]
weight = [201, 192, 295, 181, 315, 311, 181]
counts, xedges, yedges, Image = plt.hist2d(height, weight, (20, 50),
range=np.array([(0, 200), (0, 500)]),
cmap=plt.cm.Paired, normed=True)
dx = xedges[2]-xedges[1]
dy = yedges[2]-yedges[1]
for i in range(xedges.size-1):
for j in range(yedges.size-1):
xb = xedges[i] + 0.25*dx
yb = yedges[j] + 0.25*dy
plt.text(xb, yb, str(np.round(100.*counts[i,j],2)), fontsize=6 )
plt.show()
</code></pre>
<p>which gives,
<a href="http://i.stack.imgur.com/IBuck.png" rel="nofollow"><img src="http://i.stack.imgur.com/IBuck.png" alt="enter image description here"></a></p>
| 1 | 2016-08-11T12:38:58Z | [
"python",
"matplotlib",
"histogram"
] |
Change string according to csv file | 38,890,064 | <p>I have to open several websites to check something. The only difference between the links to every page is an id which I have stored in a CSV file.
I want to iterate through the CSV file and replace the id for every website.</p>
<p>I want to do it with the replace statement and change the xxx in the link. But it does´nt change the id and tries to open the link with the xxx several times. </p>
<pre><code>import webbrowser
import csv
link = "https://website.com/de/tour/xxx/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print(row)
link.replace("xxx", str(row))
webbrowser.open(link)
print(link)
link = "https://website.com/de/tour/xxx/geometrie.html"
</code></pre>
| 1 | 2016-08-11T07:33:38Z | 38,890,140 | <p>the replace method of a string returns a new string and doesn't modify the old one in place so you have to catch the new string in another variable or re-use your link variable</p>
<pre><code>link = link.replace("xxx", str(row))
</code></pre>
<p>The reason for this, is that strings are immutable (you can't modify them after creation)</p>
<pre><code>>>> a = 'hello world'
>>> a.replace('hello', 'hi')
'hi world'
>>> a # a is still hello world
'hello world'
>>> a = a.replace('hello', 'hi')
>>> a
'hi world'
>>>
</code></pre>
| 0 | 2016-08-11T07:37:57Z | [
"python",
"csv",
"replace"
] |
Change string according to csv file | 38,890,064 | <p>I have to open several websites to check something. The only difference between the links to every page is an id which I have stored in a CSV file.
I want to iterate through the CSV file and replace the id for every website.</p>
<p>I want to do it with the replace statement and change the xxx in the link. But it does´nt change the id and tries to open the link with the xxx several times. </p>
<pre><code>import webbrowser
import csv
link = "https://website.com/de/tour/xxx/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print(row)
link.replace("xxx", str(row))
webbrowser.open(link)
print(link)
link = "https://website.com/de/tour/xxx/geometrie.html"
</code></pre>
| 1 | 2016-08-11T07:33:38Z | 38,890,189 | <p><code>str.replace</code> returns a new string, so you will have to catch it:</p>
<p><code>link = link.replace("xxx", str(row))</code></p>
<p>Although it will be better to use a "template" url instead of reassigning <code>link</code> to the url with the <code>xxx</code> in every iteration.
An example of having a template url and using <code>format</code> to create the required url:</p>
<pre><code>import webbrowser
import csv
basic_url = "https://website.com/de/tour/{}/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print(row)
webbrowser.open(basic_url.format(row))
</code></pre>
| 1 | 2016-08-11T07:40:25Z | [
"python",
"csv",
"replace"
] |
Change string according to csv file | 38,890,064 | <p>I have to open several websites to check something. The only difference between the links to every page is an id which I have stored in a CSV file.
I want to iterate through the CSV file and replace the id for every website.</p>
<p>I want to do it with the replace statement and change the xxx in the link. But it does´nt change the id and tries to open the link with the xxx several times. </p>
<pre><code>import webbrowser
import csv
link = "https://website.com/de/tour/xxx/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print(row)
link.replace("xxx", str(row))
webbrowser.open(link)
print(link)
link = "https://website.com/de/tour/xxx/geometrie.html"
</code></pre>
| 1 | 2016-08-11T07:33:38Z | 38,890,281 | <p>You can also use <code>format</code>.</p>
<pre><code>for row in reader:
webbrowser.open('https://website.com/de/tour/{0}/geometrie.html'.format(row))
</code></pre>
| 0 | 2016-08-11T07:44:59Z | [
"python",
"csv",
"replace"
] |
Django - Extract from JSON data using Python | 38,890,207 | <p>Everytime I extract from JSON data, I will got <code>TypeError: unhashable type: 'dict'</code></p>
<p>My json info</p>
<pre><code>u 'paging': {
u 'cursors': {
u 'after': u 'MTQyNzMzMjE3MDgxNzUzOQZDZD', u 'before': u 'OTUzNDg3MjMxMzQ2NjQ0'
}
}, u 'data': [{
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Nurdin Norazan Services', u 'id': u '953487231346644'
}, {
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Intellij System Solution Sdn. Bhd.', u 'id': u '433616770180650'
}]
}
</code></pre>
<p>My code</p>
<pre><code>data = json.load(urllib2.urlopen("https://graph.facebook.com/v2.7/me/accounts?access_token="XXXXX")
print (data[data][0][id]) //953487231346644
</code></pre>
<p>BTW, how to print loop data?</p>
<p>Please advice. Thank you.</p>
| -1 | 2016-08-11T07:41:19Z | 38,890,387 | <p>According to the docs, <code>json.load</code> is for reading file pointers (or some object that implements the <code>read()</code> interface).
<a href="https://docs.python.org/2.7/library/json.html#json.load" rel="nofollow">https://docs.python.org/2.7/library/json.html#json.load</a></p>
<p>I'd say you want <code>json.loads</code>, but in fact you want <code>json.dumps</code>. Your TypeError implies that you are getting in a python dictionary (very similar to JSON), whereas json.load/s expects a string.</p>
<pre><code>>>> import json
>>> json.dumps({"foo": "bar"})
'{"foo": "bar"}'
>>> json.loads({"foo": "bar"})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'dict'
>>> json.loads(json.dumps({"foo": "bar"}))
{'foo': 'bar'}
</code></pre>
<p>As for looping through data, iterate through it:</p>
<pre><code>for key, val in data.items():
print("{}: {}".format(key, val))
</code></pre>
<p>You may have to implement some fancier looping if you want to recursively loop through json.</p>
| 0 | 2016-08-11T07:50:28Z | [
"python",
"json",
"django"
] |
Django - Extract from JSON data using Python | 38,890,207 | <p>Everytime I extract from JSON data, I will got <code>TypeError: unhashable type: 'dict'</code></p>
<p>My json info</p>
<pre><code>u 'paging': {
u 'cursors': {
u 'after': u 'MTQyNzMzMjE3MDgxNzUzOQZDZD', u 'before': u 'OTUzNDg3MjMxMzQ2NjQ0'
}
}, u 'data': [{
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Nurdin Norazan Services', u 'id': u '953487231346644'
}, {
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Intellij System Solution Sdn. Bhd.', u 'id': u '433616770180650'
}]
}
</code></pre>
<p>My code</p>
<pre><code>data = json.load(urllib2.urlopen("https://graph.facebook.com/v2.7/me/accounts?access_token="XXXXX")
print (data[data][0][id]) //953487231346644
</code></pre>
<p>BTW, how to print loop data?</p>
<p>Please advice. Thank you.</p>
| -1 | 2016-08-11T07:41:19Z | 38,890,473 | <p>Your problem is not in "extracting" the data: it's your print statement, as the full traceback would have shown.</p>
<p>In that statement for some reason you call <code>data[data]</code>. But that just means you're trying to index the data dictionary with itself. To get the data <em>key</em>, you need to use a string: <code>data["data"]</code>; and the same for the id value.</p>
<pre><code>print(data["data"][0]["id"])
</code></pre>
| 1 | 2016-08-11T07:55:07Z | [
"python",
"json",
"django"
] |
Django - Extract from JSON data using Python | 38,890,207 | <p>Everytime I extract from JSON data, I will got <code>TypeError: unhashable type: 'dict'</code></p>
<p>My json info</p>
<pre><code>u 'paging': {
u 'cursors': {
u 'after': u 'MTQyNzMzMjE3MDgxNzUzOQZDZD', u 'before': u 'OTUzNDg3MjMxMzQ2NjQ0'
}
}, u 'data': [{
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Nurdin Norazan Services', u 'id': u '953487231346644'
}, {
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Intellij System Solution Sdn. Bhd.', u 'id': u '433616770180650'
}]
}
</code></pre>
<p>My code</p>
<pre><code>data = json.load(urllib2.urlopen("https://graph.facebook.com/v2.7/me/accounts?access_token="XXXXX")
print (data[data][0][id]) //953487231346644
</code></pre>
<p>BTW, how to print loop data?</p>
<p>Please advice. Thank you.</p>
| -1 | 2016-08-11T07:41:19Z | 38,904,878 | <p>I just got the answer</p>
<pre><code>data = json.load(urllib2.urlopen("https://graph.facebook.com/v2.7/me/accounts?access_token="XXXXX")
for i in data['data']:
print i['id']
</code></pre>
| 0 | 2016-08-11T19:44:09Z | [
"python",
"json",
"django"
] |
User cash on delivery in django-oscar | 38,890,232 | <p>I'm working in e-shop project using <code>django-oscar</code> and i trying to add COD support. I'm using <a href="https://github.com/michaelkuty/django-oscar-cash-on-delivery" rel="nofollow"><code>django-oscar-cash-on-delivery</code></a>.</p>
<p>I did the <a href="https://github.com/michaelkuty/django-oscar-cash-on-delivery/blob/master/README.rst" rel="nofollow">steps</a>, you can see my configuration:</p>
<pre><code>THIRD_PARTY_APPS = [
'jet.dashboard',
'jet',
'axes',
'cashondelivery',
'django_extensions',
'oscarapi',
'paypal',
'payu',
'rest_framework',
'robots',
'widget_tweaks',
'webpack_loader',
]
</code></pre>
<p>And created an app called <code>apps</code> and loaded properly:</p>
<pre><code>INSTALLED_APPS = THIRD_PARTY_APPS + PROJECT_APPS + [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
] + get_core_apps(
[
'apps.shipping'
]
)
</code></pre>
<p>In <code>apps</code>folder i created an <code>apps.py</code> file with this code inside:</p>
<pre><code>from oscar.app import Shop
# from apps.checkout.app import application as checkout_app
from cashondelivery.app import application as checkout_app
class ApplicationShop(Shop):
checkout_app = checkout_app
application = ApplicationShop()
</code></pre>
<p>But i can't understand why Oscar doesn't show me the checkout template with cash on delivery method.</p>
<p>This is my structure folder:
<a href="http://i.stack.imgur.com/cG8uq.png" rel="nofollow"><img src="http://i.stack.imgur.com/cG8uq.png" alt="enter image description here"></a></p>
<p>Can anyone help me with this?</p>
| 1 | 2016-08-11T07:42:43Z | 39,086,305 | <p>There are two ways for integrate cash on delivery in <code>django-oscar</code> project:</p>
<ol>
<li><p>Override checkout application:<br>
In this case is necessary override checkout templates because by default <code>Oscar</code> don't or can't get the <code>cashondelivery</code> checkout templates, at least <code>payment_details</code>. So, first you need override these template file and after create an app and inside it add a <code>app.py</code> file where you override the checkout application as <code>cashondelivery</code> <a href="https://github.com/michaelkuty/django-oscar-cash-on-delivery/blob/master/README.rst" rel="nofollow">documentation</a> says.</p>
<p><a href="http://i.stack.imgur.com/NBuWi.png" rel="nofollow"><img src="http://i.stack.imgur.com/NBuWi.png" alt="enter image description here"></a></p></li>
<li><p>Create a custom view and checkout app:<br>
You can see in <code>django-oscar-paypal</code> integration package a sandbox example for integrate <code>paypal</code> with <code>Oscar</code>.
You can see in this package that they use a checkout app for replace the defaul checkout app; inside this app they override <code>view.py</code> file and <code>app.view</code> file; override templates and override <code>app.py</code> file.</p>
<p>So, we can do the same for <code>django-oscar-cash-on-delivery</code>, so:<br>
a. Create a new application called <code>checkout</code> inside the <code>apps</code> application if you want, or some like you. This application only will contain the views and application file.<a href="http://i.stack.imgur.com/ChWGr.png" rel="nofollow"><img src="http://i.stack.imgur.com/ChWGr.png" alt="enter image description here"></a></p>
<p>b. In views file we'll put the <code>cash-on-delivery</code> <a href="https://github.com/michaelkuty/django-oscar-cash-on-delivery/blob/master/sandbox/apps/checkout/views.py" rel="nofollow">views</a> file, now it is in sanbox folder.</p>
<p>c. In app file inside checkout we declarate the checkout application:</p></li>
</ol>
<p>from oscar.apps.checkout import app</p>
<p>from .views import PaymentDetailsView</p>
<p>class CheckoutApplication(app.CheckoutApplication):
payment_details_view = PaymentDetailsView</p>
<p>application = CheckoutApplication()</p>
<p>d. Finally, we declarate our checkout app as default checkout app as <a href="https://github.com/michaelkuty/django-oscar-cash-on-delivery/blob/master/README.rst" rel="nofollow">documentation</a> says.<br>
e. We have ensure that the application override default check out application, in settings:</p>
<pre><code>INSTALLED_APPS = + get_core_apps(
[
'apps.checkout',
'apps.shipping'
]
)
</code></pre>
<p>You can now pay with cash on delivery method in your Oscar project.<br>
We recommend use the second way because enable you use more than one method for payment.</p>
<p><strong>PD:</strong><br>
Wich the new master version we have moved the <code>views.py</code> file at sandbox folder, so, the first option won't work anymore. But, if you want it come back, say us please!</p>
| 0 | 2016-08-22T18:25:33Z | [
"python",
"django",
"e-commerce",
"django-oscar"
] |
Reading binary file with specific sequence in Python | 38,890,265 | <p>I have some <code>32x32x8192</code> binary datafile with a specific sequence and I was wondering.<br>
How I can read it as so in <code>Python 3x.</code> The file consists of <code>Nx à Ny à Nz</code> numbers (floating point single precision).<br>
The sequence of the numbers corresponds to <code>indexes x, y and z</code> which all increase sequentially from <code>1 to Nx, Ny and Nz</code> respectively.<br>
The fastest-varying index is <code>z</code>, followed by <code>y</code>, and the slowest varying index is <code>x</code>.<br>
That is, the first <code>Nz</code> numbers from the sequence correspond to indexes <code>x = 1, y = 1</code>, and <code>z</code> increasing from <code>1 to Nz</code>.</p>
<p>A sample of the data by <code>np.fromfile("turbine_32x32x8192.bin", dtype=float, count=10, sep="")</code>:</p>
<pre><code>[ -8.26325563e+02 -7.41263867e+00 -1.52541103e+01 -1.83999292e+03
-7.53629982e+03 -3.43120688e+05 -1.88674962e+04 -1.81482768e+00
-4.13878029e+03 -8.29483377e+05]
</code></pre>
| 2 | 2016-08-11T07:44:20Z | 38,890,653 | <pre><code>import struct
data = open(filename, 'rb').read()
def chunk(i, j):
at = i * 32 + j
return data[at * (8192 * 4) : (at + 1) * (8192 * 4)]
a = [list(struct.unpack('8192f', chunk(i, j))) for i in range(32) for j in range(32)]
</code></pre>
<p>the result will be in <code>a</code>.</p>
| 0 | 2016-08-11T08:04:25Z | [
"python",
"pandas",
"numpy",
"binary"
] |
TransportError happened when calling softlayer-api | 38,890,319 | <p>It is wired to get an exception at about 7:30am(utc+8) everyday when calling softlayer-api.</p>
<p>TransportError: TransportError(0): HTTPSConnectionPool(host='api.softlayer.com', port=443): Max retries exceeded with url: /xmlrpc/v3.1/SoftLayer_Product_Package (Caused by ProxyEr
ror('Cannot connect to proxy.', error('Tunnel connection failed: <strong>503 Service Unavailable</strong>',)))</p>
<p>And I uses a proxy to forward https request to softlayer's server. At first I thougth it is caused by the proxy, but when I looked into the log, it showed every request had been forwarded successfully. So maybe it is caused by the server. Does the server do something so busy at that moment everyday that it fails to server?</p>
| 0 | 2016-08-11T07:47:16Z | 38,898,571 | <p>We don't have any report about this kind of issue nor if the server is busy in SoftLayer's side. but regarding to your issue, it is something related with network issues. It seems that there is something happening with your proxy connection.</p>
<p>First we need to discard if the proxy can be the reason for this issue, it would be very useful if can verify that this issue is reproducible without using a proxy from your side, let me know if you could test it.</p>
<p>If you could check this without proxy, I recommend to submit a ticket for further investigation about this issue.</p>
| 0 | 2016-08-11T14:02:55Z | [
"python",
"softlayer"
] |
Why is an int in a list and in an compact array the same size? (24bytes) | 38,890,542 | <p>I was just reading that a compactArray defined as "i" should yield an array that hold integers with 2 or 4 bytes, but executing this snippet i am still getting 24bytes, which is the same as i would use integer lists.</p>
<pre><code>import array
import sys
lowLevelArray = array.array("i", [1,2,3])
print sys.getsizeof(lowLevelArray[0])
pythonList = [1,2,3]
print sys.getsizeof(pythonList[0])
</code></pre>
<p>Output:</p>
<blockquote>
<p>24</p>
<p>24</p>
</blockquote>
| 0 | 2016-08-11T07:58:18Z | 38,890,754 | <p>Because once you retrieve the integer it has to be wrapped in a python object so you can work with it. Everything in python is an object, it has no concept of primitives (even though the underlying implementation uses them). </p>
| 2 | 2016-08-11T08:09:34Z | [
"python",
"arrays"
] |
Why is an int in a list and in an compact array the same size? (24bytes) | 38,890,542 | <p>I was just reading that a compactArray defined as "i" should yield an array that hold integers with 2 or 4 bytes, but executing this snippet i am still getting 24bytes, which is the same as i would use integer lists.</p>
<pre><code>import array
import sys
lowLevelArray = array.array("i", [1,2,3])
print sys.getsizeof(lowLevelArray[0])
pythonList = [1,2,3]
print sys.getsizeof(pythonList[0])
</code></pre>
<p>Output:</p>
<blockquote>
<p>24</p>
<p>24</p>
</blockquote>
| 0 | 2016-08-11T07:58:18Z | 38,891,067 | <p>The array object <em>is</em> more space efficient; it's 4 bytes per int it holds, plus 56 bytes overhead:</p>
<pre><code>>>> sys.getsizeof(array.array("i", [1,2,3])
68L
>>> sys.getsizeof(array.array("i", range(1000))
4056L
</code></pre>
<p>However, when you do</p>
<pre><code>>>> sys.getsizeof(lowLevelArray[0])
</code></pre>
<p>it first evaluates <code>lowLevelArray[0]</code>, which of course returns a normal integer, and then shows the size used by <em>that</em>. Which is completely unrelated to the fact that you also have an array that happens to hold the same value.</p>
| 2 | 2016-08-11T08:26:15Z | [
"python",
"arrays"
] |
Formulate query and rank answers via cosine similarity Python | 38,890,575 | <p>I tokenized multiple text files and created a <code>tf-idf</code> matrix from that: </p>
<pre><code>Token 1 Token 2 Token 3
Doc 1 0.00.. 0.0002 0.0003
Doc 2 0.00.. ... ...
Doc 3 ... ... ...
...
</code></pre>
<p>How do I now formulate a query, say for token 1 and token 3? </p>
<p>How do I then rank them using cosine similarity? </p>
| 0 | 2016-08-11T07:59:40Z | 38,891,597 | <p>If you are trying to rank them per Doc I suggest using a tuple per Token. I'm not certain on the maths behind cosine similarity but assuming we can use a function <code>f(x,y)</code> that returns the cosine similarity between x and y, we can apply this to Token 1 to Token 2 and 3 as per your suggestion as follows:</p>
<pre><code>list_with_scores = []
for i,doc in enumerate(Docs):
score1_3 = f(doc[0],doc[1])
score1_3 = f(doc[0],doc[2])
list_with_scores.append(i,score1_3, score_2_3,)
#then sort by score1_3
sortedlist1 = sorted(list_with_scores, key = lambda x:x[1])
#similary, sort by score2_3
sortedlist2 = sorted(list_with_scores, key = lambda x:x[2])
</code></pre>
<p>You can also keep the token score in the tuple if required. And the explicit saving to <code>score1_3</code> and <code>score1_2</code> can be removed, it's done for readiblity, probably better to leave them as is. For more information regarding the sorting part, check <a href="http://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value">Sort a list of tuples by 2nd item (integer value) </a></p>
| 0 | 2016-08-11T08:51:07Z | [
"python",
"jupyter",
"cosine-similarity"
] |
How to read every log line to match a regex pattern using spark? | 38,890,660 | <p>The following program throws an error</p>
<pre><code>from pyparsing import Regex, re
from pyspark import SparkContext
sc = SparkContext("local","hospital")
LOG_PATTERN ='(?P<Case_ID>[^ ;]+);(?P<Event_ID>[^ ;]+);(?P<Date_Time>[^ ;]+);(?P<Activity>[^;]+);(?P<Resource>[^ ;]+);(?P<Costs>[^ ;]+)'
logLine=sc.textFile("C:\TestLogs\Hospital.log").cache()
#logLine='1;35654423;30-12-2010:11.02;register request;Pete;50'
for line in logLine.readlines():
match = re.search(LOG_PATTERN,logLine)
Case_ID = match.group(1)
Event_ID = match.group(2)
Date_Time = match.group(3)
Activity = match.group(4)
Resource = match.group(5)
Costs = match.group(6)
print Case_ID
print Event_ID
print Date_Time
print Activity
print Resource
print Costs
</code></pre>
<p>Error: </p>
<blockquote>
<p>Traceback (most recent call last): File
"C:/Spark/spark-1.6.1-bin-hadoop2.4/bin/hospital2.py", line 7, in
for line in logLine.readlines(): AttributeError: 'RDD' object has no attribute 'readlines'</p>
</blockquote>
<p>If i add the <code>open</code> function to read the file then i get the following error:</p>
<blockquote>
<p>Traceback (most recent call last): File
"C:/Spark/spark-1.6.1-bin-hadoop2.4/bin/hospital2.py", line 7, in
f = open(logLine,"r") TypeError: coercing to Unicode: need string or buffer, RDD found</p>
</blockquote>
<p>Can't seem to figure out how to read line by line and extract words that match the pattern.
Also if i pass only a single logline <code>logLine='1;35654423;30-12-2010:11.02;register request;Pete;50'</code> it works. I'm new to spark and know only basics in python. Please help.</p>
| 0 | 2016-08-11T08:04:41Z | 38,891,153 | <p>You are mixing things up.
The line </p>
<pre><code>logLine=sc.textFile("C:\TestLogs\Hospital.log")
</code></pre>
<p>creates an RDD, and RDDs do not have a readlines() method.
See the RDD API here:</p>
<p><a href="http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD" rel="nofollow">http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD</a></p>
<p>You can use collect() to retrieve the content of the RDD line by line.
readlines() is part of the standard Python file API, but you do not usually need it when working with files in Spark.
You simply load the file with textFile() and then process it with RDD API, see the link above. </p>
| 1 | 2016-08-11T08:30:24Z | [
"python",
"apache-spark",
"pyspark"
] |
Server crash on MySQL backup using python | 38,890,678 | <p>I have a python script that backs up my MySQL database to Amazon S3 buckets every hour. I use the script to simply call <code>mysqldump</code> in order to create the dump and then upload it to the S3 bucket using <code>tinys3</code>, note that I set <code>lock-tables</code> to false so that transactions by other applications are not hindered.</p>
<p>Here is the script for your reference:</p>
<pre><code>import tinys3
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
application = get_wsgi_application()
from django.utils import timezone
import pytz
import datetime
import json
timezone.activate(pytz.timezone("Asia/Kolkata"))
current_datetime = timezone.localtime(
datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
)
dir_struct = '/'.join(current_datetime.strftime("%Y-%m-%d-%H-%M-%S").split('-'))
endpoint = 's3-us-west-2.amazonaws.com'
params = json.load(open('buckets.json'))
S3_ACCESS_KEY=params['S3_ACCESS_KEY']
S3_SECRET_KEY = params["S3_SECRET_KEY"]
bucket = params['mysql']
db_name = params['db_name']
mysql_command = 'sudo mysqldump --defaults-file=/home/ubuntu/.my.cnf --lock-tables=false %s > /home/ubuntu/%s.sql' %(db_name, db_name)
compress_command = "zip -r /home/ubuntu/%s.sql.zip /home/ubuntu/%s.sql" %(db_name, db_name)
delete_command = "sudo rm -rf /home/ubuntu/%s.sql*" %db_name
os.system(mysql_command)
os.system(compress_command)
backup_file = open('/home/ubuntu/%s.sql.zip' %db_name, 'rb')
conn = tinys3.Connection(S3_ACCESS_KEY, S3_SECRET_KEY, tls=True,endpoint=endpoint)
print conn.upload(
(dir_struct+'%s.sql.zip' %db_name),
backup_file,
bucket,
public=False
)
print conn.get((dir_struct+'%s.sql.zip' %db_name),bucket)
os.system(delete_command)
</code></pre>
<p>The problem is that when I start the cron job to run this script every hour, the server crashes after a few hours (say 5 to 7 hours). I haven't found a considerable reason for this behaviour yet. What is the problem here? Is there a fault in this script or something related to MySQL?</p>
| 1 | 2016-08-11T08:06:05Z | 38,898,064 | <p>It's easy to imagine what's happening here. <a href="http://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#mysqldump-performance" rel="nofollow">Mysqldump</a> is slow. Restoration worse.</p>
<blockquote>
<p>It is not intended as a fast or scalable solution for backing up
substantial amounts of data. With large data sizes, even if the backup
step takes a reasonable time, restoring the data can be very slow
because replaying the SQL statements involves disk I/O for insertion,
index creation, and so on.</p>
</blockquote>
<p>Once you take the backup you appear to zip it, then upload it to amazon s3. It's my guess is that your second backup starts before the first one finishes and it keeps escalating until the server is overwhelmed.</p>
<p>Even if your server doesn't crash, you still should not be using this approach because in a few months time you will be spending thumping amounts for storage. </p>
<p>There is a much much better way. <a href="http://dev.mysql.com/doc/refman/5.7/en/replication.html" rel="nofollow">Mysql replication</a>. No cronjobs, almost immidiate recovery if the mast goes down, no bulky data transfers.</p>
| 1 | 2016-08-11T13:41:19Z | [
"python",
"mysql",
"amazon-s3"
] |
run a url in django backend | 38,890,694 | <p>I need the server to open a url in the backend, before returning an http response, any http response.</p>
<p>For example, After user enters his/her phone number and submits, in my views, a url like:</p>
<blockquote>
<p>example.com/api/publicapi/ptpsms?username=username&password=password ...</p>
</blockquote>
<p>is ran, and then a page is renderd, asking user to enter the code that was sent to him/her by sms.</p>
| -2 | 2016-08-11T08:06:39Z | 38,902,655 | <p>I think you mean to make a request to an external service through a http request inside your view.
You might want to look for a http client <a href="https://docs.python.org/3.1/library/http.client.html" rel="nofollow">https://docs.python.org/3.1/library/http.client.html</a>
Then get the response and do whatever you need to do inside your view before returning it to your client.</p>
| 0 | 2016-08-11T17:28:13Z | [
"python",
"django"
] |
run a url in django backend | 38,890,694 | <p>I need the server to open a url in the backend, before returning an http response, any http response.</p>
<p>For example, After user enters his/her phone number and submits, in my views, a url like:</p>
<blockquote>
<p>example.com/api/publicapi/ptpsms?username=username&password=password ...</p>
</blockquote>
<p>is ran, and then a page is renderd, asking user to enter the code that was sent to him/her by sms.</p>
| -2 | 2016-08-11T08:06:39Z | 38,920,927 | <p><a href="http://docs.python-requests.org/en/master/" rel="nofollow">http://docs.python-requests.org/en/master/</a></p>
<p>This one did the Job, thanks to Vipul</p>
| 1 | 2016-08-12T14:55:18Z | [
"python",
"django"
] |
Python Eve: Is there a way to avoid resource lookup passed through url in eve framework | 38,890,705 | <p>Python Eve: Is there a way to avoid resource lookup passed through url in eve framework? </p>
<p>e.g. /people/(string:user_id)/hobbies</p>
<p>I want to avoid user_id lookup in the endpoint request where I will handle user_id field in a custom way.</p>
| 0 | 2016-08-11T08:07:04Z | 38,903,245 | <p>You can select which methods are allowed for each resource, or globally. </p>
<p>In this case you could limit the <code>GET</code> for <code>people</code> by setting the item <code>item_methods</code> property. For example, if you want to allow only <code>DELETE</code> for the item, you need to add the following in the <a href="http://python-eve.org/config.html#resource-item-endpoints" rel="nofollow">endpoint definition</a>:</p>
<pre><code>'item_methods': ['DELETE']
</code></pre>
<p>The documentation says:</p>
<blockquote>
<p>item_methods: </p>
<p>A list of HTTP methods supported at item endpoint. Allowed values: GET, PATCH, PUT and DELETE. PATCH or, for clients not supporting PATCH, POST with the X-HTTP-Method-Override header tag. Locally overrides ITEM_METHODS.</p>
</blockquote>
| 0 | 2016-08-11T18:03:33Z | [
"python",
"get",
"endpoint",
"eve"
] |
cannot import name pool theano | 38,890,764 | <p>as written in the title, I cannot import pool</p>
<p>specifically,</p>
<pre><code>from theano.tensor.signal import pool
</code></pre>
<p>doesn't work.</p>
<p>It says</p>
<pre><code>ImportError: cannot import name pool
</code></pre>
<p>I tried to update theano by</p>
<pre><code>sudo pip install git+git://github.com/Theano/Theano.git --upgrade --no-deps
</code></pre>
<p>Then, it shows 'Successfully installed Theano-0.9.0.dev2' but still cannot import pool.</p>
<p>When I write these code in the python interpreter</p>
<pre><code>import theano
theano.__version__
</code></pre>
<p>Then it says '0.7.0.dev-f986e0dd35f .... '
I think still I am using 0.7.0 version but I don't know how to do.</p>
<p>Would you plz tell me how to solve importing error?</p>
| 0 | 2016-08-11T08:10:03Z | 38,899,784 | <p>You probably have two Pythons installed on your system, one of them locally and the other globally. When you <code>sudo pip install</code>, you install the latest Theano for your global installation of Python. However, when you run Python, you run the local Python with the old version of the Theano.</p>
| 0 | 2016-08-11T14:53:31Z | [
"python",
"theano",
"importerror"
] |
Tkinter Checkbox issues | 38,890,769 | <p>Edit: Changed to use TopLevel and the radio buttons</p>
<p>I am working on making a python chess game for the fun of it and I am coming at a slight problem with creating a checkbox.</p>
<p>In the standard game of chess, if the pawn reaches the other side of the chessboard, the player will be able to choose what chess piece they want. </p>
<p>Well, I wanted to give the user a checkbox to check the item they wanted and then the box would disappear(destroyed). Here is my code:</p>
<pre><code>from Tkinter import *
def AddChessPiece():
CheckBox = TopLevel()
print("Im in The checkbox function")
CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 = IntVar()
CheckVar4 = IntVar()
C1 = Radiobutton(CheckBox, text="Rook",variable = CheckVar1, command = lambda: PieceName("Rook"))
C2 = Radiobutton(CheckBox, text="Knight",variable = CheckVar2,command= lambda: PieceName("Knight"))
C3 = Radiobutton(CheckBox, text="Bishop",variable = CheckVar3,command= lambda: PieceName("Bishop"))
C4 = Radiobutton(CheckBox, text="Queen",variable = CheckVar4, command= lambda: PieceName("Queen"))
C1.pack()
C2.pack()
C3.pack()
C4.pack()
CheckBox.mainloop()
print("Im leaving the checkbox function")
</code></pre>
<p>What it is doing is that it creates the window, then when checked, it sends the item to the lambda function. The problem is that </p>
<ol>
<li><p>I don't know where or how to destroy it immediately after the item has been clicked and </p></li>
<li><p>It seems like the program doesn't continue when it goes into the function PieceName. It goes through the complete function but it never prints "I'm Leaving the checkbox function". I'm thinking this might be an error since I destroyed the function.Any help would be wonderful!</p></li>
</ol>
<p>Here is the PieceName Method if you're curious. I don't think it will help anything though. What is does is it Adds the new coordinates to new chess piece first(Depending if its player 1 (White Chess Piece) or player 2 (Black chess piece) turn to go) and then removes the pawns coordinates.</p>
<pre><code>def PieceName(name):
global Player1, CurrentChessPiece, IndexVal,White_Pieces,Black_Pieces
if(Player1 == True):
FullName = "White_" + name
NewPieceIndex = White_Pieces.index(FullName)
White_Pieces[NewPieceIndex].coordinates.append(CurrentChessPiece.coordinates[IndexVal])
else:
FullName = "Black_" + name
NewPieceIndex = Black_Pieces.index(FullName)
Black_Pieces[NewPieceIndex].coordinates.append(CurrentChessPiece.coordinates[IndexVal])
del CurrentChessPiece.coordinates[IndexVal]
CheckBox.destroy()
print("Im leaving the PieceName function")
</code></pre>
| 0 | 2016-08-11T08:10:13Z | 38,905,128 | <p>Ok, so this is the new revision that is now working. What I did was remove all the lambda parameters and just saved all possible values to "CheckVar1". From there I created a messagebox and gave the user the options to choose from the options and click C5 ("Ok button") to quit.</p>
<p>When the ok button was clicked, it closed the widget but did not destroy it, so I was able to still grab "CheckVar1". From there, I called a getter function "CheckVar1.get()" to return the value as a string variable and pass it into the following method "PieceName"</p>
<p>Once the method "PieceName" was finished, "Checkbox" was then destroyed, removing it from the system.</p>
<pre><code>def AddChessPiece():
CheckBox = Toplevel()
print("Im in The checkbox function")
CheckVar1 = StringVar()
C = Message(CheckBox,text="What did you want to\n replace your pawn for?\n\n",width = 300)
C1 = Radiobutton(CheckBox, text="Rook",variable = CheckVar1,value ="Rook")
C2 = Radiobutton(CheckBox, text="Knight",variable = CheckVar1,value = "Knight")
C3 = Radiobutton(CheckBox, text="Bishop",variable = CheckVar1,value = "Bishop")
C4 = Radiobutton(CheckBox, text="Queen",variable = CheckVar1,value = "Queen")
C5 = Button(CheckBox, text="Ok", command=CheckBox.quit)
C.pack()
C1.pack()
C2.pack()
C3.pack()
C4.pack()
C5.pack()
CheckBox.mainloop()
PieceName(str(CheckVar1.get()))
print("Im leaving the checkbox function")
CheckBox.destroy()
</code></pre>
<p>This is the second function. The only thing that was changed was that "CheckBox.destroy()" was not used at all in this function. CheckBox wasn't used at all in this function, so this code is now irrelevant to the discussion.</p>
<pre><code>def PieceName(name):
global Player1, CurrentChessPiece, IndexVal,White_Pieces,Black_Pieces
if(Player1 == True):
FullName = "White_" + str(name)
for n in range(0, len(White_Pieces)):
if((FullName in White_Pieces[n].name)== True):
White_Pieces[n].coordinates.append(CurrentChessPiece.coordinates[IndexVal])
else:
FullName = "Black_" + str(name)
for n in range(0,len(Black_Pieces)):
if((FullName in Black_Pieces[n].name) == True):
Black_Pieces[n].coordinates.append(CurrentChessPiece.coordinates[IndexVal])
del CurrentChessPiece.coordinates[IndexVal]
print("Name is " + str(FullName))
print("Im leaving the PieceName function")
</code></pre>
<p>Thanks for all the help!</p>
| 1 | 2016-08-11T20:01:33Z | [
"python",
"checkbox",
"tkinter"
] |
Python - Microsoft Cognitive Verify API (params) | 38,890,807 | <p>I'm trying to use the Microsoft Cognitive Verify API with python 2.7: <a href="https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523a" rel="nofollow">https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523a</a></p>
<p>The code is:</p>
<pre><code>import httplib, urllib, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'my key',
}
params = '{\'faceId1\': \'URL.jpg\',\'faceId2\': \'URL.jpg.jpg\'}'
try:
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/face/v1.0/verify?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
</code></pre>
<p>I tried letting the conn.request line like this:</p>
<pre><code>conn.request("POST", "/face/v1.0/verify?%s" % params, "", headers)
</code></pre>
<p>The error is:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request</h2>
<hr><p>HTTP Error 400. The request is badly formed.</p>
</BODY></HTML>
</code></pre>
<p>I alrealy tried to follow and make work the following codes:</p>
<ol>
<li><p><a href="https://github.com/Microsoft/Cognitive-Emotion-Python/blob/master/Jupyter%20Notebook/Emotion%20Analysis%20Example.ipynb" rel="nofollow">https://github.com/Microsoft/Cognitive-Emotion-Python/blob/master/Jupyter%20Notebook/Emotion%20Analysis%20Example.ipynb</a></p></li>
<li><p><a href="http://stackoverflow.com/questions/33769708/using-project-oxfords-emotion-api">Using Project Oxford's Emotion API</a></p></li>
</ol>
<p>However I just can't make this one work. I guess there is something wrong with the params or body argument.
Any help is very appreciated.</p>
| 1 | 2016-08-11T08:12:51Z | 38,908,506 | <p>Dawid's comment looks like it should fix it (double quoting), try this for python 2.7:</p>
<pre><code>import requests
url = "https://api.projectoxford.ai/face/v1.0/verify"
payload = "{\n \"faceId1\":\"A Face ID\",\n \"faceId2\":\"A Face ID\"\n}"
headers = {
'ocp-apim-subscription-key': "KEY_HERE",
'content-type': "application/json"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
</code></pre>
<p>for python 3: </p>
<pre><code>import http.client
conn = http.client.HTTPSConnection("api.projectoxford.ai")
payload = "{\n\"faceId1\": \"A Face ID\",\n\"faceId2\": \"Another Face ID\"\n}"
headers = {
'ocp-apim-subscription-key': "keyHere",
'content-type': "application/json"
}
conn.request("POST", "/face/v1.0/verify", payload, headers)
res = conn.getresponse()
data = res.read()
</code></pre>
| 0 | 2016-08-12T01:32:55Z | [
"python",
"microsoft-cognitive"
] |
Possible Bug when using diff on datetime objects in a pandas groupby object with multiindex | 38,891,000 | <p>Consider a dataframe with a column with labels that are used to create groups and two rows of the same dates:</p>
<pre><code>import datetime as dt
import pandas as pd
dd = [['A','A','A','A','B','B']\
,[dt.date(1981,3,6),dt.date(1986,5,1),dt.date(1983,11,8)\
,dt.date(1982,6,11),dt.date(1977,2,26),dt.date(1991,9,4)]]
dd = map(list,zip(*dd))
DF = pd.DataFrame(dd,columns=['Label','Date'])
DF['Date2'] = DF['Date'].copy()
print DF
print type(DF.Date[0])
print type(DF.Date2[0])
</code></pre>
<p>This yields:</p>
<pre><code> Label Date Date2
0 A 1981-03-06 1981-03-06
1 A 1986-05-01 1986-05-01
2 A 1983-11-08 1983-11-08
3 A 1982-06-11 1982-06-11
4 B 1977-02-26 1977-02-26
5 B 1991-09-04 1991-09-04
<type 'datetime.date'>
<type 'datetime.date'>
</code></pre>
<p>Now I can do these:</p>
<pre><code>print DF.groupby(['Label']).diff()
print "======================================"
print DF.groupby(['Label']).apply(lambda s: s[u'Date'].diff())
print "======================================"
print DF.groupby(['Label']).apply(lambda s: s[u'Date2'].diff())
</code></pre>
<p>Leading to this output:</p>
<pre><code> Date Date2
0 NaN NaN
1 1882 days, 0:00:00 1882 days, 0:00:00
2 -905 days, 0:00:00 -905 days, 0:00:00
3 -515 days, 0:00:00 -515 days, 0:00:00
4 NaN NaN
5 5303 days, 0:00:00 5303 days, 0:00:00
======================================
Label
A 0 NaT
1 1882 days
2 -905 days
3 -515 days
B 4 NaT
5 5303 days
Name: Date, dtype: timedelta64[ns]
======================================
Label
A 0 NaT
1 1882 days
2 -905 days
3 -515 days
B 4 NaT
5 5303 days
Name: Date2, dtype: timedelta64[ns]
</code></pre>
<p>However when I'm doing these:</p>
<pre><code>print DF.groupby(['Label','Date']).diff()
print "======================================"
print DF.groupby(['Label','Date']).apply(lambda s: s[u'Date2'].diff())
print "======================================"
print DF.groupby(['Label','Date'])[u'Date2'].transform(pd.Series.diff)
</code></pre>
<p>Then the output is broken:</p>
<pre><code> Date2
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
======================================
Label Date
A 1981-03-06 0 NaN
1982-06-11 3 NaN
1983-11-08 2 NaN
1986-05-01 1 NaN
B 1977-02-26 4 NaN
1991-09-04 5 NaN
Name: Date2, dtype: object
======================================
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
Name: Date2, dtype: object
</code></pre>
<p>As you can see for some reason the Date2 column is no longer a timedelta64 dtype but just an object type. This happens with every method I have tried and also when switching the two date columns, so this must be something to do with the multiindex groupby.</p>
<p>I can't tell if this is expected or unexpected behaviour, that is if it's a bug or not.</p>
<p>EDIT: Pandas 0.18.1 on Python 2.7.12</p>
<p>EDIT2: Deleted, my mistake.</p>
| 1 | 2016-08-11T08:23:08Z | 38,891,332 | <p>I see two problems - first you need dtypes <code>datetimes</code> and then your sample data where output is <code>NaT</code> (len of each group was <code>1</code>, so <code>difference</code> is <code>NaT</code>):</p>
<pre><code>import datetime as dt
import pandas as pd
dd = [['A','A','A','A','B','B']\
,[dt.date(1981,3,6),dt.date(1986,5,1),dt.date(1983,11,8)\
,dt.date(1982,6,11),dt.date(1977,2,26),dt.date(1991,9,4)]]
dd = list(zip(*dd))
DF = pd.DataFrame(dd,columns=['Label','Date'])
DF['Date2'] = DF['Date'].copy()
print (DF)
Label Date Date2
0 A 1981-03-06 1981-03-06
1 A 1986-05-01 1986-05-01
2 A 1983-11-08 1983-11-08
3 A 1982-06-11 1982-06-11
4 B 1977-02-26 1977-02-26
5 B 1991-09-04 1991-09-04
</code></pre>
<pre><code>print (DF.dtypes)
Label object
Date object
Date2 object
dtype: object
DF['Date'] = pd.to_datetime(DF['Date'])
DF['Date2'] = pd.to_datetime(DF['Date2'])
print (DF.dtypes)
Label object
Date datetime64[ns]
Date2 datetime64[ns]
dtype: object
print (DF.groupby(['Label','Date'])['Date2'].diff())
0 NaT
1 NaT
2 NaT
3 NaT
4 NaT
5 NaT
Name: Date2, dtype: timedelta64[ns]
</code></pre>
<p>I changed data in <code>Date2</code>:</p>
<pre><code>import datetime as dt
import pandas as pd
dd = [['A','A','A','A','B','B']\
,[dt.date(1981,3,6),dt.date(1981,3,6),dt.date(1983,11,8)\
,dt.date(1983,11,8),dt.date(1977,2,26),dt.date(1991,9,4)]\
,[dt.date(1981,3,6),dt.date(1986,5,1),dt.date(1983,11,8)\
,dt.date(1982,6,11),dt.date(1977,2,26),dt.date(1991,9,4)]]
dd = list(zip(*dd))
DF = pd.DataFrame(dd,columns=['Label','Date', 'Date2'])
DF['Date'] = pd.to_datetime(DF['Date'])
DF['Date2'] = pd.to_datetime(DF['Date2'])
print (DF)
Label Date Date2
0 A 1981-03-06 1981-03-06
1 A 1981-03-06 1986-05-01
2 A 1983-11-08 1983-11-08
3 A 1983-11-08 1982-06-11
4 B 1977-02-26 1977-02-26
5 B 1991-09-04 1991-09-04
print (DF.dtypes)
Label object
Date datetime64[ns]
Date2 datetime64[ns]
dtype: object
</code></pre>
<pre><code>print (DF.groupby(['Label','Date'])['Date2'].diff())
0 NaT
1 1882 days
2 NaT
3 -515 days
4 NaT
5 NaT
Name: Date2, dtype: timedelta64[ns]
print (DF.groupby(['Label','Date']).diff())
Date2
0 NaT
1 1882 days
2 NaT
3 -515 days
4 NaT
5 NaT
Label Date
print (DF.groupby(['Label','Date']).apply(lambda s: s[u'Date2'].diff()))
A 1981-03-06 0 NaT
1 1882 days
1983-11-08 2 NaT
3 -515 days
B 1977-02-26 4 NaT
1991-09-04 5 NaT
Name: Date2, dtype: timedelta64[ns]
print (DF.groupby(['Label','Date'])[u'Date2'].transform(pd.Series.diff))
0 NaT
1 1975-02-26
2 NaT
3 1968-08-04
4 NaT
5 NaT
Name: Date2, dtype: datetime64[ns]
</code></pre>
<p>If remove converting <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>, output is <code>NaN</code> and with groups with numbers <code>NaT</code>:</p>
<pre><code>import datetime as dt
import pandas as pd
dd = [['A','A','A','A','B','B']\
,[dt.date(1981,3,6),dt.date(1981,3,6),dt.date(1983,11,8)\
,dt.date(1983,11,8),dt.date(1977,2,26),dt.date(1991,9,4)]\
,[dt.date(1981,3,6),dt.date(1986,5,1),dt.date(1983,11,8)\
,dt.date(1982,6,11),dt.date(1977,2,26),dt.date(1991,9,4)]]
dd = list(zip(*dd))
DF = pd.DataFrame(dd,columns=['Label','Date', 'Date2'])
print (DF)
Label Date Date2
0 A 1981-03-06 1981-03-06
1 A 1981-03-06 1986-05-01
2 A 1983-11-08 1983-11-08
3 A 1983-11-08 1982-06-11
4 B 1977-02-26 1977-02-26
5 B 1991-09-04 1991-09-04
print (DF.dtypes)
Label object
Date object
Date2 object
dtype: object
</code></pre>
<pre><code>print (DF.groupby(['Label','Date'])['Date2'].diff())
0 NaT
1 1882 days, 0:00:00
2 NaT
3 -515 days, 0:00:00
4 NaN
5 NaN
Name: Date2, dtype: object
print (DF.groupby(['Label','Date']).diff())
Date2
0 NaN
1 1882 days, 0:00:00
2 NaN
3 -515 days, 0:00:00
4 NaN
5 NaN
print (DF.groupby(['Label','Date']).apply(lambda s: s[u'Date2'].diff()))
Label Date
A 1981-03-06 0 NaT
1 1882 days, 0:00:00
1983-11-08 2 NaT
3 -515 days, 0:00:00
B 1977-02-26 4 NaN
1991-09-04 5 NaN
Name: Date2, dtype: object
print (DF.groupby(['Label','Date'])[u'Date2'].transform(pd.Series.diff))
0 None
1 162604800000000000
2 None
3 -44496000000000000
4 NaN
5 NaN
Name: Date2, dtype: object
</code></pre>
<p>EDIT:</p>
<p>If length of group is <code>1</code> and it means has one row, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow"><code>diff</code></a> return <code>NaT</code>:</p>
<pre><code>import pandas as pd
import numpy as np
import io
import datetime as dt
import pandas as pd
dd = [['A','A','A','A','B','B']\
,[dt.date(1981,3,6),dt.date(1981,3,6),dt.date(1983,11,8)\
,dt.date(1983,11,8),dt.date(1977,2,26),dt.date(1991,9,4)]\
,[dt.date(1981,3,6),dt.date(1986,5,1),dt.date(1983,11,8)\
,dt.date(1982,6,11),dt.date(1977,2,26),dt.date(1991,9,4)]]
dd = list(zip(*dd))
DF = pd.DataFrame(dd,columns=['Label','Date', 'Date2'])
DF['Date'] = pd.to_datetime(DF['Date'])
DF['Date2'] = pd.to_datetime(DF['Date2'])
print (DF)
Label Date Date2
0 A 1981-03-06 1981-03-06
1 A 1981-03-06 1986-05-01
2 A 1983-11-08 1983-11-08
3 A 1983-11-08 1982-06-11
4 B 1977-02-26 1977-02-26
5 B 1991-09-04 1991-09-04
</code></pre>
<pre><code>for i, g in DF.groupby(['Label','Date']):
print (g)
print ('diff: ')
print (g[['Date', 'Date2']].diff())
print ('------------')
0 A 1981-03-06 1981-03-06
1 A 1981-03-06 1986-05-01
diff:
Date Date2
0 NaT NaT
1 0 days 1882 days
------------
Label Date Date2
2 A 1983-11-08 1983-11-08
3 A 1983-11-08 1982-06-11
diff:
Date Date2
2 NaT NaT
3 0 days -515 days
------------
Label Date Date2
4 B 1977-02-26 1977-02-26
diff:
Date Date2
4 NaT NaT
------------
Label Date Date2
5 B 1991-09-04 1991-09-04
diff:
Date Date2
5 NaT NaT
------------
print ('*************************')
</code></pre>
<pre><code>for i, g in DF.groupby(['Label','Date2']):
print (g)
print ('diff2: ')
print (g[['Date', 'Date2']].diff())
print ('------------')
Label Date Date2
0 A 1981-03-06 1981-03-06
diff2:
Date Date2
0 NaT NaT
------------
Label Date Date2
3 A 1983-11-08 1982-06-11
diff2:
Date Date2
3 NaT NaT
------------
Label Date Date2
2 A 1983-11-08 1983-11-08
diff2:
Date Date2
2 NaT NaT
------------
Label Date Date2
1 A 1981-03-06 1986-05-01
diff2:
Date Date2
1 NaT NaT
------------
Label Date Date2
4 B 1977-02-26 1977-02-26
diff2:
Date Date2
4 NaT NaT
------------
Label Date Date2
5 B 1991-09-04 1991-09-04
diff2:
Date Date2
5 NaT NaT
------------
</code></pre>
| 1 | 2016-08-11T08:38:36Z | [
"python",
"pandas",
"types"
] |
Combine dataframes on columns containing repeated values | 38,891,019 | <p>I am trying to combine two dataframes which both contain a column of repeated values but not the same number of repeats.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'col1':[1, 1, 2, 2, 3, 3, 3],
'col2':[1.1, 1.3, 2.1, 2.3, 3.1, 3.3, 3.5]})
df2 = pd.DataFrame({'col1':[1, 2, 2, 3, 3, 3],
'col2':[1.2, 2.2, 2.4, 3.2, 3.4, 3.6]})
df1
col1 col2
0 1 1.1
1 1 1.3
2 2 2.1
3 2 2.3
4 3 3.1
5 3 3.3
6 3 3.5
df2
col1 col2
0 1 1.2
1 2 2.2
2 2 2.4
3 3 3.2
4 3 3.4
5 3 3.6
</code></pre>
<p>The desired output would be for example:</p>
<pre><code>desired_result = pd.DataFrame({'col1': [1, 1, 2, 2, 3, 3, 3],
'col2_x':[1.1, 1.3, 2.1, 2.3, 3.1, 3.3, 3.5],
'col2_y':[1.2, 'NaN' , 2.2, 2.4, 3.2, 3.4, 3.6]})
desired_result
col1 col2_x col2_y
0 1 1.1 1.2
1 1 1.3 NaN
2 2 2.1 2.2
3 2 2.3 2.4
4 3 3.1 3.2
5 3 3.3 3.4
6 3 3.5 3.6
</code></pre>
<p>The problem is the ambiguity in how to combine the two dataframes on col1 which contains repeated values and a direct matching is not possible (and also not necessary). </p>
| 1 | 2016-08-11T08:24:02Z | 38,891,554 | <p>You can <code>groupby</code> and horizontal-<code>concat</code> each of the groups. After that, it's just some column/index manipulation:</p>
<pre><code>In [75]: merged = df1.groupby(df1.col1).apply(lambda g: pd.concat([g[['col2']].reset_index(), df2[['col2']][df2.col1 == g.col1.values[0]].reset_index()], axis=1))
In [76]: merged.columns = ['_', 'col2_x', '__', 'col2_y']
In [77]: merged.reset_index()[['col1', 'col2_x', 'col2_y']]
Out[77]:
col1 col2_x col2_y
0 1 1.1 1.2
1 1 1.3 NaN
2 2 2.1 2.2
3 2 2.3 2.4
4 3 3.1 3.2
5 3 3.3 3.4
6 3 3.5 3.6
</code></pre>
| 1 | 2016-08-11T08:48:21Z | [
"python",
"pandas",
"dataframe"
] |
How to create 10 random x, y coordinates in a grid using Python | 38,891,066 | <p>I need to create a 8x8 grid and distribute 10 coins in random positions on the grid. The problem I am facing is that the randint function will sometimes generate the same random co-ordinates and therefore only 9 or 8 coins are generated and placed on the grid. How can I make sure this doesn't happen? Cheers :) This is my code so far:</p>
<pre><code>from random import randint
grid = []
#Create a 8x8 grid
for row in range(8):
grid.append([])
for col in range(8):
grid[row].append("0")
#create 10 random treasure chests
#problem is that it might generate the same co-ordinates and therefore not enough coins
for coins in range(10):
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
while c_x == 7 and c_y == 0:
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
else:
grid[c_x][c_y] = "C"
for row in grid:
print(" ".join(row))
</code></pre>
<p>I have included a while/else - as there must not be a coin in the bottom left corner of the grid</p>
| 3 | 2016-08-11T08:26:14Z | 38,891,133 | <p>You could add another check in your <code>while</code> loop to make sure there is not already a coin at the currently chosen coordinate.
BTW, you could also avoid the checks you already have by changing the range of your <code>randint</code> directly to match your needs.</p>
<p>Or you could generate all possible 7*7=49 coordinates (eliminating the unwanted coordinates) and then pick 10 different at random using the <code>np.random.choice</code> function.</p>
| 1 | 2016-08-11T08:29:43Z | [
"python",
"random",
"coordinates"
] |
How to create 10 random x, y coordinates in a grid using Python | 38,891,066 | <p>I need to create a 8x8 grid and distribute 10 coins in random positions on the grid. The problem I am facing is that the randint function will sometimes generate the same random co-ordinates and therefore only 9 or 8 coins are generated and placed on the grid. How can I make sure this doesn't happen? Cheers :) This is my code so far:</p>
<pre><code>from random import randint
grid = []
#Create a 8x8 grid
for row in range(8):
grid.append([])
for col in range(8):
grid[row].append("0")
#create 10 random treasure chests
#problem is that it might generate the same co-ordinates and therefore not enough coins
for coins in range(10):
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
while c_x == 7 and c_y == 0:
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
else:
grid[c_x][c_y] = "C"
for row in grid:
print(" ".join(row))
</code></pre>
<p>I have included a while/else - as there must not be a coin in the bottom left corner of the grid</p>
| 3 | 2016-08-11T08:26:14Z | 38,891,160 | <p>So you wish to generate 10 random <em>unique</em> coordinates?</p>
<p>You can use a set to verify:</p>
<pre><code>cords_set = set()
while len(cords_set) < 10:
x, y = 7, 0
while (x, y) == (7, 0):
x, y = randint(0, len(grid) - 1), randint(0, len(grid[0]) - 1)
# that will make sure we don't add (7, 0) to cords_set
cords_set.add((x, y))
</code></pre>
<p>This will generate a set of tuples that represent <code>(x, y)</code> coordinates.</p>
<p>A few examples of the output of <code>print(cords_set)</code>:</p>
<pre><code>{(5, 6), (7, 6), (4, 4), (6, 3), (7, 4), (6, 2), (3, 6), (0, 4), (1, 7), (5, 2)}
{(7, 3), (1, 3), (2, 6), (5, 5), (4, 6), (3, 0), (0, 7), (2, 0), (4, 1), (6, 5)}
{(1, 2), (1, 3), (6, 7), (3, 3), (4, 5), (4, 4), (6, 0), (1, 0), (2, 5), (2, 4)}
</code></pre>
| 5 | 2016-08-11T08:30:35Z | [
"python",
"random",
"coordinates"
] |
How to create 10 random x, y coordinates in a grid using Python | 38,891,066 | <p>I need to create a 8x8 grid and distribute 10 coins in random positions on the grid. The problem I am facing is that the randint function will sometimes generate the same random co-ordinates and therefore only 9 or 8 coins are generated and placed on the grid. How can I make sure this doesn't happen? Cheers :) This is my code so far:</p>
<pre><code>from random import randint
grid = []
#Create a 8x8 grid
for row in range(8):
grid.append([])
for col in range(8):
grid[row].append("0")
#create 10 random treasure chests
#problem is that it might generate the same co-ordinates and therefore not enough coins
for coins in range(10):
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
while c_x == 7 and c_y == 0:
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
else:
grid[c_x][c_y] = "C"
for row in grid:
print(" ".join(row))
</code></pre>
<p>I have included a while/else - as there must not be a coin in the bottom left corner of the grid</p>
| 3 | 2016-08-11T08:26:14Z | 38,891,242 | <p>Look at the code below:</p>
<pre><code>from random import randint
grid = []
#Create a 8x8 grid
for row in range(8):
grid.append([])
for col in range(8):
grid[row].append("0")
for coins in range(10):
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
while grid[c_x][c_y] == "C":
c_x = randint(0, len(grid) - 1)
c_y = randint(0, len(grid[0]) - 1)
grid[c_x][c_y] = "C"
</code></pre>
<p>The after generating the coordinates you check to make sure there is no 'C' in place before assigning one to it. If there is you draw again and re-check. If there is not, you assign one and draw the next.</p>
<p>Let me know if this helps âº</p>
| 0 | 2016-08-11T08:34:19Z | [
"python",
"random",
"coordinates"
] |
How to create 10 random x, y coordinates in a grid using Python | 38,891,066 | <p>I need to create a 8x8 grid and distribute 10 coins in random positions on the grid. The problem I am facing is that the randint function will sometimes generate the same random co-ordinates and therefore only 9 or 8 coins are generated and placed on the grid. How can I make sure this doesn't happen? Cheers :) This is my code so far:</p>
<pre><code>from random import randint
grid = []
#Create a 8x8 grid
for row in range(8):
grid.append([])
for col in range(8):
grid[row].append("0")
#create 10 random treasure chests
#problem is that it might generate the same co-ordinates and therefore not enough coins
for coins in range(10):
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
while c_x == 7 and c_y == 0:
c_x = randint(0, len(grid)-1)
c_y = randint(0, len(grid[0])-1)
else:
grid[c_x][c_y] = "C"
for row in grid:
print(" ".join(row))
</code></pre>
<p>I have included a while/else - as there must not be a coin in the bottom left corner of the grid</p>
| 3 | 2016-08-11T08:26:14Z | 38,891,529 | <p>You only have 64 cases, so you can generate all coordinates as tuples (x,y) and then you can use random.sample to directly have 10 unique elements, so you don't have to check or redraw.</p>
<pre><code>import random
from itertools import product
g = [['0' for _ in range(8)] for _ in range(8)]
coord = list(product(range(8), range(8)))
for coins in random.sample(coord, 10):
g[ coins[0] ][ coins[1] ] = 'C'
for row in g:
print(' '.join(row))
</code></pre>
| 5 | 2016-08-11T08:47:04Z | [
"python",
"random",
"coordinates"
] |
How to raise error for unbalanced braces, when parsing using PLY? | 38,891,196 | <p>I have a lexer, written with <a href="http://www.dabeaz.com/ply/ply.html" rel="nofollow">ply</a>.
Lexer has two states: string and macros. Macros is a special expression put in curly braces. Lexer is very simple:</p>
<pre><code>states = (
('macro', 'exclusive'),
)
t_STRING = [^{] # any char but curly brace
def t_lcurlybrace(t):
r'{'
t.lexer.begin('macro')
... some other tokens for macro state
def t_macro_rcurlybrace(t):
r'}'
t.lexer.begin('INITIAL')
</code></pre>
<p>So basically it works like this:</p>
<pre><code>Two plus two is {2 + 2}
</code></pre>
<p>Lexer produces tokens like STRING, NUMBER, OPERATOR, NUMBER for this line.</p>
<p>But I'm stuck with error handling. If input is </p>
<pre><code>Two plus two is {2 + 2
</code></pre>
<p>lexer produces the same stream of tokens as before. The only difference is the state of lexer in the end (macro, not INITIAL).</p>
<p>I want to raise an error in such case, but I can't find any built in hooks in lex for such task. Now my guess is to wrap a lexer in a wrapper, which will check the state of the lexer, when all input is consumed.</p>
<p><strong>UPDATE:</strong></p>
<p>I tried to use t_eof like this:
def t_eof(t):
if t.lexer.current_state() != 'INITIAL':
raise Exception('Unbalanced brackets')</p>
<p>but it didn't work.</p>
<p><strong>UPDATE2:</strong></p>
<p>t_eof must be defined as t_macro_eof, as EOF is reached during "macro" state,
so it can be done like:</p>
<pre><code>def t_macro_eof(t):
raise Exception('Unbalanced brackets')
</code></pre>
| 0 | 2016-08-11T08:31:48Z | 38,900,330 | <p>You can check the state in the <a href="http://www.dabeaz.com/ply/ply.html#ply_nn14" rel="nofollow">EOF handler</a></p>
| 0 | 2016-08-11T15:19:46Z | [
"python",
"ply"
] |
while executing a py file encountering an error at module importing | 38,891,307 | <p>Please help me on this, getting the following error,</p>
<blockquote>
<p>Traceback (most recent call last):
File "abdm.py", line 9, in
from core.api import rest_api
File "D:\Mydev\Development\abdm\core\api.py", line 3, in
from core import data, tasks</p>
</blockquote>
<p>here are the code and the directory path</p>
<pre><code>from gevent import monkey
monkey.patch_all()
from flask import Flask
from flask_socketio import SocketIO
from core.api import rest_api
from core.signals import task_added, task_completed,
worker_before_execution, worker_after_execution, task_deleted
from core.commands import command_manager
import settings
</code></pre>
<p>Directory path:</p>
<ul>
<li>abdm
<ul>
<li>Core
<ul>
<li><strong>init</strong>.py</li>
<li>api.py</li>
</ul></li>
<li>abdm.py</li>
</ul></li>
</ul>
<p>I'm using Python 3.5. Any help would be appreciated.</p>
<p>Here is the stracktrace:</p>
<pre><code>Exception in user code:
------------------------------------------------------------
Traceback (most recent call last):
File "abdm.py", line 10, in <module>
from core.api import rest_api
File "D:\abdm\Development\abdm\core\api.py", line 3, in <module>
from core import data, tasks
File "D:\abdm\Development\abdm\core\tasks.py", line 14, in <module>
from gams import *
File "D:\Installation\Program Files\Python35\lib\site-packages\gams\__init__.py", line 8, in <module>
from .workspace import *
ImportError: DLL load failed: The specified module could not be found.
------------------------------------------------------------
D:\Installation\Program Files\Python35\lib\site-packages\flask\exthook.py:71: ExtDeprecationWarning: Importing flask.ext.script is deprecated, use fla
sk_script instead.
.format(x=modname), ExtDeprecationWarning
Traceback (most recent call last):
File "abdm.py", line 18, in <module>
from core.commands import command_manager
File "D:\abdm\Development\abdm\core\commands.py", line 5, in <module>
from core.tasks import GamsWorker, ResultCollector
File "D:\abdm\Development\abdm\core\tasks.py", line 14, in <module>
from gams import *
File "D:\Installation\Program Files\Python35\lib\site-packages\gams\__init__.py", line 8, in <module>
from .workspace import *
ImportError: DLL load failed: The specified module could not be found.
</code></pre>
| -4 | 2016-08-11T08:37:25Z | 39,095,127 | <p>So, the issue is GAMS doesn't support Python 3.5.</p>
<p>Thanks for your help guys.</p>
| 0 | 2016-08-23T07:38:37Z | [
"python",
"python-2.7",
"python-3.x",
"gams-math"
] |
how to initialize and fill list of lists in python 2.7 | 38,891,457 | <p>I need to have a list of lists like mentioned below :-</p>
<pre><code>some_name = [(statement, sentiment),
(statement, sentiment),
...
...
...
]
</code></pre>
<p>accessing them is fine, but how to fill them up with two different lists namely statement and sentiment.</p>
| -1 | 2016-08-11T08:44:13Z | 38,891,570 | <p>You can use list comprehension and <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a>:</p>
<pre><code>some_name = [(statement, sentiment) for statement, sentiment
in zip(statements_list, sentiment_list)]
</code></pre>
<p><strong>EDIT</strong> In Python 2 you don't need to iterate over the return value of <code>zip</code>, so this will suffice:</p>
<pre><code>some_name = zip(statements_list, sentiment_list)
</code></pre>
| 1 | 2016-08-11T08:49:16Z | [
"python",
"list",
"python-2.7"
] |
Create dictionary from another dictionary with the fastest and scalable way | 38,891,514 | <p>I have few scenarios to create a new dictionary:</p>
<ol>
<li>only take those dictionary in list with key 'total' is not zero</li>
<li>delete keys from dictionary e.g 'total' and 'rank'</li>
<li>use the 'name' key value as key and 'game' key value as list of<br>
values in the new dict</li>
<li>sort the list of values in new dict</li>
</ol>
<p>My code is:</p>
<pre><code># input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
</code></pre>
<p>Output of my code:</p>
<pre><code>{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
</code></pre>
<p>Expected result:</p>
<pre><code>{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
</code></pre>
<p>Is there a faster way to get the result, or can I use some python builtin function to handle this scenario?</p>
| 3 | 2016-08-11T08:46:23Z | 38,891,673 | <p>You can try:</p>
<pre><code>data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
final_dict={}
for single_data in data:
if single_data['total'] > 0:
if single_data['name'] in final_dict:
final_dict[single_data['name']].append(single_data['game'])
else:
final_dict[single_data['name']]=[single_data['game']]
print final_dict
</code></pre>
<p>Output:</p>
<pre><code>{'foo': ['football', 'cricket'], 'bar': ['cricket']}
</code></pre>
| 1 | 2016-08-11T08:54:14Z | [
"python",
"python-2.7",
"python-3.x"
] |
Create dictionary from another dictionary with the fastest and scalable way | 38,891,514 | <p>I have few scenarios to create a new dictionary:</p>
<ol>
<li>only take those dictionary in list with key 'total' is not zero</li>
<li>delete keys from dictionary e.g 'total' and 'rank'</li>
<li>use the 'name' key value as key and 'game' key value as list of<br>
values in the new dict</li>
<li>sort the list of values in new dict</li>
</ol>
<p>My code is:</p>
<pre><code># input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
</code></pre>
<p>Output of my code:</p>
<pre><code>{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
</code></pre>
<p>Expected result:</p>
<pre><code>{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
</code></pre>
<p>Is there a faster way to get the result, or can I use some python builtin function to handle this scenario?</p>
| 3 | 2016-08-11T08:46:23Z | 38,891,676 | <p>You could really simplify this as there is no need to modify the existing dictionary. It's usually a lot cleaner to leave the original data structure alone and build a new one as the result.</p>
<pre><code>data = [
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result = {}
for e in data:
if e["total"]:
name = e["name"]
if name not in result:
result[name] = []
result[name].append(e["game"])
print result
</code></pre>
<p>The result is <code>{'foo': ['football', 'cricket'], 'bar': ['cricket']}</code> which is what you're looking for.</p>
| 2 | 2016-08-11T08:54:23Z | [
"python",
"python-2.7",
"python-3.x"
] |
Create dictionary from another dictionary with the fastest and scalable way | 38,891,514 | <p>I have few scenarios to create a new dictionary:</p>
<ol>
<li>only take those dictionary in list with key 'total' is not zero</li>
<li>delete keys from dictionary e.g 'total' and 'rank'</li>
<li>use the 'name' key value as key and 'game' key value as list of<br>
values in the new dict</li>
<li>sort the list of values in new dict</li>
</ol>
<p>My code is:</p>
<pre><code># input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
</code></pre>
<p>Output of my code:</p>
<pre><code>{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
</code></pre>
<p>Expected result:</p>
<pre><code>{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
</code></pre>
<p>Is there a faster way to get the result, or can I use some python builtin function to handle this scenario?</p>
| 3 | 2016-08-11T08:46:23Z | 38,891,684 | <p>if I understand your requirements well, this should do it:</p>
<pre><code>names = set(x['name'] for x in data)
{name: sorted(list(set(x['game'] for x in data if (x['total']>0 and x['name']==name)))) for name in names}
</code></pre>
| 0 | 2016-08-11T08:55:04Z | [
"python",
"python-2.7",
"python-3.x"
] |
Create dictionary from another dictionary with the fastest and scalable way | 38,891,514 | <p>I have few scenarios to create a new dictionary:</p>
<ol>
<li>only take those dictionary in list with key 'total' is not zero</li>
<li>delete keys from dictionary e.g 'total' and 'rank'</li>
<li>use the 'name' key value as key and 'game' key value as list of<br>
values in the new dict</li>
<li>sort the list of values in new dict</li>
</ol>
<p>My code is:</p>
<pre><code># input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
</code></pre>
<p>Output of my code:</p>
<pre><code>{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
</code></pre>
<p>Expected result:</p>
<pre><code>{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
</code></pre>
<p>Is there a faster way to get the result, or can I use some python builtin function to handle this scenario?</p>
| 3 | 2016-08-11T08:46:23Z | 38,891,736 | <p>Addition to other answers, if you add a <code>result_data={}</code> inside <code>for my_dict in dict_without_total:</code>, it should work fine.</p>
<pre><code>for my_dict in dict_without_total:
result_data={}
....rest of the code...
</code></pre>
<p><code>result_data</code> is not getting reinitialized at each iteration which is the issue. </p>
| 0 | 2016-08-11T08:58:04Z | [
"python",
"python-2.7",
"python-3.x"
] |
Create dictionary from another dictionary with the fastest and scalable way | 38,891,514 | <p>I have few scenarios to create a new dictionary:</p>
<ol>
<li>only take those dictionary in list with key 'total' is not zero</li>
<li>delete keys from dictionary e.g 'total' and 'rank'</li>
<li>use the 'name' key value as key and 'game' key value as list of<br>
values in the new dict</li>
<li>sort the list of values in new dict</li>
</ol>
<p>My code is:</p>
<pre><code># input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
</code></pre>
<p>Output of my code:</p>
<pre><code>{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
</code></pre>
<p>Expected result:</p>
<pre><code>{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
</code></pre>
<p>Is there a faster way to get the result, or can I use some python builtin function to handle this scenario?</p>
| 3 | 2016-08-11T08:46:23Z | 38,891,739 | <p>Another solution:</p>
<p>To create the dictionary you want:</p>
<pre><code>from collections import defaultdict
d2 = defaultdict(set)
[d2[d["name"]].add(d["game"]) for d in data if d["total"] > 0]
</code></pre>
<p>To sort the keys:</p>
<pre><code>for key in d2.keys(): d2[key] = sorted(list(d2[key]))
</code></pre>
| 0 | 2016-08-11T08:58:15Z | [
"python",
"python-2.7",
"python-3.x"
] |
Create dictionary from another dictionary with the fastest and scalable way | 38,891,514 | <p>I have few scenarios to create a new dictionary:</p>
<ol>
<li>only take those dictionary in list with key 'total' is not zero</li>
<li>delete keys from dictionary e.g 'total' and 'rank'</li>
<li>use the 'name' key value as key and 'game' key value as list of<br>
values in the new dict</li>
<li>sort the list of values in new dict</li>
</ol>
<p>My code is:</p>
<pre><code># input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
</code></pre>
<p>Output of my code:</p>
<pre><code>{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
</code></pre>
<p>Expected result:</p>
<pre><code>{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
</code></pre>
<p>Is there a faster way to get the result, or can I use some python builtin function to handle this scenario?</p>
| 3 | 2016-08-11T08:46:23Z | 38,892,608 | <p>You can also go for pandas (alternative approach):</p>
<pre><code>import pandas as pd
df = pd.DataFrame([i for i in data if i['total']])
{k: g['game'].tolist() for k,g in df.groupby('name')}
#Out[178]: {'bar': ['cricket'], 'foo': ['football', 'cricket']}
</code></pre>
| 0 | 2016-08-11T09:37:29Z | [
"python",
"python-2.7",
"python-3.x"
] |
Feature Selection | 38,891,600 | <p>I tried to do recursive feature selection in scikit learn with following code.</p>
<pre><code>from sklearn import datasets, svm
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.feature_selection import RFE
import numpy as np
input_file_iris = "/home/anuradha/Project/NSL_KDD_master/Modified/iris.csv"
dataset = np.loadtxt(input_file_iris, delimiter=",")
X = dataset[:,0:4]
y = dataset[:,4]
estimator= svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1)
selector = RFE(estimator,3, step=1)
selector = selector.fit(X,y)
</code></pre>
<p>But it gives following error</p>
<pre><code>Traceback (most recent call last):
File "/home/anuradha/PycharmProjects/LearnPython/Scikit-learn/univariate.py", line 30, in <module>
File "/usr/local/lib/python2.7/dist-packages/sklearn/feature_selection/rfe.py", line 131, in fit
return self._fit(X, y)
File "/usr/local/lib/python2.7/dist-packages/sklearn/feature_selection/rfe.py", line 182, in _fit
raise RuntimeError('The classifier does not expose '
RuntimeError: The classifier does not expose "coef_" or
"feature_importances_" attributes
</code></pre>
<p>Please some one can help me to solve this or guide me to another solution</p>
| 2 | 2016-08-11T08:51:17Z | 38,901,203 | <p>Change your kernel to <strong>linear</strong> and your code would work.</p>
<p>Besides, <code>svm.OneClassSVM</code> is used for unsupervised outlier detection. Are you sure that you want to use it as estimator? Or perhaps you want to use <code>svm.SVC()</code>. Look the following link for documentation. </p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.OneClassSVM.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.svm.OneClassSVM.html</a></p>
<p>Lastly, iris data set is already available in sklearn. You have imported the <code>sklearn.datasets</code>. So you can simply load iris as:</p>
<pre><code>iris = datasets.load_iris()
X = iris.data
y = iris.target
</code></pre>
| 2 | 2016-08-11T16:01:44Z | [
"python",
"scikit-learn",
"feature-selection"
] |
How to optimize sorting program in Python? | 38,891,655 | <p>I need to write a program that takes a list of strings containing integers and words and returns a sorted version of the list. The output should maintain the positions of strings and numbers as they appeared in the original string.</p>
<pre><code>data=raw_input("Enter data").split(" ")
alpha=[]
num=[]
for item in data:
if item.isalpha():
alpha.append(item)
else:
num.append(item)
alpha.sort()
num.sort()
i=0
j=0
result=""
for item in data :
if item.isalpha():
result +=alpha[i]+" "
i +=1
else:
result +=num[j]+" "
j +=1
print result
</code></pre>
<p>Above code is working fine for me, but I want to use minimum memory. <strong>How can I reduce the above code and get the correct result with a single list and least iteration?</strong></p>
<p><strong>input</strong></p>
<blockquote>
<p>car truck 8 4 bus 6 1</p>
</blockquote>
<p><strong>output</strong></p>
<blockquote>
<p>bus car 1 4 truck 6 8</p>
</blockquote>
| 2 | 2016-08-11T08:53:45Z | 38,892,162 | <p>You can't avoid having to sort twice, or create <em>some kind of mapping</em> for the number positions here. Either partition, sort the partitions, and re-assemble based on the types in the original word list (as you did), or resort a sorted word list based on a type position map.</p>
<p>To create a type position map, you record 'type' positions first (where the difference is determined using <code>str.digit()</code>). You can then sort all words regardless of type, then <em>re</em>sort based on the type map:</p>
<pre><code>type_map = {}
words = line.split()
for i, word in enumerate(words):
type_map.setdefault(word.isdigit(), []).append(i)
# sort keys
# sort digits as numbers (natural sort)
int_for_digits = lambda w: int(w) if w.isdigit() else w
# sort specific types to the next position for that type
type_to_pos = lambda w, m={k: iter(v) for k, v in type_map.items()}: next(m[w.isdigit()])
sorted_line = sorted(sorted(words, key=int_for_digits), key=type_to_pos)
</code></pre>
<p>Note that the <code>type_to_pos</code> lambda creates a map from 'type' (<code>str.isdigit()</code> outcome) to position <em>iterators</em>, and these are going to be exhausted after sorting. Make sure you create the lambda anew each time you need to sort the same line.</p>
<p>I also incorporated a natural sort to ensure that <code>10</code> is sorted after <code>9</code>, not before as a lexicographical sort on strings would do.</p>
<p>Demo:</p>
<pre><code>>>> line = 'car truck 8 4 bus 6 1'
>>> type_map = {}
>>> words = line.split()
>>> for i, word in enumerate(words):
... type_map.setdefault(word.isdigit(), []).append(i)
...
>>> int_for_digits = lambda w: int(w) if w.isdigit() else w
>>> type_to_pos = lambda w, m={k: iter(v) for k, v in type_map.items()}: next(m[w.isdigit()])
>>> sorted(sorted(words, key=int_for_digits), key=type_to_pos)
['bus', 'car', '1', '4', 'truck', '6', '8']
</code></pre>
<p>There is no real difference in memory use between this and yours; both solutions require creating some additional lists (with a total length equal that of number of words).</p>
| 2 | 2016-08-11T09:16:19Z | [
"python",
"sorting"
] |
How to optimize sorting program in Python? | 38,891,655 | <p>I need to write a program that takes a list of strings containing integers and words and returns a sorted version of the list. The output should maintain the positions of strings and numbers as they appeared in the original string.</p>
<pre><code>data=raw_input("Enter data").split(" ")
alpha=[]
num=[]
for item in data:
if item.isalpha():
alpha.append(item)
else:
num.append(item)
alpha.sort()
num.sort()
i=0
j=0
result=""
for item in data :
if item.isalpha():
result +=alpha[i]+" "
i +=1
else:
result +=num[j]+" "
j +=1
print result
</code></pre>
<p>Above code is working fine for me, but I want to use minimum memory. <strong>How can I reduce the above code and get the correct result with a single list and least iteration?</strong></p>
<p><strong>input</strong></p>
<blockquote>
<p>car truck 8 4 bus 6 1</p>
</blockquote>
<p><strong>output</strong></p>
<blockquote>
<p>bus car 1 4 truck 6 8</p>
</blockquote>
| 2 | 2016-08-11T08:53:45Z | 38,892,432 | <pre><code>data = raw_input("Enter data:\n").split()
alphas = sorted([x for x in data if x.isalpha()])
numbers = sorted([x for x in data if not x.isalpha()], key=int)
output = ' '.join(alphas.pop(0) if x.isalpha() else numbers.pop(0) for x in data)
print(output)
</code></pre>
| 0 | 2016-08-11T09:28:58Z | [
"python",
"sorting"
] |
How to optimize sorting program in Python? | 38,891,655 | <p>I need to write a program that takes a list of strings containing integers and words and returns a sorted version of the list. The output should maintain the positions of strings and numbers as they appeared in the original string.</p>
<pre><code>data=raw_input("Enter data").split(" ")
alpha=[]
num=[]
for item in data:
if item.isalpha():
alpha.append(item)
else:
num.append(item)
alpha.sort()
num.sort()
i=0
j=0
result=""
for item in data :
if item.isalpha():
result +=alpha[i]+" "
i +=1
else:
result +=num[j]+" "
j +=1
print result
</code></pre>
<p>Above code is working fine for me, but I want to use minimum memory. <strong>How can I reduce the above code and get the correct result with a single list and least iteration?</strong></p>
<p><strong>input</strong></p>
<blockquote>
<p>car truck 8 4 bus 6 1</p>
</blockquote>
<p><strong>output</strong></p>
<blockquote>
<p>bus car 1 4 truck 6 8</p>
</blockquote>
| 2 | 2016-08-11T08:53:45Z | 38,893,110 | <p>This Python 2 / Python 3 code uses a similar algorithm to yours, but it avoids the retesting of data types when building the result string.</p>
<p>It creates a list <code>dtypes</code> that stores the datatypes of the items as references to the destination lists <code>alpha</code> and <code>num</code>. This simplifies the process of putting the sorted items back into the correct sequence. </p>
<p>We use reversed sorts so that we can <code>.pop()</code> the desired items off the ends of their lists. This is more efficient than using <code>.pop(0)</code>, since popping items from the front of a list requires all the subsequent items to be moved down every time we pop.</p>
<pre><code>from __future__ import print_function
def parallel_sort(data):
''' sort numeric & non-numeric items in str `data` in parallel,
keeping numeric values in the original numeric slots
and alpha values in the original alpha slots
'''
data = data.split()
alpha = []
num = []
dtypes = [num if item.isdigit() else alpha for item in data]
for lst, item in zip(dtypes, data):
lst.append(item)
alpha.sort(reverse=True)
num.sort(key=int, reverse=True)
return ' '.join([lst.pop() for lst in dtypes])
# Test
strings = (
'car truck 8 4 bus 6 1',
'9 2 car bus 297',
'dog ape 1 12 333 emu cat 7 32 zebra bat',
)
for data in strings:
result = parallel_sort(data)
print('{!r} -> {!r}'.format(data, result))
</code></pre>
<p><strong>output</strong></p>
<pre><code>'car truck 8 4 bus 6 1' -> 'bus car 1 4 truck 6 8'
'9 2 car bus 297' -> '2 9 bus car 297'
'dog ape 1 12 333 emu cat 7 32 zebra bat' -> 'ape bat 1 7 12 cat dog 32 333 emu zebra'
</code></pre>
<hr>
<p>Here's some <code>timeit</code> code to compare the speeds of the various algorithms. For small strings, piyush's code (modified to sort numbers correctly) is the fastest, but for sufficiently large strings my code is a little faster.</p>
<p>These tests were performed on an old 2GHz Pentium 4 machine running Python 2.6 (I had to modify Martijn's code because 2,6 doesn't have dictionary comprehensions).</p>
<pre><code>from __future__ import print_function
from timeit import Timer
def parallel_sort_piyush(data):
data = data.split()
alpha=[]
num=[]
for item in data:
if item.isalpha():
alpha.append(item)
else:
num.append(item)
alpha.sort()
num.sort(key=int)
i = 0
j = 0
result = ""
for item in data :
if item.isalpha():
result += alpha[i] + " "
i +=1
else:
result += num[j] + " "
j +=1
return result[:-1]
def parallel_sort_acw1668(data):
data = data.split()
alphas = sorted([x for x in data if x.isalpha()])
numbers = sorted([x for x in data if not x.isalpha()], key=int)
return ' '.join(alphas.pop(0) if x.isalpha() else numbers.pop(0) for x in data)
def parallel_sort_martijn(line):
type_map = {}
words = line.split()
for i, word in enumerate(words):
type_map.setdefault(word.isdigit(), []).append(i)
# sort keys
# sort digits as numbers (natural sort)
int_for_digits = lambda w: int(w) if w.isdigit() else w
# sort specific types to the next position for that type
#type_to_pos = lambda w, m={k: iter(v) for k, v in type_map.items()}: next(m[w.isdigit()])
type_to_pos = lambda w, m=dict((k, iter(v)) for k, v in type_map.items()): next(m[w.isdigit()])
return ' '.join(sorted(sorted(words, key=int_for_digits), key=type_to_pos))
def parallel_sort_PM2R(data):
''' sort numeric & non-numeric items in str `data` in parallel,
keeping numeric values in the original numeric slots
and alpha values in the original alpha slots
'''
data = data.split()
alpha = []
num = []
dtypes = [num if item.isdigit() else alpha for item in data]
for lst, item in zip(dtypes, data):
lst.append(item)
alpha.sort(reverse=True)
num.sort(key=int, reverse=True)
return ' '.join([lst.pop() for lst in dtypes])
funcs = (
parallel_sort_piyush,
parallel_sort_acw1668,
parallel_sort_martijn,
parallel_sort_PM2R,
)
strings = (
'car truck 8 4 bus 6 1',
'9 2 car bus 297',
'dog ape 1 12 333 emu cat 7 32 zebra bat',
'only alpha words',
'42 23 17 5',
'',
)
def test():
for parallel_sort in funcs:
print(parallel_sort.__name__)
for data in strings:
result = parallel_sort(data)
print('{0!r} -> {1!r}'.format(data, result))
print()
def verify():
for data in strings:
result = [parallel_sort(data) for parallel_sort in funcs]
r = result[0]
ok = all(s == r for s in result[1:])
print('{0}: {1!r} -> {2!r}'.format(ok, data, r))
# Time tests
def time_test(loops, reps):
''' Print timing stats for all the functions '''
timings = []
for func in funcs:
fname = func.__name__
setup = 'from __main__ import datastring, ' + fname
cmd = fname + '(datastring)'
t = Timer(cmd, setup)
result = t.repeat(reps, loops)
result.sort()
timings.append((result, fname))
timings.sort()
for result, fname in timings:
print('{0:21} {1}'.format(fname, result))
#test()
verify()
reps = 3
loops = 5000
for datastring in strings:
print('\n{0!r}'.format(datastring))
time_test(loops, reps)
print('\n' + '- ' * 32)
datastring = ' '.join(strings * 3)
reps = 3
loops = 256
for i in range(7):
print('\nlength={0}, loops{1}'.format(len(datastring), loops))
time_test(loops, reps)
loops >>= 1
datastring += datastring
</code></pre>
<p><strong>output</strong></p>
<pre><code>True: 'car truck 8 4 bus 6 1' -> 'bus car 1 4 truck 6 8'
True: '9 2 car bus 297' -> '2 9 bus car 297'
True: 'dog ape 1 12 333 emu cat 7 32 zebra bat' -> 'ape bat 1 7 12 cat dog 32 333 emu zebra'
True: 'only alpha words' -> 'alpha only words'
True: '42 23 17 5' -> '5 17 23 42'
True: '' -> ''
'car truck 8 4 bus 6 1'
parallel_sort_piyush [0.16613292694091797, 0.1678168773651123, 0.17213606834411621]
parallel_sort_PM2R [0.19424915313720703, 0.19544506072998047, 0.1982269287109375]
parallel_sort_acw1668 [0.26951003074645996, 0.27229499816894531, 0.2791450023651123]
parallel_sort_martijn [0.38483405113220215, 0.39478588104248047, 0.41512084007263184]
'9 2 car bus 297'
parallel_sort_piyush [0.12851309776306152, 0.1293489933013916, 0.13681578636169434]
parallel_sort_PM2R [0.16056299209594727, 0.16071605682373047, 0.16141486167907715]
parallel_sort_acw1668 [0.22338008880615234, 0.22396492958068848, 0.22573399543762207]
parallel_sort_martijn [0.31512093544006348, 0.31612205505371094, 0.3207099437713623]
'dog ape 1 12 333 emu cat 7 32 zebra bat'
parallel_sort_piyush [0.22555994987487793, 0.22738313674926758, 0.2362220287322998]
parallel_sort_PM2R [0.2644810676574707, 0.26884698867797852, 0.30507016181945801]
parallel_sort_acw1668 [0.34023594856262207, 0.3423771858215332, 0.34470510482788086]
parallel_sort_martijn [0.49398708343505859, 0.49546003341674805, 0.50142598152160645]
'only alpha words'
parallel_sort_piyush [0.069504022598266602, 0.06974482536315918, 0.077678918838500977]
parallel_sort_PM2R [0.097023963928222656, 0.10160112380981445, 0.10884809494018555]
parallel_sort_acw1668 [0.16136789321899414, 0.16139507293701172, 0.16254186630249023]
parallel_sort_martijn [0.20757603645324707, 0.20803117752075195, 0.21358394622802734]
'42 23 17 5'
parallel_sort_piyush [0.12735700607299805, 0.13022804260253906, 0.13068699836730957]
parallel_sort_PM2R [0.14782595634460449, 0.14879608154296875, 0.14986395835876465]
parallel_sort_acw1668 [0.2091820240020752, 0.21131205558776855, 0.21974492073059082]
parallel_sort_martijn [0.27461814880371094, 0.27850794792175293, 0.27975988388061523]
''
parallel_sort_piyush [0.024302959442138672, 0.024441957473754883, 0.031994104385375977]
parallel_sort_PM2R [0.046028852462768555, 0.046576023101806641, 0.046601057052612305]
parallel_sort_acw1668 [0.091669082641601562, 0.091941118240356445, 0.092013120651245117]
parallel_sort_martijn [0.094310998916625977, 0.094748973846435547, 0.095381021499633789]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
length=320, loops256
parallel_sort_PM2R [0.086880922317504883, 0.087455987930297852, 0.087592840194702148]
parallel_sort_piyush [0.089211940765380859, 0.089900970458984375, 0.10294389724731445]
parallel_sort_acw1668 [0.1074371337890625, 0.10886883735656738, 0.11089897155761719]
parallel_sort_martijn [0.15668392181396484, 0.15747618675231934, 0.15912413597106934]
length=640, loops128
parallel_sort_PM2R [0.086150884628295898, 0.088001012802124023, 0.091377019882202148]
parallel_sort_piyush [0.088989019393920898, 0.089003086090087891, 0.095314979553222656]
parallel_sort_acw1668 [0.10632085800170898, 0.10663104057312012, 0.10766291618347168]
parallel_sort_martijn [0.15318799018859863, 0.1544189453125, 0.1579129695892334]
length=1280, loops64
parallel_sort_PM2R [0.086312055587768555, 0.08635711669921875, 0.08643794059753418]
parallel_sort_piyush [0.089561939239501953, 0.089729070663452148, 0.09730219841003418]
parallel_sort_acw1668 [0.10796380043029785, 0.10807299613952637, 0.10920286178588867]
parallel_sort_martijn [0.15214014053344727, 0.15265083312988281, 0.1530609130859375]
length=2560, loops32
parallel_sort_PM2R [0.086397886276245117, 0.086937904357910156, 0.12731385231018066]
parallel_sort_piyush [0.090615034103393555, 0.091663837432861328, 0.1024620532989502]
parallel_sort_acw1668 [0.11186099052429199, 0.113922119140625, 0.11545681953430176]
parallel_sort_martijn [0.1525418758392334, 0.15349197387695312, 0.15409398078918457]
length=5120, loops16
parallel_sort_PM2R [0.086872100830078125, 0.089444875717163086, 0.092289924621582031]
parallel_sort_piyush [0.09121394157409668, 0.092126131057739258, 0.099750041961669922]
parallel_sort_acw1668 [0.11780095100402832, 0.11782479286193848, 0.11829781532287598]
parallel_sort_martijn [0.1548459529876709, 0.1556861400604248, 0.16153383255004883]
length=10240, loops8
parallel_sort_PM2R [0.087334871292114258, 0.091704845428466797, 0.092611074447631836]
parallel_sort_piyush [0.092457056045532227, 0.11381292343139648, 0.11914896965026855]
parallel_sort_acw1668 [0.13423800468444824, 0.14225006103515625, 0.14964199066162109]
parallel_sort_martijn [0.15410614013671875, 0.15437102317810059, 0.15663385391235352]
length=20480, loops4
parallel_sort_PM2R [0.089828014373779297, 0.089951992034912109, 0.091377973556518555]
parallel_sort_piyush [0.093550920486450195, 0.093831062316894531, 0.10358881950378418]
parallel_sort_martijn [0.15582108497619629, 0.15685820579528809, 0.15839505195617676]
parallel_sort_acw1668 [0.15901684761047363, 0.15937495231628418, 0.16479396820068359]
</code></pre>
<p>And here's the <code>timeit</code> output running on Python 3.6; I couldn't run Martijn's code because it uses a Python 2 feature which is not supported on Python 3 (the ability to compare strings & integers).</p>
<pre><code>'car truck 8 4 bus 6 1'
parallel_sort_piyush [0.1639411759988434, 0.1641379140000936, 0.16782489100114617]
parallel_sort_PM2R [0.19857631000013498, 0.20035489499969117, 0.20133615400118288]
parallel_sort_acw1668 [0.23366880700086767, 0.23590722699918842, 0.23592727899995225]
'9 2 car bus 297'
parallel_sort_piyush [0.13465033200009202, 0.13776905200029432, 0.18482623500131012]
parallel_sort_PM2R [0.17675577999943926, 0.17687105299955874, 0.17699695900046208]
parallel_sort_acw1668 [0.1984550399993168, 0.2004171780008619, 0.20442987299975357]
'dog ape 1 12 333 emu cat 7 32 zebra bat'
parallel_sort_piyush [0.23316595300093468, 0.23489147600048454, 0.23842128900105308]
parallel_sort_PM2R [0.26679581300049904, 0.3011208970001462, 0.3172619519991713]
parallel_sort_acw1668 [0.3200034309993498, 0.3352665239999624, 0.33631655700082774]
'only alpha words'
parallel_sort_piyush [0.09549654300099064, 0.09623185599957651, 0.10429198799829464]
parallel_sort_PM2R [0.13186385899825837, 0.13212396900053136, 0.13451194299886993]
parallel_sort_acw1668 [0.1535412909997831, 0.1543631849999656, 0.15927939099856303]
'42 23 17 5'
parallel_sort_piyush [0.11825022300035926, 0.11878074699961871, 0.1252167599996028]
parallel_sort_PM2R [0.1604483920000348, 0.16769106699939584, 0.1691959849995328]
parallel_sort_acw1668 [0.18632163399888668, 0.1896887399998377, 0.1903514539990283]
''
parallel_sort_piyush [0.02776817599988135, 0.028196225999636226, 0.03495696800018777]
parallel_sort_PM2R [0.08110263499838766, 0.08155031299975235, 0.08626208599889651]
parallel_sort_acw1668 [0.0864310500001011, 0.09174712499952875, 0.09336608200101182]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
length=320, loops256
parallel_sort_PM2R [0.07467737899969507, 0.0790010450000409, 0.08554027799982578]
parallel_sort_piyush [0.08288037499914935, 0.0869976689991745, 0.08999215999938315]
parallel_sort_acw1668 [0.09541546199943696, 0.09584146999986842, 0.10051055599979009]
length=640, loops128
parallel_sort_PM2R [0.07285131699973135, 0.07332802500059188, 0.0734102949991211]
parallel_sort_piyush [0.08446464299959189, 0.08626877000097011, 0.0912491470007808]
parallel_sort_acw1668 [0.09565138899961312, 0.09577698600151052, 0.1005053829994722]
length=1280, loops64
parallel_sort_PM2R [0.0734182439991855, 0.07344354999986535, 0.07376041499992425]
parallel_sort_piyush [0.08504722700126877, 0.08517580999978236, 0.09426504600014596]
parallel_sort_acw1668 [0.09750029599854315, 0.09771097199882206, 0.098332843001117]
length=2560, loops32
parallel_sort_PM2R [0.0732510199995886, 0.07328447399959259, 0.0746706619993347]
parallel_sort_piyush [0.08774417499989795, 0.08785101400098938, 0.09428778500114277]
parallel_sort_acw1668 [0.10173674399993615, 0.103946167999311, 0.11013430999992124]
length=5120, loops16
parallel_sort_PM2R [0.07310179399974004, 0.07344265099891345, 0.07423899999957939]
parallel_sort_piyush [0.08817732100033027, 0.0979379299988068, 0.10110497500136262]
parallel_sort_acw1668 [0.10930270000062592, 0.11099402399850078, 0.11111589400024968]
length=10240, loops8
parallel_sort_PM2R [0.0742019289991731, 0.0743915310013108, 0.08267202100068971]
parallel_sort_piyush [0.0880410829995526, 0.08827138900051068, 0.09606961099962064]
parallel_sort_acw1668 [0.12271693899856473, 0.1237988149987359, 0.1242337999992742]
length=20480, loops4
parallel_sort_PM2R [0.07891896799992537, 0.08560944000055315, 0.09119457000088005]
parallel_sort_piyush [0.08942042499984382, 0.0914211269991938, 0.0983720500007621]
parallel_sort_acw1668 [0.15465029900042282, 0.17178430700005265, 0.1722458230015036]
</code></pre>
| 3 | 2016-08-11T09:59:02Z | [
"python",
"sorting"
] |
How to optimize sorting program in Python? | 38,891,655 | <p>I need to write a program that takes a list of strings containing integers and words and returns a sorted version of the list. The output should maintain the positions of strings and numbers as they appeared in the original string.</p>
<pre><code>data=raw_input("Enter data").split(" ")
alpha=[]
num=[]
for item in data:
if item.isalpha():
alpha.append(item)
else:
num.append(item)
alpha.sort()
num.sort()
i=0
j=0
result=""
for item in data :
if item.isalpha():
result +=alpha[i]+" "
i +=1
else:
result +=num[j]+" "
j +=1
print result
</code></pre>
<p>Above code is working fine for me, but I want to use minimum memory. <strong>How can I reduce the above code and get the correct result with a single list and least iteration?</strong></p>
<p><strong>input</strong></p>
<blockquote>
<p>car truck 8 4 bus 6 1</p>
</blockquote>
<p><strong>output</strong></p>
<blockquote>
<p>bus car 1 4 truck 6 8</p>
</blockquote>
| 2 | 2016-08-11T08:53:45Z | 39,412,422 | <p>I reduced code to a single list.</p>
<pre><code> def inplace_sort(input_string):
int_index, output_string, input_string_list = 0,"",[]
for item in input_string.split(' '):
if item.isdigit():
input_string_list.append(int(item))
else:
input_string_list.append(item)
input_string_list = sorted(input_string_list)
for alpha_index, value in enumerate(input_string_list):
if isinstance(value, str):
break
for item in input_string.split():
if item.isdigit():
output_string += str(input_string_list[int_index]) + " "
int_index += 1
else:
output_string += input_string_list[alpha_index] + " "
alpha_index += 1
return "\nOutput:\n"+output_string
if __name__ == "__main__":
output_string = inplace_sort(raw_input("\nInput:\n"))
print output_string
</code></pre>
| 2 | 2016-09-09T13:13:43Z | [
"python",
"sorting"
] |
Unknown column error after changing a field to foreign key in django | 38,891,669 | <p>I changed one of the field from IntegerField to ForeignKey. Migrations went well and query is working in mysql but when i start the server and load the homepage i get this error</p>
<blockquote>
<p>(1054, "Unknown column 'job_test.suite_id_id' in 'field list'")</p>
</blockquote>
<p>where job_test is a table and suite_id is a foreign key referencing to another table.</p>
<p>Please help.</p>
| 0 | 2016-08-11T08:54:05Z | 38,891,832 | <p>As documented under <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey" rel="nofollow">ForeignKey</a>:</p>
<blockquote>
<h3>Database Representation</h3>
<p>Behind the scenes, Django appends <strong>"_id"</strong> to the field name to create its database column name. In the above example, the database table for the <strong>Car</strong> model will have a <strong>manufacturer_id</strong> column. (You can change this explicitly by specifying <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_column" rel="nofollow"><strong>db_column</strong></a>) However, your code should never have to deal with the database column name, unless you write custom SQL. Youâll always deal with the field names of your model object.</p>
</blockquote>
<p>Therefore you need to rename your field to <code>suite</code> instead of <code>suite_id</code>, or else specify <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_column" rel="nofollow"><code>db_column</code></a> to override the column name Django is trying to use.</p>
| 1 | 2016-08-11T09:02:05Z | [
"python",
"mysql",
"django"
] |
How to write the data to the new column in existing csv File using python script | 38,891,843 | <p>The below code is to read the data in <code>File1</code> from columns 2, 3, 4, 8 and write it in <code>NewFile</code>. The data in each column 2 (which is already stored in <code>temp_list</code>) should be searched in <code>File3</code>. If found, the data in third column of each row in <code>File3</code> is appended with the data stored in <code>temp_list</code>. But second <code>for</code> loop only considers the column2 data in first row. It is not considering the data in column 2 in remaining rows.</p>
<p>I gave print <code>var1</code> in second loop to see if each column 2 data (copied in <code>Newfile</code>) is being considered. But the output shows value only in the first row of <code>File3</code>. Values in other rows are not searched. Can someone please help me to understand the problem in my code?</p>
<pre><code>import csv
f1 = csv.reader(open("C:/Users/File1.csv","rb"))
f2 = csv.writer(open("C:/Users/NewFile.csv","wb"))
f3 = csv.reader(open("C:/Users/File3.csv","rb"))
for row_f1 in f1:
if not row_f1[0].startswith("-"):
temp_list = [row_f1[1],row_f1[2],row_f1[3],row_f1[7]]
var1 = row_f1[1]
for row_f3 in f3:
if var1 in row_f3:
temp_list.append(row_f3[2])
f2.writerow(temp_list)
</code></pre>
| 0 | 2016-08-11T09:02:30Z | 38,892,127 | <p>One of your problems is that when you do <code>for row_f3 in f3:</code> you read the file and it doesn't go to the beginning automatically. An option is to read it once saving the lines to a list, but checking if <code>var1</code> exists in a list every time will be very slow.</p>
<p>What is the field in row_f3 where you try to find var1? You can use a dictionary if the keys are the same:</p>
<pre><code>d = dict()
for row_f3 in f3:
d[row_f3[field_index]] = row_f3[2]
</code></pre>
<p>And then:</p>
<pre><code> new_field = d.get(var1)
if new_field is not None: temp_list.append(new_field)
</code></pre>
<p>How bigs are your files? If they are <1Gb you can also try pandas instead of reading line by line:</p>
<pre><code>import pandas as pd
df1 = pd.read_csv("C:/Users/File1.csv",header=None,index_col=None)
df1 = df1.loc[~df1[0].str.startswith("-"),[1,2,3,7]
df1[8] = df1[1].apply(lambda x: d.get(x))
df1.to_csv("C:/Users/NewFile.csv",header=None)
</code></pre>
| 0 | 2016-08-11T09:14:33Z | [
"python",
"python-2.7",
"python-3.x"
] |
How to write the data to the new column in existing csv File using python script | 38,891,843 | <p>The below code is to read the data in <code>File1</code> from columns 2, 3, 4, 8 and write it in <code>NewFile</code>. The data in each column 2 (which is already stored in <code>temp_list</code>) should be searched in <code>File3</code>. If found, the data in third column of each row in <code>File3</code> is appended with the data stored in <code>temp_list</code>. But second <code>for</code> loop only considers the column2 data in first row. It is not considering the data in column 2 in remaining rows.</p>
<p>I gave print <code>var1</code> in second loop to see if each column 2 data (copied in <code>Newfile</code>) is being considered. But the output shows value only in the first row of <code>File3</code>. Values in other rows are not searched. Can someone please help me to understand the problem in my code?</p>
<pre><code>import csv
f1 = csv.reader(open("C:/Users/File1.csv","rb"))
f2 = csv.writer(open("C:/Users/NewFile.csv","wb"))
f3 = csv.reader(open("C:/Users/File3.csv","rb"))
for row_f1 in f1:
if not row_f1[0].startswith("-"):
temp_list = [row_f1[1],row_f1[2],row_f1[3],row_f1[7]]
var1 = row_f1[1]
for row_f3 in f3:
if var1 in row_f3:
temp_list.append(row_f3[2])
f2.writerow(temp_list)
</code></pre>
| 0 | 2016-08-11T09:02:30Z | 38,893,626 | <p>If I understand your description properly, the following should do what you want. The main problem with your code is that it doesn't close and reopen the third file in order to read and copy the data from it. Since your code is also sloppy about the closing of files in general, I've taken care of that by modifying it to use <code>with</code> statements which will handle it automatically.</p>
<pre><code>import csv
with open("C:/Users/File1.csv", "rb") as file1, \
open("C:/Users/NewFile.csv", "wb") as file2:
f2 = csv.writer(file2)
for row_f1 in csv.reader(file1):
if not row_f1[0].startswith("-"):
temp_list = [row_f1[1], row_f1[2], row_f1[3], row_f1[7]]
var1 = row_f1[1]
var1_found = False
with open("C:/Users/File3.csv", "rb") as file3:
for row_f3 in csv.reader(file3):
if var1 in row_f3:
var1_found = True
break
if var1_found:
with open("C:/Users/File3.csv", "rb") as file3:
for row_f3 in csv.reader(file3):
temp_list.append(row_f3[2])
f2.writerow(temp_list)
</code></pre>
| 0 | 2016-08-11T10:21:27Z | [
"python",
"python-2.7",
"python-3.x"
] |
python process takes time to start in django project running on nginx and uwsgi | 38,891,879 | <p>I am starting a process using python's multiprocessing module. The process is invoked by a post request sent in a django project. When I use development server (python manage.py runserver), the post request takes no time to start the process and finishes immediately.</p>
<p>I deployed the project on production using nginx and uwsgi. </p>
<p>Now when i send the same post request, it takes around 5-7 minutes to complete that request. It only happens with those post requests where I am starting a process. Other post requests work fine.</p>
<p>What could be reason for this delay? And How can I solve this?</p>
| 4 | 2016-08-11T09:04:21Z | 38,975,522 | <p>Basically the background processing needs to be started outside the WSGI application module. </p>
<p>In WSGI, a python webapp process is started to handle requests, number of which vary depending on configuration. If this process spawns a new process that will block the WSGI process from handling new requests, making the server block and wait for it to finish before handling new requests.</p>
<p>What I would suggest is you use a shared queue in the WSGI application module to feed into a process started <em>outside</em> the WSGI application module. Something like the below. This will start one new processor for each WSGI process outside the webapp module so as not to block requests.</p>
<p><code>your_app/webapp.py</code>:</p>
<pre><code>from . import bg_queue
def post():
# Webapp POST code here
bg_queue.add(<task data>)
</code></pre>
<p><code>your_app/processor.py</code>:</p>
<pre><code>from multiprocessing import Process
class Consumer(Process):
def __init__(self, input_q):
self.input_q = input_q
def run(self):
while True:
task_data = input_q.get()
<process data>
</code></pre>
<p><code>your_app/__init__.py</code>:</p>
<pre><code>from .processor import Consumer
bg_queue = Queue()
consumer = Consumer(bg_queue)
consumer.daemon = True
consumer.start()
</code></pre>
| 0 | 2016-08-16T12:53:28Z | [
"python",
"django",
"nginx",
"process",
"uwsgi"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.