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 |
|---|---|---|---|---|---|---|---|---|---|
Extracting XML element text based on node attribute in Python 3 | 37,924,347 | <p>I am trying to extract various information from an XML file. I am able to partially collect information, but I am having difficulties walking the element tree as some nodes have the same name and I am having to extract based on attribute name within the child node.</p>
<p>Here's the XML snippet:</p>
<pre><code>&l... | 0 | 2016-06-20T13:53:31Z | 37,924,662 | <p>try this:</p>
<pre><code>import lxml.etree as et
doc = et.parse('C:/temp/report.xml')
testTags = doc.xpath('//test_case')
for test in testTags:
propertyTags = test.xpath('properties')
actionTags = test.xpath('/runner/iteration/step/action')
for prop in propertyTags:
print (prop[0].text)
print(... | 0 | 2016-06-20T14:07:50Z | [
"python",
"xml",
"xpath"
] |
Receiving error code when non unique value is found in list | 37,924,418 | <p>So our assignment is to find non unique items on our list and return an error message if two "students" havde the same student id number.
"Your program must at least detect and display information about the following possible errors:
1. If two students in the data have the same student id.
2. If a grade in the data... | 0 | 2016-06-20T13:57:02Z | 37,924,576 | <p>You can iterate through your grade-list like so:</p>
<pre><code>for grade in grades2:
</code></pre>
<p>In every iteration, variable grade is compared against all variables in the allowed grade list like so:</p>
<pre><code> if grade not in [-3,0,2,4,7,10,12]:
</code></pre>
<p>So the complete code is:</p>
<pre... | 1 | 2016-06-20T14:04:22Z | [
"python",
"error-handling"
] |
Return the next nth result \w+ after a hyphen globally | 37,924,545 | <p>Just getting to the next stage of understanding regex, hoping the community can help...</p>
<p>string = <code>These.Final.Hours-AUSVERSION.2013-TEST-TESTAGAIN-YIFY.cp(tt123456).MiLLENiUM.mp4</code></p>
<p>There are multiple test names preceded by a '-' hyphen which I derive from regex
<code>\(?<=-)\w+\g</code>... | 1 | 2016-06-20T14:02:38Z | 37,924,922 | <p>In Python, you can get these matches with a simple <code>-\s*(\w+)</code> regex and <code>re.findall</code> and then access any match with the appropriate index:</p>
<p>See <a href="https://ideone.com/h0LykP" rel="nofollow">IDEONE demo</a>:</p>
<pre><code>import re
s = 'These.Final.Hours-AUSVERSION.2013-TEST-TESTA... | 0 | 2016-06-20T14:21:22Z | [
"python",
"regex",
"regex-lookarounds"
] |
number or size of python igraph communities | 37,924,579 | <p>I am using the python igraph package for community detection. Currently, I am using <code>community_multilevel</code></p>
<pre><code>communities = ig.Graph.community_multilevel(g)
</code></pre>
<p>However, the detected communities are too large, making them less informative. Is there a way to either specify the nu... | 0 | 2016-06-20T14:04:32Z | 38,296,412 | <blockquote>
<p>Is there a way to either specify the number of communities or restrict the size of the communities so they are smaller?</p>
</blockquote>
<p>The answer is pretty disappointing: no, there isn't; none of the community detection algorithms in igraph let you specify the number of communities in advance o... | 0 | 2016-07-10T20:57:04Z | [
"python",
"python-2.7",
"igraph"
] |
averaging every five minutes data as one datapoint in pandas dataframe ovewr multiple days | 37,924,642 | <p>I have a dataframe like this:</p>
<pre><code>"16-feb-05 07:10", 6.8, 8.1, 0.0214, 1.8105, 0.0214, 1.6985, 1.00, 2.631
"16-feb-05 07:15", 18.3, 8.1, 0.0214, 1.8093, 0.0214, 1.6977, 1.00, 2.656
"16-feb-05 07:20", 12.7, 8.1, 0.0214, 1.8083, 0.0214, 1.6971, 1.00, 2.673
...
...
"01-mar-05 00:00", -10.1, 7.9, 0.... | 1 | 2016-06-20T14:06:57Z | 37,924,779 | <p>For me it works nice:</p>
<pre><code>#pandas 0.18.0
#df1 = close_px[['Conc']].resample('5min').sum()
#pandas bellow 0.18.0
df1 = close_px[['Conc']].resample('5min',how='sum')
print (df1)
Conc
Date
2005-02-16 07:10:00 6.8
2005-02-16 07:15:00 18.3
2005-02-16 07:20:00 12.7... | 0 | 2016-06-20T14:13:06Z | [
"python",
"pandas"
] |
ttk.Separator set the length/width | 37,924,785 | <p>How to set/change the length/width of a ttk.Separator object in Tkinter?</p>
<pre><code> ttk.Separator(self, orient='horizontal').grid(column=0,
row=0, columnspan=2, sticky='ew')
</code></pre>
<p>It seems that columnspan tries to do the job, but when you have multiple separators with the same column... | 1 | 2016-06-20T14:13:19Z | 37,926,842 | <p>Your problem is not that the separators are too short, it's that you haven't told <code>grid</code> what to do with extra un-allocated space. Your columns are only exactly as wide as they need to be, and your separator is only as wide as the columns it is in. In a comment you say "I want them to go till the end of t... | 2 | 2016-06-20T15:55:18Z | [
"python",
"tkinter",
"width",
"separator",
"ttk"
] |
Python pptx (Power Point) Find and replace text (ctrl + H) | 37,924,808 | <p><strong>Question in Short:</strong> How can I use the find and replace option (ctrl+H) using the Python-pptx module?</p>
<p>Example Code:</p>
<pre><code>from pptx import Presentation
nameOfFile = "NewPowerPoint.pptx" #Replace this with: path name on your computer + name of the new file.
def open_PowerPoint_Prese... | 0 | 2016-06-20T14:15:09Z | 37,937,511 | <p>You would have to visit each slide on each shape and look for a match using the available text features. It might not be pretty because PowerPoint has a habit of splitting runs up into what may seem like odd chunks. It does this to support features like spell checking and so forth, but its behavior there is unpredic... | 0 | 2016-06-21T07:00:00Z | [
"python",
"python-2.7",
"powerpoint",
"python-pptx"
] |
Python search for string in line | 37,924,825 | <p>I have the following code, which I think should work, but doesn't appear to:</p>
<pre><code>old_name = 'Some User'
new_name = 'New User'
with open(complete_filename, 'r') as provisioning_file:
lines = provisioning_file.read()
# if the old_name is in this file
if old_name in lines:
file_found = 1
... | 0 | 2016-06-20T14:16:05Z | 37,924,898 | <pre><code>lines = provisioning_file.read()
</code></pre>
<p>This doesn't look right to me. <code>read()</code> doesn't return a list of lines, it returns a single string. So later on when you do <code>for line in lines:</code>, you're not iterating line-by-line, you're iterating one character at a time.</p>
<p>Try <... | 3 | 2016-06-20T14:20:08Z | [
"python",
"string",
"replace",
"substitution"
] |
Check python function determine isogram from codewars | 37,924,869 | <p>An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.</p>
<pre><code>is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == f... | 0 | 2016-06-20T14:18:31Z | 37,925,397 | <p>Try this:</p>
<pre><code>def is_isogram(string):
string = string.lower()
for char in string:
if string.count(char) > 1:
return False
return True
</code></pre>
<p>In your code when <code>is_isogram("moose")</code> is called, it will see that the first character's ('m') count is no... | 0 | 2016-06-20T14:43:55Z | [
"python",
"string",
"algorithm",
"python-2.7"
] |
Check python function determine isogram from codewars | 37,924,869 | <p>An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.</p>
<pre><code>is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == f... | 0 | 2016-06-20T14:18:31Z | 37,925,463 | <p>How about using <a href="https://docs.python.org/3.4/library/stdtypes.html?highlight=set#set" rel="nofollow">sets</a>? Casting the string into a set will drop the duplicate characters, causing isograms to return as <code>True</code>, as the length of the set won't differ from the length of the original string:</p>
... | 1 | 2016-06-20T14:46:51Z | [
"python",
"string",
"algorithm",
"python-2.7"
] |
Execute a function to return a value on a loop until that function returns False - Python | 37,924,937 | <p>I have a function that moves a file from one server to another. The function returns the file name when executed or it returns False if no file was transferred. </p>
<p>I would like to call this function on a loop until it returns False. I also need to access the returned value (file name) each time the function is... | 0 | 2016-06-20T14:21:52Z | 37,925,004 | <p>You can't do things like that in Python, as assignment is always a statement. The usual pattern is:</p>
<pre><code>while True:
name_of_file = move_first_matching_file()
if not name_of_file:
break
...
</code></pre>
| 2 | 2016-06-20T14:24:03Z | [
"python"
] |
Execute a function to return a value on a loop until that function returns False - Python | 37,924,937 | <p>I have a function that moves a file from one server to another. The function returns the file name when executed or it returns False if no file was transferred. </p>
<p>I would like to call this function on a loop until it returns False. I also need to access the returned value (file name) each time the function is... | 0 | 2016-06-20T14:21:52Z | 37,925,215 | <p>As said in comment, you can also do </p>
<pre><code>filename = move_first_matching_file()
while filename:
# process file
# call the function again and reassing the filename
filename = move_first_matching_file()
</code></pre>
<p>Because your function send a string if successful (which always stands for... | 0 | 2016-06-20T14:34:44Z | [
"python"
] |
os.listdir analog for a zipped directory | 37,925,011 | <p>My goal is to list all files contained in the certain <strong>sub</strong>-directory inside a zip-archive.</p>
<p><code>os.listdir(target_dir)</code> raises a <code>FileNotFoundError</code>, and <code>zfile.namelist()</code> just lists all the files in all directories. </p>
<p>Any ideas?</p>
| 0 | 2016-06-20T14:24:28Z | 37,925,346 | <p>Try the following:</p>
<pre><code>files = list(filter(lambda f: f.startswith("subdir"), zfile.namelist()))
print(files)
</code></pre>
<p>Explanation: <code>filter</code> filters the list supplied by <code>zfile.namelist()</code> on a <code>lambda</code> that is checking whether the filename starts with "subdir".<... | 1 | 2016-06-20T14:40:45Z | [
"python",
"python-2.7",
"python-3.x",
"zipfile"
] |
os.listdir analog for a zipped directory | 37,925,011 | <p>My goal is to list all files contained in the certain <strong>sub</strong>-directory inside a zip-archive.</p>
<p><code>os.listdir(target_dir)</code> raises a <code>FileNotFoundError</code>, and <code>zfile.namelist()</code> just lists all the files in all directories. </p>
<p>Any ideas?</p>
| 0 | 2016-06-20T14:24:28Z | 37,925,549 | <p>You can use the supplied <code>zip_listdir</code> function, which is a bit quick-n-dirty but should always work in Unix clones.</p>
<pre><code>class MockZipFile(object):
fake_file_names = [
"string.pyc", # Top level name
"test/__init__.pyc", # Package directory
"test/test_support.pyc",... | 2 | 2016-06-20T14:51:12Z | [
"python",
"python-2.7",
"python-3.x",
"zipfile"
] |
Setting import function to simplify the import process in Python | 37,925,016 | <p>Here is my question.</p>
<p>I use ipython notebook for daily data processing and analysis. When I create a new notebook, some essential packages must be imported first. After long-time accumulation, some process are interlinked and oriented to different task. </p>
<p>I can summarize the nature of my common proj... | -1 | 2016-06-20T14:24:38Z | 37,926,147 | <p>It is certainly possible. You'll just need to understand the Python import rules- any package that appears as a sub-directory of your PYTHONPATH environment variable can be imported with a traditional import statement.</p>
<p>So, say you had a directory called ~/python/mypatterns containing your set of utility cod... | 0 | 2016-06-20T15:20:15Z | [
"python",
"python-2.7",
"function"
] |
2d array save python | 37,925,018 | <p>I have a program that creates a 2d array in Python but how do I save it as a csv file, it is</p>
<pre><code>value_a = int(input("Type in a value for a: "))
value_b = int(input("Now a value for b: "))
value_c = int(input("And a value for c: "))
d = value_a + value_b + value_c
result = [[value_a, value_b, value_c, d]... | -2 | 2016-06-20T14:24:52Z | 37,925,131 | <p>Use <a href="https://docs.python.org/2/library/csv.html#csv.csvwriter.writerows" rel="nofollow"><code>csvwriter.writerows</code></a>,</p>
<pre><code>import csv
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerows(result)
</code></pre>
| 0 | 2016-06-20T14:30:19Z | [
"python",
"arrays"
] |
2d array save python | 37,925,018 | <p>I have a program that creates a 2d array in Python but how do I save it as a csv file, it is</p>
<pre><code>value_a = int(input("Type in a value for a: "))
value_b = int(input("Now a value for b: "))
value_c = int(input("And a value for c: "))
d = value_a + value_b + value_c
result = [[value_a, value_b, value_c, d]... | -2 | 2016-06-20T14:24:52Z | 37,925,142 | <p>If you're able to use third-party libraries and you're going to be working with 2d (or more) arrays in Python, I'd recommend you use a library like numpy or pandas. Numpy includes a method to write out arrays as csv files called <code>savetxt</code>. Good luck!</p>
| 0 | 2016-06-20T14:30:44Z | [
"python",
"arrays"
] |
2d array save python | 37,925,018 | <p>I have a program that creates a 2d array in Python but how do I save it as a csv file, it is</p>
<pre><code>value_a = int(input("Type in a value for a: "))
value_b = int(input("Now a value for b: "))
value_c = int(input("And a value for c: "))
d = value_a + value_b + value_c
result = [[value_a, value_b, value_c, d]... | -2 | 2016-06-20T14:24:52Z | 37,925,169 | <p>Python comes with CSV writing and reading functionality. See <a href="https://docs.python.org/2/library/csv.html" rel="nofollow"> The Python Standard Library » 13.1csv â CSV File Reading and Writing</a> for fuller documentation, but here is a quick example taken from that page and adapted to your problem:</p>
<... | 0 | 2016-06-20T14:32:28Z | [
"python",
"arrays"
] |
Extra file created while executing a python script | 37,925,024 | <p>After I execute my python script in linux and then see the contents of the directory, there is another file created with '~' at the end of the file name.What is that file exactly?
P.S-I just started learning python today so I am a complete noob!</p>
| 0 | 2016-06-20T14:25:06Z | 37,925,490 | <p>It is probably a backup created by your text editor. See <a href="http://askubuntu.com/questions/173151/what-does-the-tilde-at-the-end-of-a-file-name-stand-for">here</a>.</p>
<blockquote>
<p>If a file is appended with a tilde~, it only means that it is a backup created by a text editor or similar program; it does... | 1 | 2016-06-20T14:48:09Z | [
"python",
"linux"
] |
Is there a Rawblock-like feature for docx Writers? | 37,925,040 | <p>When I convert from Markdown to LaTeX, I can replace Images or RawBlocks with special LaTeX code using python filters. Is there a similar way to do this for docx output?</p>
<p>In fact, I would like to use python-docx to generate tables which are more complex than what pandoc can handle. I can extract the xml relat... | 0 | 2016-06-20T14:25:46Z | 37,928,392 | <p>Yes, as can be seen <a href="https://github.com/jgm/pandoc/blob/master/src/Text/Pandoc/Writers/Docx.hs#L782" rel="nofollow">in the pandoc source code</a>, the format should be:</p>
<pre><code>RawBlock (Format "openxml") "<customXML></customXML>"
</code></pre>
<p>or</p>
<pre><code>RawInline (Format "op... | 1 | 2016-06-20T17:25:28Z | [
"python",
"docx",
"pandoc"
] |
Redis write dict and retrieve by nested key | 37,925,075 | <p>So im working on a project for school but im getting stuck somewhere. I create an object that contains 3 variables; source ip, destination ip, dnsname. I make this in an object, then I wrap it as JSON and write it to Redis with the name "dnsanswer" so the whole line in redis looks like this, when I check if it's wri... | 1 | 2016-06-20T14:27:30Z | 37,925,318 | <p>The List's member is opaque to Redis, so you can't request just parts of it. What you can do is either deserialize your JSON in your Python code and extract the key that interests you, or use a server-side Lua script (with <a href="http://redis.io/commands/eval" rel="nofollow"><code>EVAL</code></a> or <a href="http:... | 1 | 2016-06-20T14:39:58Z | [
"python",
"json",
"dictionary",
"redis"
] |
For loop that creates a dictionary | 37,925,100 | <p>I am trying to store training and testing errors with the corresponding <code>test_size</code> in a dictionary, because I want to create a test/training error figure. Unfortunately the for loop is not working. Does anyone know what I am doing wrong? (instead of a dictionary storing them in a pandas df is also fine).... | -1 | 2016-06-20T14:28:55Z | 37,925,136 | <p>You're never assigning the value in the dictionary:</p>
<pre><code>dicto[i, test, train] # This is trying to lookup a key of (i, test, train), which doesn't exist yet.
</code></pre>
<p>Try this instead:</p>
<pre><code>dicto[i] = (test, train) # map test and train variables to test_size, which is i
</code></pre>
| 2 | 2016-06-20T14:30:32Z | [
"python",
"dictionary",
"pandas",
"scikit-learn"
] |
For loop that creates a dictionary | 37,925,100 | <p>I am trying to store training and testing errors with the corresponding <code>test_size</code> in a dictionary, because I want to create a test/training error figure. Unfortunately the for loop is not working. Does anyone know what I am doing wrong? (instead of a dictionary storing them in a pandas df is also fine).... | -1 | 2016-06-20T14:28:55Z | 37,925,194 | <p>Is that, what you want?</p>
<pre><code>dicto[i] = test, train
</code></pre>
| 0 | 2016-06-20T14:33:31Z | [
"python",
"dictionary",
"pandas",
"scikit-learn"
] |
SQLite from API Call | 37,925,160 | <p>i am trying to insert a few thousands rows from the quandl site by making an API call and storing into an object call "data"
The structure of the data is simply date and price</p>
<pre><code>import quandl as q
import sqlite3 as sq
token = "asdaasdewqrdfc"
data = quandl.get("WGC/GOLD_DAILY_USD", authtoken=token)
... | -1 | 2016-06-20T14:31:58Z | 37,932,746 | <p>The return from <code>quandl.get</code> is a Pandas dataframe. Use the Pandas utility function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow"><code>.to_sql()</code></a> to insert your data:</p>
<pre><code>import quandl as q
import sqlite3 as sq
token = "... | 0 | 2016-06-20T22:20:25Z | [
"python",
"sqlite",
"api"
] |
Where python prometheus_client stores the data? | 37,925,279 | <p>Just a quick question here as I am quiet lazy to go through the code.. :) Where does python <a href="https://github.com/prometheus/client_python" rel="nofollow">prometheus_client</a> stores all the data it captures? Is it stored in memory of current thread? If not then where?</p>
<p>I would like to use it with my d... | 1 | 2016-06-20T14:37:52Z | 37,925,422 | <p>It's all kept in memory, protected by a mutex. For a multi-threaded application it'll all Just Work.</p>
| 0 | 2016-06-20T14:45:03Z | [
"python",
"django",
"prometheus"
] |
'QTextEdit' object has no attribute 'setPlaceholderText' | 37,925,283 | <p>I know that <a href="http://stackoverflow.com/questions/3952850/pyqt4-attributeerror-qlineedit-object-has-no-attribute-setplaceholdertext">this question has been asked before</a>, but there only <code>PySide</code> was referred as alternative. I kind of want it to work using <code>PyQt4</code>.</p>
<p>The problem i... | 0 | 2016-06-20T14:38:21Z | 37,925,972 | <p>The PyQt4 you are using has not been <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qt_v5.html" rel="nofollow">built against Qt5</a>, so it cannot access any of the features added in Qt5.</p>
| 2 | 2016-06-20T15:11:40Z | [
"python",
"qt",
"pyqt",
"pyqt4"
] |
Django makes a QueryDict from JSON data | 37,925,385 | <p>I use this code to post some data to a Django-powered site:</p>
<pre><code>url = "http://example.com:8080/api/v1/data/"
request = {"info": "", "data": [{"extra": 0, "amount": 100, "id": "10000000016"}, {"extra": 0, "amount": 100, "id": "10000000002"}]}
opener = urllib2.build_opener()
opener.addheaders = [("Authoriz... | 3 | 2016-06-20T14:43:09Z | 37,928,272 | <p>As @dhke said in the comments, the problem is that <code>urllib2</code> will use <code>application/x-www.form-urlencoded</code> by default. A quick search online gave me this code:</p>
<pre><code>r = urllib.Request(url, data=json.dumps(request), headers={..})
urllib2.urlopen(req)
</code></pre>
<p>which works as ex... | 0 | 2016-06-20T17:17:14Z | [
"python",
"django",
"rest"
] |
sqlserver datetime to oracle timestamp problems | 37,925,387 | <p>So I am working on a project to move data from a sql server db to an oracle db and the dates are giving me a hard time. To do data movement I have a python script that pulls data from the sql server db and and then runs an insert query. </p>
<p>The problem is that the dates look like this <code>2016-06-01 05:45:06.... | 0 | 2016-06-20T14:43:32Z | 37,925,791 | <p>It's possible that what you're experiencing is something to do with your nls format settings. However, I don't see an issue with using <code>to_timestamp</code>:</p>
<pre><code>with sample_data as (select '2016-06-01 05:45:06.003' col1 from dual union all
select '2016-06-01 12:55:06.638' col1 f... | 1 | 2016-06-20T15:02:43Z | [
"python",
"sql-server",
"oracle",
"cx-oracle"
] |
sqlserver datetime to oracle timestamp problems | 37,925,387 | <p>So I am working on a project to move data from a sql server db to an oracle db and the dates are giving me a hard time. To do data movement I have a python script that pulls data from the sql server db and and then runs an insert query. </p>
<p>The problem is that the dates look like this <code>2016-06-01 05:45:06.... | 0 | 2016-06-20T14:43:32Z | 37,927,387 | <p><a href="http://www.oracle.com/technetwork/articles/dsl/prez-python-timesanddates-093014.html" rel="nofollow">This Oracle article</a> warns that :</p>
<blockquote>
<p>Fractional seconds of a date/time value passed as a bind variable will be truncated unless the setinputsizes() method is used between prepare() and... | 2 | 2016-06-20T16:22:59Z | [
"python",
"sql-server",
"oracle",
"cx-oracle"
] |
How to test not entered (empty) username show an error message beside the text field in Python Selenium | 37,925,427 | <p>I'm trying to write the automation for the login field. I wanted to test if the username field is clicked and not entered any info and proceed to next field will generate an error message saying "*This field is required" </p>
<pre><code> def test_UserNameValidate(self):
self.driver.getElement("id", "user... | -1 | 2016-06-20T14:45:20Z | 37,928,736 | <p>Look at your line of code:</p>
<pre><code>if not (user_input)
</code></pre>
<p>if there is a user_input object, then this will never evaluate to true. You're probably wanting to look at </p>
<pre><code>if (user_input.getAttribute("value").equals(""))
</code></pre>
| 1 | 2016-06-20T17:47:40Z | [
"python",
"selenium"
] |
Converting xml to dictionary with values on tags | 37,925,468 | <p>I have a XML that has attributes for each tag as the following on:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version= "1.0" encoding="ISO-8859-1" ?>
<month xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="my.xsd">
<day Day="2016-1-01">
... | 1 | 2016-06-20T14:47:01Z | 37,927,437 | <p>The answer you linked is using what's called what's called <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a>. It's a pretty simple and elegant solution because it will do the same thing at each level of the <code>ElementTree</code> to generate that level of the <code>dict</cod... | 3 | 2016-06-20T16:25:51Z | [
"python",
"xml",
"dictionary",
"elementtree"
] |
Converting xml to dictionary with values on tags | 37,925,468 | <p>I have a XML that has attributes for each tag as the following on:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version= "1.0" encoding="ISO-8859-1" ?>
<month xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="my.xsd">
<day Day="2016-1-01">
... | 1 | 2016-06-20T14:47:01Z | 37,927,709 | <p>I often use recursive <code>defaultdict</code> when converting XML to dict, like so:</p>
<pre><code>import xml.etree.ElementTree as ET
from collections import defaultdict
def Tree():
return defaultdict(Tree)
tree = ET.parse('x.xml')
root = tree.getroot()
d = Tree()
for day in root.findall('day'):
for hou... | 0 | 2016-06-20T16:42:38Z | [
"python",
"xml",
"dictionary",
"elementtree"
] |
Running Scrapy on Dokku using a Digital Ocean server | 37,925,504 | <p>Not sure how to describe this but I am running a Scrapy spider on a Digital Ocean server ($5 server), the Scrapy project is deployed as a Dokku app.</p>
<p>However, it runs very slowly compared to the speed on my local computer and on a Heroku free tier dyno. On Dokku it crawls at a speed of 30 pages per minute whi... | 0 | 2016-06-20T14:48:50Z | 37,969,257 | <p>I 'fixed' this issue by not using a Digital Ocean server. The website that I am trying to crawl, which is craigslist.org, just did not respond well to a DO server. It takes a long time to respond to a request. Other websites like Google or Amazon work just fine with DO.</p>
<p>My scraper works just fine on craigsli... | 0 | 2016-06-22T13:17:40Z | [
"python",
"heroku",
"scrapy",
"digital-ocean",
"dokku"
] |
Import Sequences From Swiss-Prot Fasta File | 37,925,508 | <p>I´m working with the fasta file from swiss-port (<a href="ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.fasta.gz" rel="nofollow">ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.fasta.gz</a>) where in the lines that s... | 0 | 2016-06-20T14:49:02Z | 37,979,026 | <p>If you are using Linux, familiarize yourself with <code>sed</code>, <code>awk</code> and <code>tail/head</code>. They will save you a lot of time in the future.</p>
<p>Let's assume we are looking for gene FV3-002L</p>
<pre><code>sed -n '/GN=FV3-002L/,/^>/p' uniprot_sprot.fasta | head -n -1
</code></pre>
<p><co... | 0 | 2016-06-22T22:03:38Z | [
"python",
"fasta"
] |
If statement ordering and key error python | 37,925,526 | <p>Here I get a key error even I check if the key exists in the dict :</p>
<pre><code>def foo(d):
if (('element' in d.keys()) & (d['element'] == 1)):
print "OK"
foo({})
</code></pre>
<p>In the <a href="https://docs.python.org/2/reference/expressions.html#boolean-operations" rel="nofollow">documentati... | -1 | 2016-06-20T14:49:51Z | 37,925,557 | <p><code>&</code> is "bitwise and", <code>and</code> is the logical "and" operator, they are not the same thing.</p>
<p>You should use <code>and</code>, and you can also remove the unneeded parenthesis for readability.</p>
<p>You also don't even have to call the <code>keys</code> method:</p>
<p><code>if 'elemen... | 5 | 2016-06-20T14:51:35Z | [
"python",
"if-statement",
"dictionary",
"keyerror"
] |
Python logger: won't overwrite the original log? | 37,925,579 | <p>So, when I copy paste the following x times to the python prompt,
it add the log x times to the end of the designated file. </p>
<p>How can I change the code so that each time I copy paste this to the prompt,
I simply overwrite the existing file (the code seems to not accept the
<code>mode = 'w'</code> option ... | 0 | 2016-06-20T14:52:49Z | 37,925,758 | <p>Your log messages are being duplicated because you call <code>addHandler</code> more than once. Each call to <code>addHandler</code> adds an <em>additional</em> log handler.</p>
<p>If you want to make sure the file is created from scratch, add an extra line of code to remove it:</p>
<pre><code>os.remove(os.path.j... | 2 | 2016-06-20T15:01:06Z | [
"python",
"logging"
] |
Python logger: won't overwrite the original log? | 37,925,579 | <p>So, when I copy paste the following x times to the python prompt,
it add the log x times to the end of the designated file. </p>
<p>How can I change the code so that each time I copy paste this to the prompt,
I simply overwrite the existing file (the code seems to not accept the
<code>mode = 'w'</code> option ... | 0 | 2016-06-20T14:52:49Z | 37,925,788 | <p>The mode is specified as part of logging.basicConfig and is passed through using filemode.</p>
<pre><code>logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = 'oneDayFileLoader.log,
filemode = 'w'
)
</code></pre>
<p><a href="https://docs.python.or... | 1 | 2016-06-20T15:02:23Z | [
"python",
"logging"
] |
Python logger: won't overwrite the original log? | 37,925,579 | <p>So, when I copy paste the following x times to the python prompt,
it add the log x times to the end of the designated file. </p>
<p>How can I change the code so that each time I copy paste this to the prompt,
I simply overwrite the existing file (the code seems to not accept the
<code>mode = 'w'</code> option ... | 0 | 2016-06-20T14:52:49Z | 37,925,843 | <p>If I understand correctly, you're running a certain Python process for days at a time, and want to rotate the log every day. I'd recommend you go a different route, using a handler that automatically rotates the log file, e.g. <a href="http://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/"... | 2 | 2016-06-20T15:05:34Z | [
"python",
"logging"
] |
Order of response in Google Adwords API | 37,925,802 | <p>Are there any guarantees the Google Adwords API can make about the order of the entries in the response when creating objects calling <code>mutate()</code>?</p>
<p>For example if the request was sent something like:</p>
<pre><code>operations = [add_adgroup_1, add_adgroup_2, add_adgroup_3]
response = client.mutate(... | 0 | 2016-06-20T15:03:30Z | 37,930,660 | <p>Yes they are according to the AdWords API Team: <a href="https://groups.google.com/forum/#!topic/adwords-api/6Jpcc6dnr-M" rel="nofollow">https://groups.google.com/forum/#!topic/adwords-api/6Jpcc6dnr-M</a></p>
| 0 | 2016-06-20T19:48:14Z | [
"python",
"google-adwords",
"adwords-apiv201402"
] |
Sorting a SortedDictionary Requires a Different Key from OrderedDict | 37,925,852 | <p>I am having trouble sorting a dictionary based on key values, which are originally strings. I am looking for a solution that uses <a href="http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html" rel="nofollow"><code>SortedDict</code></a>. Below I cast the strings to <code>int</code>, but the sorting seems i... | -1 | 2016-06-20T15:05:53Z | 37,925,975 | <p>It will work if you replace <code>int(k[0])</code> with <code>int(k)</code> because otherwise you're sorting your dict based on the first digit of the key.</p>
| 2 | 2016-06-20T15:11:45Z | [
"python",
"python-2.7",
"sorteddictionary",
"sortedcontainers"
] |
iterating over multiple columns and rows in pandas dataframe | 37,925,903 | <p>I am fairly new to Pandas and desperately need help to modify my dataframe by comparing consecutive rows within multiple group pairings:</p>
<p>Dataframe example = </p>
<pre><code>idData idStation idCast Pressure
1 1 1 1505
2 1 1 1506
3 1 1 1507
4 1 1 1508
5 1 2 1505
6 1 2 1506... | 1 | 2016-06-20T15:08:42Z | 37,926,285 | <p>You could use <code>boolean indexing</code> with the condition that for each group the <code>Pressure</code> value is not below the <code>.cummax()</code> for that group. </p>
<ol>
<li>Use <code>.groupby()</code> to work on unique subsets of <code>['idStation', 'idCast']</code>. </li>
<li>For each of these groups, ... | 1 | 2016-06-20T15:27:00Z | [
"python",
"pandas"
] |
Python XLWT: Excel generated by Python xlwt contains missing value | 37,925,969 | <p>I'm quite new to Python and trying to fetch data in HTML and saved to excels using xlwt.</p>
<p>So far the program seems work well (all the output are correctly printed on the python console when running the program) except that when I open the excel file, an error message saying <em>'We found a problem with some c... | 0 | 2016-06-20T15:11:32Z | 37,931,428 | <p>seems like a caching issue.
Try sheet.flush_row_data() every 100 rows or so ?</p>
| -2 | 2016-06-20T20:38:51Z | [
"python",
"xlwt"
] |
Async Python function call upon a Bash execution (through Python Popen) | 37,925,994 | <p>I am executing a bash command (that downloads a file) inside a Python script.</p>
<pre><code>def execBashCmd(bash_cmd):
process = Popen([bash_cmd], stdout=PIPE, stderr=PIPE, shell=True)
</code></pre>
<p>The bash command outputs a progression (refreshed) in stdout as follow:</p>
<pre><code>Downloading File - ... | 0 | 2016-06-20T15:12:40Z | 38,370,845 | <blockquote>
<p>I would like to be able to call a python function at a regular
interval to update the progression (that I would catch with a regex or
something like this) somewhere in my python code.</p>
</blockquote>
<p>At any time you can call e. g. <code>os.read(process.stdout.fileno(), 4096)</code> and get t... | 0 | 2016-07-14T09:45:12Z | [
"python",
"multithreading",
"bash",
"asynchronous"
] |
ImportError: No module named 'baseapi' | 37,926,004 | <p>I can`t use the pyfcm module because of bellow error message.
How do I fix this error??</p>
<pre><code>>>> from pyfcm import FCMNotification
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from pyfcm import FCMNotification
File "C:\Anaconda3\lib\site-packages\... | 0 | 2016-06-20T15:13:08Z | 37,926,319 | <p>If you are running Linux, try running this command in the shell: <code>pip install baseapi</code>.</p>
<p>If you are using an IDE, look for a prompt asking if you want to install this package.</p>
| 0 | 2016-06-20T15:29:08Z | [
"python"
] |
Django not detecting AngularJS | 37,926,050 | <p>I have a Django project (that I created using PyCharm IDE). I have two HTML files and below is the code I have in those files.</p>
<p>-- header.html</p>
<pre><code><!DOCTYPE html>
<html lang="en" >
<head>
<title>This is my title</title>
<meta charset="UTF-8">
{% load staticfiles... | 1 | 2016-06-20T15:14:48Z | 37,926,479 | <p>Let's see...</p>
<ol>
<li><p>In header.html you seem to have no <code>{% block content %}</code> defined. There is nothing your template can inherit if no defined.</p></li>
<li><p>in home.html you have an additional html wrapping. You don't need it. In fact AFAIK the extends tag should be the first content in the f... | 2 | 2016-06-20T15:37:37Z | [
"javascript",
"python",
"html",
"angularjs",
"django"
] |
Pyspark logging with log4j conversionpattern not working | 37,926,166 | <p>I am having a problem with logging in spark (pyspark) when changing the format of logs using log4j. I have edited the ConversionPattern in log4j.properties, but it is not working properly. When writing logs, log4j will only use the first letter of the pattern I am trying to use. As an example, I cannot use %replace... | 0 | 2016-06-20T15:21:01Z | 37,935,472 | <p>Have you tried with Log4j 2? Log4j 2 is actively maintained, while Log4j 1.x is End Of Life. </p>
<p>There is an adapter module <code>log4j-1.2-api</code> that you can add to the classpath that delegates application calls to the Log4j 1.2 API to the Log4j 2 implementation. If the application relies on Log4j 1.2 int... | 1 | 2016-06-21T04:13:19Z | [
"python",
"logging",
"apache-spark",
"log4j",
"pyspark"
] |
Automatically logged out when searching using selenium | 37,926,192 | <p>I am using selenium to automate search in a website.
Here is my code.</p>
<pre><code>import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.ex... | -1 | 2016-06-20T15:22:38Z | 37,927,346 | <p>I suspect that you are experiencing expected behavior with your product. You mentioned that you manually open a browser and login, then run the script. When your script runs, Selenium will open a new browser w/ a new profile, which means that it won't have any cookies that are probably being used for authenticatio... | 2 | 2016-06-20T16:20:45Z | [
"python",
"selenium",
"firefox"
] |
How to remove accents from values in columns? | 37,926,248 | <p>How do I change the special characters to the usual alphabet letters?
This is my dataframe:</p>
<pre><code>In [56]: cities
Out[56]:
Table Code Country Year City Value
240 Ã
land Islands 2014.0 MARIEHAMN 11437.0 1
240 Ã
land Islands 2010.0 MARIEHAMN 58... | 5 | 2016-06-20T15:25:16Z | 37,926,330 | <p>This is for Python 2.7. For converting to ASCII you might want to try:</p>
<pre><code>import unicodedata
unicodedata.normalize('NFKD', u"Durrës Ã
land Islands").encode('ascii','ignore')
'Durres Aland Islands'
</code></pre>
| 1 | 2016-06-20T15:29:38Z | [
"python",
"pandas",
"dataframe"
] |
How to remove accents from values in columns? | 37,926,248 | <p>How do I change the special characters to the usual alphabet letters?
This is my dataframe:</p>
<pre><code>In [56]: cities
Out[56]:
Table Code Country Year City Value
240 Ã
land Islands 2014.0 MARIEHAMN 11437.0 1
240 Ã
land Islands 2010.0 MARIEHAMN 58... | 5 | 2016-06-20T15:25:16Z | 37,926,512 | <p>The pandas method is to use the vectorised <code>str.normalize</code> combined with <code>str.decode</code> and <code>str.encode</code>:</p>
<pre><code>In [60]:
df['Country'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8')
Out[60]:
0 Aland Islands
1 Aland Islands
2 Alb... | 3 | 2016-06-20T15:39:39Z | [
"python",
"pandas",
"dataframe"
] |
How to remove accents from values in columns? | 37,926,248 | <p>How do I change the special characters to the usual alphabet letters?
This is my dataframe:</p>
<pre><code>In [56]: cities
Out[56]:
Table Code Country Year City Value
240 Ã
land Islands 2014.0 MARIEHAMN 11437.0 1
240 Ã
land Islands 2010.0 MARIEHAMN 58... | 5 | 2016-06-20T15:25:16Z | 37,926,646 | <p>Use this code:</p>
<pre><code>df['Country'] = df['Country'].str.replace(u"Ã
", "A")
df['City'] = df['City'].str.replace(u"ë", "e")
</code></pre>
<p>See <a href="http://stackoverflow.com/questions/23839465/python-pandas-replace-special-character">here</a>! Of course you should do it then for every special characte... | 1 | 2016-06-20T15:45:56Z | [
"python",
"pandas",
"dataframe"
] |
Python: How to add days to localized datetimes while handling ambigious days (23 and 25 hours days) | 37,926,306 | <p>My problem is similar to this <a href="http://stackoverflow.com/questions/24673330/how-to-add-weekly-timedeltas-with-regards-to-daylight-saving-timezones">question</a>, but doing the timedelta on UTC datetimes is not an option for me.</p>
<p>I have a function that evaluates a period every 'human day', so midnight-t... | 0 | 2016-06-20T15:28:08Z | 37,926,430 | <p>Add 25 hours and then reset the time. This works if the time is always midnight to midnight, but might fail at other times of day.</p>
<pre><code>end_dt = start_dt + datetime.timedelta(hours=25)
end_dt = end_dt.replace(hour=0, minute=0, second=0)
</code></pre>
<p>A more robust solution uses a noon-to-noon calculat... | 1 | 2016-06-20T15:35:18Z | [
"python",
"datetime",
"pytz",
"normalize"
] |
Can I access the views in django from an android application through urls we define on the urlconfig or should I need an API? | 37,926,346 | <p>I am a beginner in django. I covered the basic poll application in the django site. Now I want my android app to communicate with django application. As I googled, the suggestion was to build an API. But is it possible to access the server from an android application like I access the views from my browser using url... | -2 | 2016-06-20T15:30:35Z | 38,283,639 | <p>You should use api for that however you can use webview in android dev.</p>
| 1 | 2016-07-09T15:57:31Z | [
"android",
"python",
"django",
"django-rest-framework"
] |
Django 2 model 1 authentication system | 37,926,416 | <p>In my project, I should create personal type user and company type user they have different attributes. I can create them with different models but I cannot implement both in auth system at the same time? I wonder if it is possible?</p>
| 0 | 2016-06-20T15:34:25Z | 38,361,615 | <p>As stated in django <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-authentication-backends" rel="nofollow">docs</a> you can write your own AUTHENTICATION_BACKENDS.
For example:</p>
<pre><code>class UserProfileModelBackend(ModelBackend):
def authenticate(self, username=None, ... | 0 | 2016-07-13T21:00:11Z | [
"python",
"django",
"authentication"
] |
Python regex finditer's second group got ignored by first captured group | 37,926,542 | <p>For example, I have the following string.</p>
<pre><code>input = "a b c d e f 1 2 3 4"
</code></pre>
<p>I have the following regex code.</p>
<p><code>input = re.sub(r"([0-9])\s+([0-9])", "\1\2", input)</code></p>
<p>This basically is trying to remove the spaces between just digits.</p>
<p>However, after running... | 1 | 2016-06-20T15:41:21Z | 37,926,623 | <p>Since two space separated digits are matched it will not get again in next match. What you can do is use <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">positive look ahead assertion</a> for second digit. Aldo you can use <code>\d</code> short handle for digit group <code>[0-9]</code>.</... | 2 | 2016-06-20T15:44:53Z | [
"python",
"regex"
] |
Tensorflow conv2d_transpose (deconv) Number of rows of out_backprop doesn't match computed | 37,926,562 | <p><strong>EDIT</strong> My issue is the width and height of my filter, I misunderstood the API doc... working on correction now</p>
<p><strong>SOLUTION</strong> Follow deconvolution from <a href="http://cs231n.stanford.edu/slides/winter1516_lecture13.pdf" rel="nofollow">here</a> slide 53</p>
<hr>
<p>I have a simila... | 0 | 2016-06-20T15:42:03Z | 37,927,114 | <p>When using transposed convolutions, you need to think backwards: how would you get your input (<code>conv3</code> of shape <code>[batch_size, 25, 25, 128]</code>) given the output (of shape <code>[batch_size, 200, 200, 1]</code>)?</p>
<p>You would do a succession of 3x3 convolutions and max pooling. Unfortunately, ... | 1 | 2016-06-20T16:08:10Z | [
"python",
"machine-learning",
"neural-network",
"artificial-intelligence",
"tensorflow"
] |
Using pd.apply() with shift to compare adjacent rows | 37,926,571 | <p>I'd like to compare adjacent rows on two separate columns. I have a <code>dataframe</code> with two columns, <code>Letter</code> and <code>Boolean_Value</code>. I would like to create a new column, <code>New Col</code> in which the value is <code>True</code> or <code>False</code>. </p>
<p>For the value to be true: ... | 1 | 2016-06-20T15:42:43Z | 37,926,732 | <p>You could:</p>
<pre><code>df['new_col'] = (df.Letter == df.Letter.shift(-1)) & df.Boolean_Value.shift(-1)
Letter Boolean_Value new_col
0 A False True
1 A True False
2 B False False
3 B False True
4 B True False
</code></pre>
| 2 | 2016-06-20T15:50:11Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Using pd.apply() with shift to compare adjacent rows | 37,926,571 | <p>I'd like to compare adjacent rows on two separate columns. I have a <code>dataframe</code> with two columns, <code>Letter</code> and <code>Boolean_Value</code>. I would like to create a new column, <code>New Col</code> in which the value is <code>True</code> or <code>False</code>. </p>
<p>For the value to be true: ... | 1 | 2016-06-20T15:42:43Z | 37,927,314 | <p>Try this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data=[['A', False],
['A', True],
['B', False],
['B', False],
['B', True]]
,columns=['Letter', 'Boolean_Value'])
df['New Col'] = df['Lette... | 1 | 2016-06-20T16:19:03Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Sending multiple .CSV files after zipping them and without saving to disk | 37,926,604 | <p>I am trying to retrieve files from the internet, save them as dataframe (without saving the files on computer), do some
calculation, save resulting dataframes in the required format as csv files, zip them and send them back to the orginal source(see below my code).
This works perfectly fine but as I have to send hun... | 0 | 2016-06-20T15:44:12Z | 37,926,985 | <p>Have a look at BytesIO():</p>
<pre><code>memory_file = BytesIO()
with zipfile.ZipFile(memory_file, 'w') as zf:
zi = zipfile.ZipInfo('your_filename.txt')
zi.date_time = time.localtime(time.time())[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zf.writestr(zi, 'your file content goes here')
memory_file.... | 0 | 2016-06-20T16:01:49Z | [
"python",
"csv",
"python-requests",
"zipfile",
"stringio"
] |
Get consecutive ratios of elements python | 37,926,608 | <p>Is there a simple way to get the ratios of consecutive elements of a numpy array?</p>
<p>Basically something similar to numpy.diff(x)?</p>
<p>so if x=[1,2,10,100 ...] </p>
<p>I would like [0.5 ,0.2, 0.1 ...]
ie [x1/x2, x2/x3 , x3/x4] </p>
<p>I know I can do this easily by shifting and dividing, but it seems cl... | 0 | 2016-06-20T15:44:17Z | 37,926,721 | <pre><code>xs = [1, 2, 10, 100, ...]
[x1/x2 for (x1, x2) in zip(xs, xs[1:])]
</code></pre>
| 1 | 2016-06-20T15:49:48Z | [
"python",
"numpy"
] |
Get consecutive ratios of elements python | 37,926,608 | <p>Is there a simple way to get the ratios of consecutive elements of a numpy array?</p>
<p>Basically something similar to numpy.diff(x)?</p>
<p>so if x=[1,2,10,100 ...] </p>
<p>I would like [0.5 ,0.2, 0.1 ...]
ie [x1/x2, x2/x3 , x3/x4] </p>
<p>I know I can do this easily by shifting and dividing, but it seems cl... | 0 | 2016-06-20T15:44:17Z | 37,927,051 | <p>Using numpy:</p>
<pre><code>In [6]: x
Out[6]: array([ 1., 2., 10., 100., 150., 75.])
In [7]: x[:-1]/x[1:]
Out[7]: array([ 0.5 , 0.2 , 0.1 , 0.66666667, 2. ])
</code></pre>
<p>That might be what you meant when you said "I can do this easily by shifting and dividing", but I d... | 1 | 2016-06-20T16:04:33Z | [
"python",
"numpy"
] |
Setting event's parameter value at declaration time in PyQT5? | 37,926,648 | <h1>Background</h1>
<p>I'm writing a simple application in PyQT5. The main <code>QWidget</code> is a <code>QGridLayout</code>, and visually the result should be something like this:</p>
<pre><code> +-----------------------------------+
row1 | QLabelA | QLabelB | QLabelC |
+--------------------... | 0 | 2016-06-20T15:46:00Z | 37,926,959 | <p>You're rather close to a solution with your lambda x: statement, you're just missing one little piece</p>
<h1>Using Lambdas to store transient values</h1>
<p>Since your <code>row</code> variable changes a lot, you need to store the value when the function is created; your <code>self.clicked</code> references the c... | 1 | 2016-06-20T16:01:02Z | [
"python",
"python-2.7",
"pyqt",
"pyqt5"
] |
Django - form is never valid | 37,926,662 | <p>I'm creating a form without model. Here is my form class:</p>
<pre><code>class LinkAssetsForm(forms.Form):
preview = forms.ChoiceField()
thumbnail = forms.ChoiceField()
banner = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(LinkAssetsForm, self).__init__()
filepod ... | 0 | 2016-06-20T15:46:48Z | 37,926,945 | <p>You could try to add</p>
<pre><code>{{ form.errors }}
{{ form.non_field_errors }}
</code></pre>
<p>to template display the errors - this could give you a hint.</p>
<p>P.S. "clean<strong>d</strong>_data" - is it a typo?</p>
| 1 | 2016-06-20T16:00:26Z | [
"python",
"django",
"forms"
] |
Django - form is never valid | 37,926,662 | <p>I'm creating a form without model. Here is my form class:</p>
<pre><code>class LinkAssetsForm(forms.Form):
preview = forms.ChoiceField()
thumbnail = forms.ChoiceField()
banner = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(LinkAssetsForm, self).__init__()
filepod ... | 0 | 2016-06-20T15:46:48Z | 37,927,269 | <p>I've found in cases where the form is never being validated, it is because it's requiring all fields in cases where they are not always necessary. Setting required=False inside your form fields i.e.:</p>
<pre><code>banner = forms.ChoiceField(required=False)
</code></pre>
<p>may help if you won't always be passing... | 0 | 2016-06-20T16:16:33Z | [
"python",
"django",
"forms"
] |
Django - form is never valid | 37,926,662 | <p>I'm creating a form without model. Here is my form class:</p>
<pre><code>class LinkAssetsForm(forms.Form):
preview = forms.ChoiceField()
thumbnail = forms.ChoiceField()
banner = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(LinkAssetsForm, self).__init__()
filepod ... | 0 | 2016-06-20T15:46:48Z | 37,928,555 | <p>You have forgotten to pass args and kwargs when you call <code>super()</code>. It should be:</p>
<pre><code>def __init__(self, *args, **kwargs):
super(LinkAssetsForm, self).__init__(*args, **kwargs)
</code></pre>
| 2 | 2016-06-20T17:36:02Z | [
"python",
"django",
"forms"
] |
Google Container Engine: Accessing Cloud Storage | 37,926,671 | <p>I can't get the Application Default Credentials working in Google Container Engine. The docs say that they're intended for App Engine and Compute Engine, but I've been told that they should transparently pass through to a container running on Container Engine.</p>
<p>Here's the code that's failing:</p>
<pre><code>... | 1 | 2016-06-20T15:47:12Z | 37,932,083 | <p>The easiest way to access cloud storage on Container Engine appears to be the <a href="https://googlecloudplatform.github.io/gcloud-python/stable/" rel="nofollow">gcloud</a> library.</p>
<p>It won't work with zero configuration if the App Engine SDK is installed on the container (gcloud finds it and assumes it's ru... | 1 | 2016-06-20T21:26:36Z | [
"python",
"docker",
"google-cloud-storage",
"google-cloud-platform",
"google-container-engine"
] |
psycopg2 unable to insert into specific columns | 37,926,717 | <p>I have a postgres database that I am accessing via Python using the <code>psycopg2</code> library. The table I am attempting to insert into looks like this:</p>
<pre><code> Table "public.programmes"
Column | Type | ... | 2 | 2016-06-20T15:49:35Z | 37,926,794 | <p>I am pretty sure that <code>end</code> is a reserved keyword in Postgres. Try changing the column name to a different name - that will definitely solve the issue. Alternatively, the lazy solution <em>might</em> be to change your code:</p>
<pre><code>postCur.execute("""INSERT INTO programmes('title', 'start', 'end',... | 1 | 2016-06-20T15:53:04Z | [
"python",
"postgresql"
] |
psycopg2 unable to insert into specific columns | 37,926,717 | <p>I have a postgres database that I am accessing via Python using the <code>psycopg2</code> library. The table I am attempting to insert into looks like this:</p>
<pre><code> Table "public.programmes"
Column | Type | ... | 2 | 2016-06-20T15:49:35Z | 37,926,797 | <p>Apparently, <code>end</code> is a <a href="https://www.postgresql.org/docs/9.4/static/sql-keywords-appendix.html" rel="nofollow">key word</a> in PostgreSQL. You need to quote it to make it being interpreted as an identifier:</p>
<pre><code>postCur.execute("""INSERT INTO programmes
(title, start, "end", descript... | 2 | 2016-06-20T15:53:15Z | [
"python",
"postgresql"
] |
How can I test several lines of quickly? | 37,926,719 | <p>Let's say I am browing hithub and I see some code in python I would like to run on my laptop.
Is there a way to just copy, paste it and run it without having to create a file, paste the code and run it ?</p>
<p>I tried running <strong>ipython</strong> on the terminal, then <code>%cpaste</code> and finally pasted t... | -1 | 2016-06-20T15:49:45Z | 37,927,861 | <p><code>%paste</code> works for me. </p>
<p>In editor I indent with tab</p>
<pre><code>def foo(x):
--->return x
</code></pre>
<p>Do a copy</p>
<pre><code>In [892]: %paste
def foo(x):
return x
## -- End pasted text --
In [893]: foo(2)
Out[893]: 2
</code></pre>
<p>Actually <code>ctrl v</code> paste, w... | 0 | 2016-06-20T16:51:14Z | [
"python",
"linux",
"terminal",
"ipython"
] |
How to run IPython notebook server with a specified URL route | 37,926,740 | <p>I want to run a IPython notebook server on the a predefined URL like: <code>http://localhost:8888/my_notebook</code>. </p>
<p>I've tried </p>
<pre><code>$ ipython notebook --ip=localhost/my_notebook
</code></pre>
<p>which didn't work. </p>
<p>Can anyone please help?</p>
| 1 | 2016-06-20T15:50:28Z | 37,927,088 | <p>You can set the configurable value from command line like this:</p>
<pre><code>ipython notebook --NotebookApp.base_url='my_notebook'
</code></pre>
<p>Alternatively, you can set it in a config file for your profile. You can read more about it <a href="https://ipython.org/ipython-doc/3/config/intro.html" rel="nofoll... | 2 | 2016-06-20T16:06:37Z | [
"python",
"tornado",
"ipython-notebook",
"jupyter",
"jupyter-notebook"
] |
Python matplotlib Colorfunction | 37,926,746 | <p>I would like to use a <code>ColorFunction</code> similar to that in <a href="https://reference.wolfram.com/language/ref/ColorFunction.html" rel="nofollow">Mathematica</a> for my plots in python.</p>
<p>In other words, I would like to call <code>pyplot.plot(x, y, color=c)</code>, where <code>c</code> is a vector, de... | 2 | 2016-06-20T15:50:43Z | 37,927,309 | <p>To the best of my knowledge, there is no equivalent in Matplotlib, but we can get the similar result following two steps: draw points with varied colors and draw the line. </p>
<p>Here is a demo.</p>
<p><a href="http://i.stack.imgur.com/OaquV.png" rel="nofollow"><img src="http://i.stack.imgur.com/OaquV.png" alt="e... | 0 | 2016-06-20T16:18:55Z | [
"python",
"matplotlib",
"colors"
] |
Python's Datetime: Conversion to time zones based on lat_long | 37,926,756 | <p>I have been reading python's datetime documentation and it seems like there are few things which are not clearly mentioned there. </p>
<p><code>date = datetime.datetime(2014,10,1,11,45,30)</code></p>
<p>Which timezone will the above date be in? UTC?</p>
<p>If I have to make sure that the above date remains in EST... | 0 | 2016-06-20T15:51:17Z | 37,926,932 | <p>Your code would create a "timezone naive" datetime object. That means - no timezone. It'll be interpreted as local time based on where it is used.</p>
<p>If you want to set a timezone, try using the <code>pytz</code> library.</p>
<pre><code>import pytz # 3rd party: $ pip install pytz
u = datetime.utcnow()
u = u.... | 1 | 2016-06-20T15:59:51Z | [
"python",
"date",
"datetime"
] |
How to get values of neurons on layer? Python-nolearn | 37,926,768 | <p>I have neural network created with using nolearn library.</p>
<pre><code>net = NeuralNet(
layers=[
('input', layers.InputLayer),
('conv1', layers.Conv2DLayer),
('pool1', layers.MaxPool2DLayer),
('dropout1', layers.DropoutLayer),
('conv2', layers.Conv2DLayer),
('pool2', layers.MaxPool2DLayer... | 1 | 2016-06-20T15:51:54Z | 37,990,251 | <p>So, I found the solution. </p>
<pre><code>hidden_layer = layers.get_output(net.layers_['hidden4'], deterministic=True)
input_var = net.layers_['input'].input_var
f_hidden = theano.function([input_var], hidden_layer)
instance = TestD[i][None, :, :, :]
pred = f_hidden(instance)
</code></pre>
| 1 | 2016-06-23T11:24:03Z | [
"python",
"neural-network",
"conv-neural-network",
"lasagne",
"nolearn"
] |
Getting internal value with dot notation | 37,926,809 | <p>I have a dictionary:</p>
<pre><code>d = {'time': {36.0: 'mo'}, 'amount': {200.0: '$'}}
</code></pre>
<p>Each key (e.g. 'time') only ever has one value (e.g. {36.0 'mo'})</p>
<p>I'd like to access the 36.0 by doing</p>
<pre><code>result = d.time
</code></pre>
<p>And the 200.0 by doing</p>
<pre><code>result = d.... | 2 | 2016-06-20T15:53:49Z | 37,926,894 | <p>Below snippet hijacks the attribute access, and returns the first key of the dict instead of the dict itself. It does this for all attributes except <code>__dict__</code>, so use accordingly and be aware of what this implies.</p>
<pre><code>from __future__ import print_function
d = {'... | 1 | 2016-06-20T15:57:48Z | [
"python"
] |
Getting internal value with dot notation | 37,926,809 | <p>I have a dictionary:</p>
<pre><code>d = {'time': {36.0: 'mo'}, 'amount': {200.0: '$'}}
</code></pre>
<p>Each key (e.g. 'time') only ever has one value (e.g. {36.0 'mo'})</p>
<p>I'd like to access the 36.0 by doing</p>
<pre><code>result = d.time
</code></pre>
<p>And the 200.0 by doing</p>
<pre><code>result = d.... | 2 | 2016-06-20T15:53:49Z | 37,927,296 | <p>I'd subclass <code>dict</code> and override <code>__getattr__</code>, after having enshured that there is no name clash between the data keys and <code>dict</code> methods.</p>
<pre><code>d = {'time': {36.0: 'mo'}, 'amount': {200.0: '$'}}
class Bunch(dict):
def __getattr__(self, attr):
try:
... | 1 | 2016-06-20T16:17:56Z | [
"python"
] |
How to get arguments of a list in a list | 37,926,907 | <p>I am using Python 3.5.1 and I have this list:</p>
<pre><code>my_list = [["could", "you", "please"], ["help", "me", "?"]]
</code></pre>
<p>The list can have more than 2 sublists but the sublist always has 3 elements. The variables in each sublist are unique in the whole list. And I want to search for "me" in the wh... | -5 | 2016-06-20T15:58:32Z | 37,926,978 | <p>After your update following up on the comment made earlier, it seems you are looking for this:</p>
<pre><code>In [1]: my_list = [["could", "you", "please"], ["help", "me", "?"]]
In [2]: for sublist in my_list:
...: if "me" in sublist:
...: var1, var2, var3 = sublist
...: do_something_w... | 0 | 2016-06-20T16:01:42Z | [
"python",
"list",
"python-3.x"
] |
How to get arguments of a list in a list | 37,926,907 | <p>I am using Python 3.5.1 and I have this list:</p>
<pre><code>my_list = [["could", "you", "please"], ["help", "me", "?"]]
</code></pre>
<p>The list can have more than 2 sublists but the sublist always has 3 elements. The variables in each sublist are unique in the whole list. And I want to search for "me" in the wh... | -5 | 2016-06-20T15:58:32Z | 37,927,037 | <p>You can use <a href="http://stackoverflow.com/questions/290424/search-in-a-list-by-predicate"><code>lambda & filter & in</code></a></p>
<pre><code>print filter(lambda x: "me" in x, my_list)
</code></pre>
<p>or with <code>__contains__</code> method.</p>
<pre><code>print filter(lambda x: x.__contains__("me... | 2 | 2016-06-20T16:03:47Z | [
"python",
"list",
"python-3.x"
] |
IndexError: list index out of range PYTHON (w/o using for loop) | 37,926,999 | <p>I am trying to find averages from a text file. The text file has columns of numbers and I want to find the average of each column. I get the follwoing error:
IndexError: list index out of range</p>
<p>The code I am using is:</p>
<pre><code>import os
os.chdir(r"path of my file")
file_open = open("name of my file",... | -2 | 2016-06-20T16:02:23Z | 37,927,049 | <p>The issue is you are trying to get the length of something in the array, not the array itself.</p>
<p>Try this: </p>
<p><code>length = len(list_of_lines)</code></p>
| 0 | 2016-06-20T16:04:28Z | [
"python"
] |
IndexError: list index out of range PYTHON (w/o using for loop) | 37,926,999 | <p>I am trying to find averages from a text file. The text file has columns of numbers and I want to find the average of each column. I get the follwoing error:
IndexError: list index out of range</p>
<p>The code I am using is:</p>
<pre><code>import os
os.chdir(r"path of my file")
file_open = open("name of my file",... | -2 | 2016-06-20T16:02:23Z | 37,927,057 | <p>You wrote <code>length = len(list_of_lines[0])</code></p>
<p><code>line_of_lines</code> is defined right above this line, as a list with 0 items in it. As a result, you cannot select the first item (index number 0) because index number 0 does not exist. Therefore, it is out of range.</p>
| 0 | 2016-06-20T16:04:43Z | [
"python"
] |
Can't seem to get any links to print using BeautifulSoup | 37,927,064 | <p>Hey i'm new to coding with modules and i'm trying to write a program that lists all the new anime episodes that have come out from a website just for some fun(nerdy i know). However I can't seem to be able to print of the links for the episodes and i'm not sure what is wrong. Could someone enlighten me please?</p>
... | 1 | 2016-06-20T16:05:22Z | 37,931,471 | <p>As you have seem there is up to five seconds to wait so you cannot parse the source with requests, what you get back is what you see when you are in the loading phase in your browser. You could do a get to <code>https://kissanime.to/cdn-cgi/l/chk_jschl/cdn-cgi/l/chk_jschl</code> passing <em>jschl_vc</em> and <em>pa... | 0 | 2016-06-20T20:42:21Z | [
"python",
"beautifulsoup",
"python-requests"
] |
How to create an empty mutable list in python, so that list item can be added later? | 37,927,241 | <p>I want to create an empty list in python so that I can add items into it later by a function. But when I tried to add items into it through function it showed me "TypeError: Can't convert 'tuple' object to str implicitly". Why am getting this?</p>
<pre><code>page = "There are many variations of passages of Lorem Ip... | -1 | 2016-06-20T16:15:01Z | 37,927,271 | <p>In the expression <code>word_positions.append(page.find((find_word, pos)))</code>, <code>page.find((find_word, pos))</code> passes a <code>tuple</code> to <code>page.find</code>, but <code>page.find</code> is expecting the first argument to be a string (the word to find). You want:</p>
<pre><code>page.find(find_wo... | 1 | 2016-06-20T16:16:34Z | [
"python",
"list",
"tuples",
"immutability",
"mutable"
] |
How to create an empty mutable list in python, so that list item can be added later? | 37,927,241 | <p>I want to create an empty list in python so that I can add items into it later by a function. But when I tried to add items into it through function it showed me "TypeError: Can't convert 'tuple' object to str implicitly". Why am getting this?</p>
<pre><code>page = "There are many variations of passages of Lorem Ip... | -1 | 2016-06-20T16:15:01Z | 37,927,462 | <p>How about:</p>
<pre><code>import re
page = "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, " \
"or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you ne... | 0 | 2016-06-20T16:27:15Z | [
"python",
"list",
"tuples",
"immutability",
"mutable"
] |
Python3: using matplotlib to create figure, using a dictionary | 37,927,270 | <p>I have got a dictionary in the form of <code>{test_size: (test_error, training_error)}</code> Here it is:</p>
<pre><code>{0.1: (0.94736842105263153, 0.90294117647058825), 0.2: (0.92105263157894735, 0.90397350993377479), 0.3: (0.82456140350877194, 0.9242424242424242), 0.6: (0.8722466960352423, 0.91390728476821192),... | 1 | 2016-06-20T16:16:34Z | 37,927,695 | <p>How about this,</p>
<p><a href="http://i.stack.imgur.com/LjyXQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/LjyXQ.png" alt="enter image description here"></a></p>
<hr>
<p>The source code, </p>
<pre><code>import matplotlib.pyplot as plt
import operator
fig, ax = plt.subplots()
d = {0.1: (0.94736842105... | 1 | 2016-06-20T16:42:07Z | [
"python",
"python-3.x",
"matplotlib"
] |
Open a HTML file with Python using Firefox when Firefox isn't the default browser | 37,927,327 | <p>I've seen a few questions related to this, but I'm still having trouble. </p>
<p>Running the code:</p>
<p><code>>>>webbrowser.get('firefox')</code> </p>
<p>errors with:</p>
<p><code>webbrowser.Error: could not locate runnable browser</code> </p>
<p>To troubleshoot I ran:</p>
<p><code>>>>print... | 4 | 2016-06-20T16:19:53Z | 37,927,823 | <blockquote>
<p>All would be right with the world except I need to send this program out to people who likely have IE set as their Windows default, and the HTML file has to be opened in Firefox.</p>
</blockquote>
<p>One way to solve it is to use the <a href="http://selenium-python.readthedocs.io/" rel="nofollow"><co... | 1 | 2016-06-20T16:49:05Z | [
"python",
"firefox",
"python-webbrowser"
] |
Replace every word after index k in list | 37,927,386 | <p>How do you replace every word after index[3] in list?</p>
<p>For example, I need to change first word to "How's" and second word to "it" and third word to "going?". Then, I need to change every word to "yo" after index[3]: </p>
<pre><code>input = "My name is bla bla bla?"
output = "How's it going? Yo! Yo! Yo!"
<... | 0 | 2016-06-20T16:22:58Z | 37,927,533 | <p>Try this:</p>
<pre><code>def hellohello(input):
if type(input) != str:
return "Input has to be string"
else:
new_input = input.split(' ')
if len(input) <= 3:
return "How's it going?"
else:
new_input[0] = "How's"
new_input[1] = "it"
... | 1 | 2016-06-20T16:31:37Z | [
"python",
"list",
"python-2.7",
"replace"
] |
Replace every word after index k in list | 37,927,386 | <p>How do you replace every word after index[3] in list?</p>
<p>For example, I need to change first word to "How's" and second word to "it" and third word to "going?". Then, I need to change every word to "yo" after index[3]: </p>
<pre><code>input = "My name is bla bla bla?"
output = "How's it going? Yo! Yo! Yo!"
<... | 0 | 2016-06-20T16:22:58Z | 37,927,578 | <p>Call me lazy, but I'd probably first create a list of length <code>len(new_input)</code> full of <code>'Yo!'</code> and then swap in the <code>["How's", "it", "going?"]</code> ...</p>
<pre><code>>>> s = "My name is bla bla bla?"
>>> new_input = s.split()
>>> output = ['Yo!'] * len(new_inp... | 2 | 2016-06-20T16:34:38Z | [
"python",
"list",
"python-2.7",
"replace"
] |
Send file via JSON instead of uploading to server, Django | 37,927,408 | <p>I have an app that currently allows a user to upload a file and it saves the file on the web server. My client has now decided to use a third party cloud hosting service for their file storage needs. The company has their own API for doing CRUD operations on their server, so I wrote a script to test their API and it... | 0 | 2016-06-20T16:24:20Z | 37,927,879 | <blockquote>
<p>The simplest way I can put this is that I want to avoid saving the
file to the web server entirely. I just want to encode the file, send
it as a payload, and discard it, if that's possible.</p>
</blockquote>
<p>From the <a href="https://docs.djangoproject.com/en/1.9/topics/http/file-uploads/#uplo... | 3 | 2016-06-20T16:52:27Z | [
"python",
"django"
] |
Python number of rng seeds | 37,927,577 | <p>In the docs (python 3.5) for initializing a random number from a seed:</p>
<blockquote>
<p>random.seed(a=None, version=2)</p>
<p>Initialize the random number generator.</p>
<p>If a is omitted or None, the current system time is used. If
randomness sources are provided by the operating system, they are... | 2 | 2016-06-20T16:34:35Z | 37,927,702 | <p>What's great about open source is the ability to simply view the code with a question. This is the <a href="https://github.com/python/cpython/blob/master/Lib/random.py#L115" rel="nofollow">source of <code>random.seed</code></a>:</p>
<pre><code>if a is None:
try:
# Seed with enough bytes to span the 1993... | 3 | 2016-06-20T16:42:24Z | [
"python",
"random"
] |
Running and R script that involves Packages from Python Code | 37,927,589 | <p>So I'm currently working on a simple python code to run a simple R script. The R script is only about 6 lines but uses the package "pracma". Using the subprocesses module in python, It runs the script but with the typical "Error in library(pracma) : there is no package called 'pracma' ". I am just looking for a simp... | 0 | 2016-06-20T16:35:09Z | 37,928,807 | <p>Thanks to @Dilettant for this:</p>
<p>Even when R can seemingly run the script individually without this, when running the R script from something like python, we need to make sure the script knows what path our library is in. This is achieved by adding this line to the start of the code:</p>
<pre><code> .libPaths... | 0 | 2016-06-20T17:52:10Z | [
"python",
"packages"
] |
subclassing property raising TypeError on __init__ | 37,927,612 | <p>I've subclassed property to try to add a lock to it so access to it is atomic(only one thread can read and write to it at one time). But I'm running into errors with the initializer and can't figure out why.</p>
<p>To be clear: I don't want to make a descriptor, I want to be able to use @atomic_property decorator i... | 1 | 2016-06-20T16:37:07Z | 37,928,031 | <p>You are far from properly subclassing <code>property</code> with your code: for once
you rewrite some methods, but never care to call the upstream method so it can do its business.</p>
<p>Not that it can't be done this way, if you actually reproduce in your subclass all behaviors the methods on the superclass would... | 2 | 2016-06-20T17:01:15Z | [
"python",
"concurrency",
"properties"
] |
subclassing property raising TypeError on __init__ | 37,927,612 | <p>I've subclassed property to try to add a lock to it so access to it is atomic(only one thread can read and write to it at one time). But I'm running into errors with the initializer and can't figure out why.</p>
<p>To be clear: I don't want to make a descriptor, I want to be able to use @atomic_property decorator i... | 1 | 2016-06-20T16:37:07Z | 37,928,037 | <p>It seems that using <code>property.setter</code> calls the <code>__init__</code> again, which seems odd (initialize the same object more then once?)</p>
<p>Anyway you need to let <code>property</code> do it's job, how do you expect it to work correctly if you don't use <code>property.__init__</code> at all? You co... | 1 | 2016-06-20T17:01:33Z | [
"python",
"concurrency",
"properties"
] |
Python: loop optimization | 37,927,631 | <p>I am quite new to Python but I've started using it for some data analysis and now I love it. Before, I used C, which I find just terrible for file I/O.</p>
<p>I am working on a script which computes the <a href="https://en.wikipedia.org/wiki/Radial_distribution_function" rel="nofollow">radial distribution function<... | 3 | 2016-06-20T16:38:03Z | 37,928,570 | <p>If memory is not an issue (and it probably isn't given that the actual amount of data won't be different from what you are doing now), you can use <code>numpy</code> to do the math for you and put everything into an <code>NxN</code> array (around 800MB at 8 bytes/<code>float</code>).</p>
<p>Given the operations you... | 3 | 2016-06-20T17:36:47Z | [
"python",
"loops"
] |
Python: loop optimization | 37,927,631 | <p>I am quite new to Python but I've started using it for some data analysis and now I love it. Before, I used C, which I find just terrible for file I/O.</p>
<p>I am working on a script which computes the <a href="https://en.wikipedia.org/wiki/Radial_distribution_function" rel="nofollow">radial distribution function<... | 3 | 2016-06-20T16:38:03Z | 37,940,247 | <p>You've got an interesting problem there. There are some common guidelines for high performance Python; these are for Python2 but should carry for the most part to Python3. </p>
<ul>
<li>Profile your code. Using %timeit and %%timeit on jupyter/ipython is quick and fast for interactive sessions, but cProfile and line... | 2 | 2016-06-21T09:16:13Z | [
"python",
"loops"
] |
In my models.py, one ForeignKey declaration does not require a default, but the other does? Why? | 37,927,765 | <p>In attempting to run <code>manage.py makemigrations</code>, I received the following error:</p>
<pre><code>You are trying to add a non-nullable field 'menu_category' to fooditem without
a default; we can't do that (the database needs something to populate existing
rows.
</code></pre>
<p>My code is as follows:</p>... | 0 | 2016-06-20T16:45:48Z | 37,928,930 | <p>You're adding only a single new column called <code>menu_category</code>, right? The <code>restaurant</code> field does not give errors because it already exists.</p>
<p>Django gives you this error because you are adding a field that can't be null to a table that already exists without a default value. You either n... | 1 | 2016-06-20T17:58:46Z | [
"python",
"django"
] |
Python Google App Engine Internal Server Error | 37,927,874 | <p>I am new to app engine and trying to deploy a python app. The app works correctly when I preview it on my local host but when I deploy it I get the following error: "Internal Server Error</p>
<p>The server has either erred or is incapable of performing the requested operation."</p>
<p>And traceback:</p>
<pre><cod... | -1 | 2016-06-20T16:52:15Z | 37,930,009 | <p>If this is a new/recent deployment of the app it's possible for the newly added/modified indexes to be still building, the condition is transitory and will eventually go away. See this answer: <a href="http://stackoverflow.com/a/29807764/4495081">http://stackoverflow.com/a/29807764/4495081</a>.</p>
<p>It's possible... | 1 | 2016-06-20T19:06:40Z | [
"python",
"google-app-engine"
] |
Python list type list concatenation , random module | 37,927,976 | <p>What I want to achieve : a list of posible combinations of n coin flips</p>
<p>What I get when I run this code : a list that contains letters from the 2 posible outcomes "heads" and "tails" . Why? I could not figure out .</p>
<pre><code>def randomlist(n):
l = []
for i in range(n):
a = random.randint(1,2)
i... | 1 | 2016-06-20T16:57:52Z | 37,928,009 | <p>Try using <code>append</code> instead of slice assignment.</p>
<pre><code>def randomlist(n):
l = []
for i in range(n):
a = random.randint(1,2)
if a == 1:
l.append("heads")
else:
l.append("tails")
return l
</code></pre>
| 2 | 2016-06-20T16:59:39Z | [
"python",
"python-3.x"
] |
Python list type list concatenation , random module | 37,927,976 | <p>What I want to achieve : a list of posible combinations of n coin flips</p>
<p>What I get when I run this code : a list that contains letters from the 2 posible outcomes "heads" and "tails" . Why? I could not figure out .</p>
<pre><code>def randomlist(n):
l = []
for i in range(n):
a = random.randint(1,2)
i... | 1 | 2016-06-20T16:57:52Z | 37,928,300 | <p>To generate a random list of <code>n</code> coin flips, you can also use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to express the same logic in a more concise way:</p>
<pre><code>>>> import random
>>>
>>> ... | 0 | 2016-06-20T17:19:23Z | [
"python",
"python-3.x"
] |
Python list type list concatenation , random module | 37,927,976 | <p>What I want to achieve : a list of posible combinations of n coin flips</p>
<p>What I get when I run this code : a list that contains letters from the 2 posible outcomes "heads" and "tails" . Why? I could not figure out .</p>
<pre><code>def randomlist(n):
l = []
for i in range(n):
a = random.randint(1,2)
i... | 1 | 2016-06-20T16:57:52Z | 37,928,627 | <p>You can also use the <code>itertools</code> library. It becomes really simple like that.</p>
<pre><code>>>> from itertools import product
>>> product(['heads','tails'], repeat=3) # change the repeat parameter to set the length
<itertools.product object at 0x0000000003B715A0>
>>> im... | 0 | 2016-06-20T17:40:03Z | [
"python",
"python-3.x"
] |
Python sockets; sending from client receiving on server | 37,928,047 | <p>I am trying to send messages on TCP/IP all on host machine. This is working, although for some reason the socket needs to be re-instantiated for every new message on the client side only. For example here is a basic client that sends three separate messages: </p>
<pre><code>import socket
host = '127.0.0.1'
cl... | 0 | 2016-06-20T17:02:11Z | 37,928,819 | <p>It's even worse than you think. Take a look at your server code. <code>exp.Server.accept()</code> accepts a connection from the client, but <code>connection.receive()</code> ignores that connection completely and does a second <code>self.Server.accept()</code>. You ignore half of your connections!</p>
<p>Next, your... | 0 | 2016-06-20T17:52:53Z | [
"python",
"sockets",
"tcp"
] |
Simulate multiple users in Grinder | 37,928,096 | <p>I was wondering if this is even possible. I just set up Grinder and ran some base test but what if I want to have each thread be a different user? I see this line of code in the file that is generated (I am not a python developer)-could I somehow pass the username/password as a variable?</p>
<pre><code> # Expect... | 0 | 2016-06-20T17:05:25Z | 38,140,528 | <p>So what I have done is maintain the users in a csv file and read them into an array . Now for eg there are 3 threads you can use a multiple of grinder.getRunNumber& grinder.getThreadNumber(check the exact api name) and extract that record dynamically .
Move the user1 & pass1 to a global scope and perform all... | 0 | 2016-07-01T08:24:11Z | [
"python",
"load-testing",
"grinder"
] |
Django - How to save "Google Maps Polygon" to Model? | 37,928,101 | <p>I want to create a polygon on Googlemaps, which should be posted to my postgres-database using Django/GeoDjango.</p>
<p>User select their area via Google Maps, Polygon should be saved.
i want to todo calculations on these Polygons.
On the other hand, other polygons should be displayed on the map.</p>
<p>I think, I... | 1 | 2016-06-20T17:05:53Z | 37,928,683 | <p>I'm not 100% I understand what you're asking, but the typical way to do that will be this:</p>
<pre><code>area = Area()
area.owner = request.User
area.poly = polygon_data # Assumes you have a variable set to your polygon data
area.objects = object_data # Assumes you have a variable set to your geo object data
area.... | 0 | 2016-06-20T17:43:03Z | [
"javascript",
"python",
"django",
"google-maps",
"polygon"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.