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(): ...
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 ':....
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>: <...
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 ':....
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 f...
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 ':....
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 va...
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 ':....
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 me...
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 ':....
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-packa...
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...
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 cha...
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 %&gt;% 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...
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><co...
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...
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'...
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><s...
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.manag...
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(...
-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> </blockq...
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(...
-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) &gt; 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_d...
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 th...
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 th...
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 <c...
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 ...
-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 '...
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 ...
-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 ...
-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 ...
-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_Vol...
-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><...
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_Vol...
-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_'): ret...
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>&lt;form name="form1"&gt; &lt;input type="text" name="username"&gt; &lt;a href="link_details"&gt;Click here&lt;/a&gt; &...
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>&lt;form id="form1" action="/link_details" method="post"&gt; &lt;input type="text" name="username" /&gt; &lt;input type="submit" value="Submit" /&gt; ...
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 &amp; Secret Key</strong></p> <pre><code>s3r = boto3.resource('s3', aws_access_key_id='XXXXXXXXXXXXXXXXXXXX', aws_secret_access_key=...
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> <...
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> <pr...
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> <...
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', ...
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 <...
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', ...
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"...
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', ...
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', '...
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> ...
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="nof...
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) ) </...
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, stri...
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) ) </...
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) ) </...
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) ) </...
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/questio...
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] </...
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" -> ...
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>&lt;form action="/calc/" method="get"&gt; &lt;input type="text" name="pv"&gt; &lt;input type="text" name="n"&gt; &lt;input type="text" name="r"&gt; &lt;input type="submit" value="Search"&gt; &lt;/form&gt; </code></pre> <p>And I'm defini...
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 ...
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>&lt;form action="/calc/" method="get"&gt; &lt;input type="text" name="pv"&gt; &lt;input type="text" name="n"&gt; &lt;input type="text" name="r"&gt; &lt;input type="submit" value="Search"&gt; &lt;/form&gt; </code></pre> <p>And I'm defini...
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...
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 nu...
-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 ...
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) ...
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 matchC...
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) ...
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 &gt; file1.txt for i in {1..200000}; do echo $RANDOM; done &gt; file2.txt # get every line of file2.txt which is also in...
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 &gt; log.log </code></pre> <p>but...
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 &gt;log.log 2&gt;&amp;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-m...
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 recei...
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 valu...
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 hre...
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 ...
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,)) </...
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...
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}' &lt;&lt;&lt; "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...
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...
1
2016-08-11T06:55:27Z
38,899,248
<pre><code>$ sed -E 's/\.[0-9]+ +/ /' &lt;&lt;&lt; '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:]]+/ /' &lt;&lt;&lt; '172.10.2.32 myhosts.lab.com' 172.10...
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.ht...
-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 sensor...
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&amp;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_pay...
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 ...
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="ht...
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 ...
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 3...
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 ...
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...
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 &amp; 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.Comb...
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 obj...
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 &amp; 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 g...
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://sta...
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)...
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 d...
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 ...
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 d...
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 t...
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 d...
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...
-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>js...
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...
-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 stri...
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...
-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...
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...
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...
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.', erro...
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 is...
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.getsizeo...
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.getsizeo...
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>&gt;&gt;&gt; sys.getsizeof(array.array("i", [1,2,3]) 68L &gt;&gt;&gt; sys.getsizeof(array.array("i", range(1000)) 4056L </code></pre> <p>However, when you do</p> <pre><code>&gt;&gt;&gt; sys.get...
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...
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:</...
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&lt;Case_ID&gt;[^ ;]+);(?P&lt;Event_ID&gt;[^ ;]+);(?P&lt;Date_Time&gt;[^ ;]+);(?P&lt;Activity&gt;[^;]+);(?P&lt;Resource&gt;[^ ;]+);(?P&lt;Costs...
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....
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 app...
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 ...
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&amp;password=password ...</p> </blockquote>...
-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 ...
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&amp;password=password ...</p> </blockquote>...
-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...
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://githu...
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 ch...
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...
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>Th...
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", '...
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(...
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.da...
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, ...
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)) ...
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 ...
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...
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 ...
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) &lt; 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 ad...
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 ...
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] == ...
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 ...
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(...
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 ...
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 direc...
-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...
-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...
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 valu...
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': '...
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 valu...
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'...
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 valu...
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']&gt;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 valu...
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...
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 valu...
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"] &gt; 0] </code></pre> <p>To sort the keys:</p> <pre><code>for key in d2.keys(): d2[key] = sorted(list(d2[key])) </code><...
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 valu...
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...
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><...
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 d...
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 m...
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 d...
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 d...
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 simplif...
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 d...
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 = sort...
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 ...
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 ex...
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 append...
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 whe...
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 append...
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 i...
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 usin...
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, maki...
0
2016-08-16T12:53:28Z
[ "python", "django", "nginx", "process", "uwsgi" ]