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 |
|---|---|---|---|---|---|---|---|---|---|
How to add a new line in an open txt file in python? | 37,649,529 | <p>I'm trying to write a program by change an open file, and I need to add a new line in the print.</p>
<p>In the open txt.file, it shows like this (I use"_" replace blank):</p>
<p>Name_____Height(m)_____Weight(kg)</p>
<p>Bill________1.58__________58</p>
<p>Mary_____1.65__________43</p>
<p>...</p>
<p>And now I wa... | 1 | 2016-06-06T04:26:02Z | 37,650,196 | <p>If by "add a new vertical line" you mean "add a new <em>column</em>" to your file, you can do this with the help of the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow"><code>csv</code></a> module.</p>
<p>The code below works by reading the contents of your file as a list, making the changes, and... | 0 | 2016-06-06T05:37:56Z | [
"python",
"python-3.x"
] |
How to add a new line in an open txt file in python? | 37,649,529 | <p>I'm trying to write a program by change an open file, and I need to add a new line in the print.</p>
<p>In the open txt.file, it shows like this (I use"_" replace blank):</p>
<p>Name_____Height(m)_____Weight(kg)</p>
<p>Bill________1.58__________58</p>
<p>Mary_____1.65__________43</p>
<p>...</p>
<p>And now I wa... | 1 | 2016-06-06T04:26:02Z | 37,650,373 | <p>I wrote a little class to do everything you asked for and more. Implementation examples are done at the bottom. Let me know if this works for you.</p>
<pre><code>class Feed(object):
def __init__(self, file_name, sep, naming_convention=None):
self.file_name = file_name
self.feed_item_naming = nam... | 0 | 2016-06-06T05:53:36Z | [
"python",
"python-3.x"
] |
simple prediction using Pearson correlation and linear regression with python | 37,649,608 | <p>i have a data set like this </p>
<pre><code> Value Month Year
103.4 April 2006
270.6 August 2006
51.9 December 2006
156.9 February 2006
126.9 January 2006
96.8 July 2006
183.1 June 2006
266.6 March 2006
193.1... | 0 | 2016-06-06T04:36:48Z | 37,650,186 | <p>There is not the best solution, but it works.</p>
<p>Little explanation: I have substituted month on their indexes in the list, it is necessary for algorithm.
Also I have substituted spaces delimeters on ';' delimeters, because in different rows was different number of spaces and it was not convinient. Now your dat... | 0 | 2016-06-06T05:37:31Z | [
"python",
"linear-regression",
"pearson-correlation"
] |
Interpret columns of zeros and ones as binary and store as an integer column | 37,649,829 | <p>I have a dataframe of zeros and ones. I want to treat each column as if its values were a binary representation of an integer. What is easiest way to make this conversion?</p>
<p>I want this:</p>
<pre><code>df = pd.DataFrame([[1, 0, 1], [1, 1, 0], [0, 1, 1], [0, 0, 1]])
print df
0 1 2
0 1 0 1
1 1 1 ... | 2 | 2016-06-06T05:01:09Z | 37,649,884 | <p>You can create a string from the column values and then use <code>int(binary_string, base=2)</code> to convert to integer:</p>
<pre><code>df.apply(lambda col: int(''.join(str(v) for v in col), 2))
Out[6]:
0 12
1 6
2 11
dtype: int64
</code></pre>
<p>Not sure about efficiency, multiplying by the relevant ... | 2 | 2016-06-06T05:06:22Z | [
"python",
"numpy",
"pandas",
"binary",
"integer"
] |
Interpret columns of zeros and ones as binary and store as an integer column | 37,649,829 | <p>I have a dataframe of zeros and ones. I want to treat each column as if its values were a binary representation of an integer. What is easiest way to make this conversion?</p>
<p>I want this:</p>
<pre><code>df = pd.DataFrame([[1, 0, 1], [1, 1, 0], [0, 1, 1], [0, 0, 1]])
print df
0 1 2
0 1 0 1
1 1 1 ... | 2 | 2016-06-06T05:01:09Z | 37,650,516 | <p>Similar solution, but more faster:</p>
<pre><code>print (df.T.dot(1 << np.arange(df.shape[0] - 1, -1, -1)))
0 12
1 6
2 11
dtype: int64
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>In [81]: %timeit df.apply(lambda col: int(''.join(str(v) for v in col), 2))
The slowest run took 5.66 tim... | 3 | 2016-06-06T06:04:52Z | [
"python",
"numpy",
"pandas",
"binary",
"integer"
] |
I'm having trouble printing a file in Python | 37,649,866 | <p>So I'm trying to open a file and store it's contents as a variable. It feels like this should be really simple but I am not getting what I want.
This is my code:</p>
<pre><code>file = str(input('enter a file name to decipher: '))
DAta = open(file,'r')
print(DAta.read)
</code></pre>
<p>And I thought that this would... | 0 | 2016-06-06T05:05:11Z | 37,649,960 | <p>@abby call read method by including round paranthesis like this read(), you should print content of your file like this DAta.read() and after reading the content of file, always make a habit of closing the file with close() method DAta.close().</p>
| 0 | 2016-06-06T05:14:25Z | [
"python",
"python-3.x"
] |
I'm having trouble printing a file in Python | 37,649,866 | <p>So I'm trying to open a file and store it's contents as a variable. It feels like this should be really simple but I am not getting what I want.
This is my code:</p>
<pre><code>file = str(input('enter a file name to decipher: '))
DAta = open(file,'r')
print(DAta.read)
</code></pre>
<p>And I thought that this would... | 0 | 2016-06-06T05:05:11Z | 37,649,961 | <p>You need to call the <code>read</code> method, which is done by following it with parentheses. Without them, it is simply a bound method. So use:</p>
<pre><code>print(DAta.read())
</code></pre>
<p>Also, it's a good idea to close a file when you're done accessing it:</p>
<pre><code>DAta.close()
</code></pre>
| 1 | 2016-06-06T05:14:53Z | [
"python",
"python-3.x"
] |
I'm having trouble printing a file in Python | 37,649,866 | <p>So I'm trying to open a file and store it's contents as a variable. It feels like this should be really simple but I am not getting what I want.
This is my code:</p>
<pre><code>file = str(input('enter a file name to decipher: '))
DAta = open(file,'r')
print(DAta.read)
</code></pre>
<p>And I thought that this would... | 0 | 2016-06-06T05:05:11Z | 37,650,023 | <p>read is a <strong>method</strong> from File class, so you must add ()</p>
<pre><code>DAta.read()
</code></pre>
| 0 | 2016-06-06T05:20:32Z | [
"python",
"python-3.x"
] |
Django 1.8 throws an error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | 37,649,898 | <p>There is no perfect explanation for this question, can any one please explain why this error is getting raised</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/managemen... | 0 | 2016-06-06T05:07:52Z | 37,650,693 | <p>Installed app should contain only the django apps that you want to include in your application, i see you have added app and app.views. views is not an app, it's a python file present in the app directory please remove that and try to migrate. </p>
<p>Also please add you custom apps after django's default apps for ... | 0 | 2016-06-06T06:18:45Z | [
"python",
"django"
] |
Python split list elements | 37,649,919 | <p>I have a list:</p>
<pre><code>lines = [['1 1 4.59114 0.366832 -9.56424 '], ['2 1 5.24742 -0.870574 -8.40649 '], ['3 2 5.21995 -0.38856 -7.39145 ']]
</code></pre>
<p>I want to split each individual element of the list as follows:</p>
<pre><code>[['1', '1 4.59114', '0.366832', '-9.56424'], ['2', '1', '5.24742', '-0... | 1 | 2016-06-06T05:10:26Z | 37,649,945 | <p>You need to <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a> on the whitespace character and not on the tab <code>\t</code>:</p>
<pre><code>>>> lines = [['1 1 4.59114 0.366832 -9.56424 '], ['2 1 5.24742 -0.870574 -8.40649 '], ['3 2 5.21995 -0.38856 -... | 4 | 2016-06-06T05:13:10Z | [
"python",
"list"
] |
Python split list elements | 37,649,919 | <p>I have a list:</p>
<pre><code>lines = [['1 1 4.59114 0.366832 -9.56424 '], ['2 1 5.24742 -0.870574 -8.40649 '], ['3 2 5.21995 -0.38856 -7.39145 ']]
</code></pre>
<p>I want to split each individual element of the list as follows:</p>
<pre><code>[['1', '1 4.59114', '0.366832', '-9.56424'], ['2', '1', '5.24742', '-0... | 1 | 2016-06-06T05:10:26Z | 37,649,963 | <p>It is a list of list of strings. </p>
<pre><code>lines[0][0].split(' ') # lines[0][0] is a string so you can use split
</code></pre>
<p>will give you ['1', '1', '4.59114', '0.366832', '-9.56424', '']</p>
<p>You can do</p>
<pre><code>[x[0].split(' ') for x in lines]
</code></pre>
<p>to get the desired result.</p... | 1 | 2016-06-06T05:15:03Z | [
"python",
"list"
] |
Speech to Text using Python | 37,649,949 | <p>How can I do a very accurate speech to text conversion using python ? Is it possible to do this with the use of some Python modules ? I have tried speech recognition module but failed to achieve the task. can you guys help ?</p>
| 0 | 2016-06-06T05:13:22Z | 37,881,897 | <p>"very accurate" is depends on your accent. i suggest you:</p>
<p><a href="https://pypi.python.org/pypi/SpeechRecognition/" rel="nofollow">Google Speech Recognition</a></p>
<p><strong>English is not the best choice for accuracy, you main language is. (accent)</strong></p>
<p>first, you have to install python 2.x/3... | 0 | 2016-06-17T12:44:02Z | [
"python"
] |
dict of dict to pandas dataframe | 37,649,966 | <p>I have a dict of dict following the format:</p>
<pre><code>{ row_name : { column_name : column_value } }
</code></pre>
<p>I want to convert this dictionary into a pandas dataframe:</p>
<pre><code>row_name1 | column_name1.1 | column_name1.2 | column_name1.3 |
--------------------------------------------------... | 1 | 2016-06-06T05:15:20Z | 37,650,038 | <p><code>DataFrame.from_dict</code> does this, in your case the <code>orient</code> argument needs to be <code>'index'</code> rather than <code>'columns'</code> since you have row keys in the outer dictionary:</p>
<pre><code>dd = {'rowA': {'colA': 1, 'colB': 2},
'rowB': {'colA': 3, 'colB': 4}}
df = pd.DataFrame.... | 2 | 2016-06-06T05:22:55Z | [
"python",
"dataframe"
] |
Want to display rating stars in django | 37,650,068 | <p>I am in new in django and i have a model "album" which has 3 fileds title , genre and rating and i am displaying them i a table and i want to display the digit"0" as many time as album.rating and i am using for loop from 0 to album.rating but it is displaying only once i.e if the album.rating is 2 then "0" should... | 0 | 2016-06-06T05:26:04Z | 37,650,661 | <p>Since you could not get the way to implement, after explaining:</p>
<p><code>{% for i in album.rating %}</code> is like <code>{% for i in 2 %}</code> in your case, which turns out that, for a single digit, it's going to loop once. use range filter or so on.</p>
<p>I can suggest the quickest way to get it implement... | 0 | 2016-06-06T06:16:13Z | [
"python",
"django",
"rating"
] |
How to make indexes in pygrib (grib2 files)? | 37,650,178 | <p>I'm trying to read grib2 file using pygrib from <a href="ftp://ftpprd.ncep.noaa.gov/pub/data/nccf/com/hourly/prod/uv.20160605/" rel="nofollow">here</a>. But it takes more than 4-5 hours to read the entire 120 files. So I tried making indexes to read the file faster. Whenever I try to make a index on the value key, I... | 1 | 2016-06-06T05:36:35Z | 37,783,523 | <p><code>grib_ls</code> shows on file of such type:</p>
<pre><code>edition centre date dataType gridType stepRange typeOfLevel level shortName packingType
2 kwbc 20160612 fc regular_ll 12 surface 0 uvi grid... | 0 | 2016-06-13T06:58:40Z | [
"python",
"grib",
"noaa"
] |
How to read text file with uneven number of columns with python-pandas? | 37,650,184 | <p>Given the file with following format:</p>
<pre><code>really:1 christensen:1 scariest:1 many_of:1 label:positive
varied_experiences:1 experiences_from:1 island_resident:1 many_and:1 label:positive
scariest:1 many_of:1 label:negative
</code></pre>
<p>The last column is the label of polarity, with values negative or ... | 2 | 2016-06-06T05:37:26Z | 37,650,325 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> only:</p>
<pre><code>import pandas as pd
import io
temp=u"""really:1 christensen:1 scariest:1 many_of:1 label:positive
varied_experiences:1 experiences_from:1 island_resident:1 man... | 1 | 2016-06-06T05:49:13Z | [
"python",
"pandas",
"dataframe"
] |
How to start using python on Linux Hosting | 37,650,192 | <p>I want to use python for my website.I have a Single Domain Linux hosting from BigRock. And I'hd SSH to my website to check if it has Python Installed so i did >>python -v it turns out python 2.6.6 is already Installed. BigRock support Team asked me to put:</p>
<pre><code>*Options +ExecCGI
**AddHandler cgi-script .... | 0 | 2016-06-06T05:37:45Z | 37,653,513 | <p>Adding Content Type Resolved The Problem.</p>
<p>For Those Who face Same Problem Here is The check List:</p>
<p>Make sure you have Python Installed:</p>
<blockquote>
<blockquote>
<p>You can SSH your website then type [ python -v ] on terminal it will show you which version of python is Installed.</p>
</bl... | 0 | 2016-06-06T09:09:17Z | [
"python",
"linux",
"server",
"cgi",
"web-hosting"
] |
Find the shortest interleaved string of A and B with Dynamic Programming | 37,650,206 | <p>I'm having a problem with a question on dynamic programming.</p>
<p>Given two strings A and B find the shortest interleaved string of the two.</p>
<p>For example for <code>A = "APPLE"</code>, <code>B = "ABSOLUTE"</code></p>
<p>The shortest answer will be <code>"ABPPSOLUTE"</code>
Instead answer my function return... | 2 | 2016-06-06T05:38:54Z | 37,650,921 | <p>Here's some ideas to get you started.</p>
<p>The tag wiki for dynamic programming describes it as:</p>
<blockquote>
<p>Dynamic programming is an algorithmic technique for efficiently solving problems with a recursive structure containing many overlapping subproblems</p>
</blockquote>
<p>So first, try and think ... | 4 | 2016-06-06T06:35:58Z | [
"python",
"string",
"algorithm",
"dynamic-programming",
"interleave"
] |
Flask can't find app file | 37,650,208 | <p>In <a href="http://flask.pocoo.org/docs/0.11/tutorial/setup/#tutorial-setup" rel="nofollow">Step 2</a> of the official Flask tutorial, Flask cannot find my app file because it's looking in <code>../venv/Scripts/</code> instead of where I run the command. How can I tell Flask to look in the right place? </p>
<pre><c... | 4 | 2016-06-06T05:39:13Z | 37,707,967 | <p>There seems to a bug according to this github issue:</p>
<p><a href="https://github.com/pallets/flask/issues/1829">https://github.com/pallets/flask/issues/1829</a></p>
<p>As a workaround you can do</p>
<pre><code>>python -m flask run
</code></pre>
<p>You can also use <code>>python -m flask initdb</code> later... | 5 | 2016-06-08T16:24:49Z | [
"python",
"flask"
] |
wxpython on Mac - button style | 37,650,267 | <p>I am using wxPython3.0-osx-cocoa-py2.7 on Mac 10.11.5 with python 2.7.11. Looking at the documentation, for wxmac it show the buttons looking like this:</p>
<p><a href="http://i.stack.imgur.com/QLiyh.png" rel="nofollow"><img src="http://i.stack.imgur.com/QLiyh.png" alt="enter image description here"></a></p>
<p>Bu... | 1 | 2016-06-06T05:44:35Z | 37,668,462 | <p>The image in the documentation was from a screenshot in an older version of OSX. Since wxPython uses the native widgets, then they always look the same as the widgets in the current version of the OS (because they are the same widget).</p>
| 2 | 2016-06-06T23:46:15Z | [
"python",
"osx",
"python-2.7",
"cocoa",
"wxpython"
] |
Convert string searched with regexp into lowercase with Python | 37,650,677 | <p>I have some broken XML (the example is not broken, but the document it is) that a part of it looks like this:</p>
<pre><code><sp who="#FERN">
<speaker>FERNANDO</speaker>
<p>Un instante. Soy un hombre. Huir serÃa cobarde... ¡Sin defenderse! ¡Sin salvarte!... Va a venir... con la vara del g... | 1 | 2016-06-06T06:17:30Z | 37,650,741 | <p>You may use anonymous function inside <code>re.sub</code></p>
<pre><code>>>> s = '''<sp who="#FERN">
<speaker>FERNANDO</speaker>
<p>Un instante. Soy un hombre. Huir serÃa cobarde... ¡Sin defenderse! ¡Sin salvarte!... Va a venir... con la vara del guardia. ¡Ay, que ya la conoces!... | 1 | 2016-06-06T06:22:02Z | [
"python",
"regex",
"xml"
] |
Python: fixed wait time for receiving socket data | 37,650,716 | <p>I wrote a udp server and client. The client send simple udp messages to the server and the server will respond. The server will randomly drop some response packets. In my client side code, I wrote the following line</p>
<pre><code>for i in range(0,10):
sequence_number = i
start = time.time()
clientSocket.send... | 2 | 2016-06-06T06:20:40Z | 37,651,312 | <p>The link with <code>settimeout()</code> was right. It raises a Exception when timeout. </p>
<blockquote>
<p>Set a timeout on blocking socket operations. The value argument can be
a nonnegative floating point number expressing seconds, or None. If a
non-zero value is given, subsequent socket operations will ra... | 3 | 2016-06-06T07:01:18Z | [
"python",
"sockets"
] |
Python 2.7 - Invalid Literal Errors | 37,650,733 | <p><strong>Python Version</strong> - 2.7.11</p>
<p>I am following Zed Shaw's <strong>Learn Python the Hard Way</strong> and am currently at <a href="http://learnpythonthehardway.org/book/ex21.html" rel="nofollow">Exercise 21</a></p>
<p>I am trying to modify the code so that the script prompts the user to enter the va... | 1 | 2016-06-06T06:21:28Z | 37,650,820 | <p>I think you might have meant to split the values? </p>
<pre><code>nums = map(float, raw_input('Enter 2 numbers').split(','))
age = add(*nums)
</code></pre>
<p><a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map</code></a> will apply a function, in this case <a href="https://doc... | 2 | 2016-06-06T06:27:42Z | [
"python",
"python-2.7"
] |
Python 2.7 - Invalid Literal Errors | 37,650,733 | <p><strong>Python Version</strong> - 2.7.11</p>
<p>I am following Zed Shaw's <strong>Learn Python the Hard Way</strong> and am currently at <a href="http://learnpythonthehardway.org/book/ex21.html" rel="nofollow">Exercise 21</a></p>
<p>I am trying to modify the code so that the script prompts the user to enter the va... | 1 | 2016-06-06T06:21:28Z | 37,650,898 | <p>You need to split your input into two numbers <strong>before</strong> converting these to float; use <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a>:</p>
<pre><code>while True:
ages = raw_input('Enter 2 numbers')
try:
age1, age2 = [floa... | 3 | 2016-06-06T06:33:57Z | [
"python",
"python-2.7"
] |
Python 2.7 - Invalid Literal Errors | 37,650,733 | <p><strong>Python Version</strong> - 2.7.11</p>
<p>I am following Zed Shaw's <strong>Learn Python the Hard Way</strong> and am currently at <a href="http://learnpythonthehardway.org/book/ex21.html" rel="nofollow">Exercise 21</a></p>
<p>I am trying to modify the code so that the script prompts the user to enter the va... | 1 | 2016-06-06T06:21:28Z | 37,650,903 | <p>try this.</p>
<pre><code>age1,age2=(float(x) for x in raw_input('Age_1, Age_2: ').split(','))
print add(age1,age2)
</code></pre>
<p><code>.split(n)</code> will create a list from a string by splitting the string at each index of n. Code is the same as:</p>
<pre><code>n = raw_input('Age_1, Age_2')
n = n.split(',')... | 0 | 2016-06-06T06:34:22Z | [
"python",
"python-2.7"
] |
Python 2.7 - Invalid Literal Errors | 37,650,733 | <p><strong>Python Version</strong> - 2.7.11</p>
<p>I am following Zed Shaw's <strong>Learn Python the Hard Way</strong> and am currently at <a href="http://learnpythonthehardway.org/book/ex21.html" rel="nofollow">Exercise 21</a></p>
<p>I am trying to modify the code so that the script prompts the user to enter the va... | 1 | 2016-06-06T06:21:28Z | 37,651,078 | <p>If you would like the user to input multiple values you will need to change your code up. As raw_input() can only unpack one value.</p>
<p>for example, you cannot input a tuple and have raw_input() unpack it</p>
<pre><code>>>> a, b = raw_input('enter two numbers: ')
>>> enter two numbers: 69, 420... | 0 | 2016-06-06T06:45:35Z | [
"python",
"python-2.7"
] |
Return list of objects within abject's attribute when many equals True, in Django Rest Framework | 37,650,881 | <p>In DRF, how can I return a list of objects inside an array within an object's attribute, instead of a direct array.</p>
<p>Let's say I execute the following code:</p>
<pre><code>people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
print(serializer.data)
</code></pre>
<p>The output would ... | 0 | 2016-06-06T06:32:25Z | 37,650,945 | <p>Simply do:</p>
<pre><code>people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
serializer.data = {'people': serializer.data}
print(serializer.data)
</code></pre>
| 2 | 2016-06-06T06:37:27Z | [
"python",
"django",
"django-rest-framework"
] |
XGBoost on python : what is wrong with xgb.cv? | 37,650,892 | <p>I'm trying to use xgboost on python</p>
<p>here is my code. xgb.train works but i get on error with xgb.cv
although it seems i used it the correct way </p>
<p>the following works for me</p>
<pre><code>###### XGBOOST ######
import datetime
startTime = datetime.datetime.now()
import xgboost as xgb
data_train =... | 1 | 2016-06-06T01:27:36Z | 37,650,893 | <p>Here is the signature of <code>xgboost.cv</code>, copied from the documentation</p>
<blockquote>
<p>xgboost.cv(params, dtrain, num_boost_round=10, nfold=3, stratified=False, folds=None, metrics=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, fpreproc=None, as_pandas=True, verbose_eval=None, ... | 1 | 2016-06-06T02:29:46Z | [
"classification",
"python"
] |
Convert each cell of a Pandas's column from list to word-count dictionary? | 37,650,913 | <p>There's a column of a DataFrame, <code>df['Title']</code>, where each row is a book sold at a location, <code>LOCATION_ID</code>. I'd like to group the <code>df</code> by <code>LOCATION_ID</code> and create a new DataFrame that has two columns: <code>LOCATION_ID</code> and a <code>Title-Count</code>dictionary of th... | 0 | 2016-06-06T06:35:04Z | 37,652,713 | <p>Use <code>agg</code> instead of <code>apply</code>:</p>
<pre><code>import numpy as np
import pandas as pd
from collections import Counter
prng = np.random.RandomState(0)
df = pd.DataFrame({'LOCATION_ID': prng.choice([1, 2, 3], 1000), 'TITLE': [''.join(prng.choice(list("abcd"), 3)) for _ in range(1000)]})
df.head()
... | 2 | 2016-06-06T08:25:11Z | [
"python",
"dictionary",
"pandas",
"counter"
] |
JSONSchema Resource that hints at its schema | 37,650,927 | <p>I'm trying to discover the best way to get a resource to somehow indicate the schema that should be used to validate it.</p>
<p>I need this because there may come a time where I need to return an array full of different resources. In this case I'd need each resource in the array to tell me what schema it is suppose... | 1 | 2016-06-06T06:36:14Z | 37,669,547 | <p>The way to handle something like this in JSON Schema is to use the <code>anyOf</code> constraint.</p>
<pre><code>{
"type": "array",
"items": {
"anyOf": [
{ "$ref": "car.json" },
{ "$ref": "helicopter.json" }
]
}
}
</code></pre>
<p>This way the client doesn't need to tell you what schema t... | 1 | 2016-06-07T02:23:51Z | [
"python",
"jsonschema"
] |
Generate bigrams with NLTK | 37,651,057 | <p>I am trying to produce a bigram list of a given sentence for example, if I type,</p>
<pre><code> To be or not to be
</code></pre>
<p>I want the program to generate </p>
<pre><code> to be, be or, or not, not to, to be
</code></pre>
<p>I tried the following code but just gives me </p>
<pre><code>&l... | 0 | 2016-06-06T06:44:47Z | 37,651,184 | <p><a href="http://www.nltk.org/api/nltk.html#nltk.util.bigrams" rel="nofollow"><code>nltk.bigrams()</code></a> returns an iterator (a generator specifically) of bigrams. If you want a list, pass the iterator to <code>list()</code>. It also expects a sequence of items to generate bigrams from, so you have to split the ... | 3 | 2016-06-06T06:52:22Z | [
"python",
"nltk",
"n-gram"
] |
Django create a dict with values of a model field as key and model instance as value | 37,651,068 | <p>I have a model <code>Quest</code> and it has a field <code>type</code>. I want to have a dict that maps <code>type</code> to a list of <code>Quest</code>. My current way of doing it is just iterating over all the <code>Quest</code> objects and append them to the list.</p>
<pre><code>from collections import defaultd... | 0 | 2016-06-06T06:45:09Z | 37,651,306 | <p>I am not aware of any such django <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/" rel="nofollow"><code>QuerySet</code></a> functionality. You could, however, use the query to already order your quests by <code>type</code> so that you can use <a href="https://docs.python.org/2/library/itertools.... | 0 | 2016-06-06T07:00:44Z | [
"python",
"django",
"django-queryset"
] |
Python-style variables in C++ | 37,651,358 | <p>I'm working on a C++ project and am trying to figure out how to make a "dynamic" variable.</p>
<p>In Python, variables can have multiple types:</p>
<pre><code>variable = 0
variable = "Hello"
</code></pre>
<p>In Java, this is also (somewhat) achievable:</p>
<pre><code>Object o = 0;
o = "Hello";
</code></pre>
<p>... | 3 | 2016-06-06T07:04:38Z | 37,651,398 | <p>You can use <a href="http://www.boost.org/doc/libs/1_61_0/doc/html/variant.html" rel="nofollow">boost.variant</a> library. Basic usage instructions <a href="http://www.boost.org/doc/libs/1_61_0/doc/html/variant/tutorial.html#variant.tutorial.basic" rel="nofollow">here</a>. In short, it would be something like</p>
<... | 7 | 2016-06-06T07:06:53Z | [
"python",
"c++",
"types",
"type-safety",
"strong-typing"
] |
Python-style variables in C++ | 37,651,358 | <p>I'm working on a C++ project and am trying to figure out how to make a "dynamic" variable.</p>
<p>In Python, variables can have multiple types:</p>
<pre><code>variable = 0
variable = "Hello"
</code></pre>
<p>In Java, this is also (somewhat) achievable:</p>
<pre><code>Object o = 0;
o = "Hello";
</code></pre>
<p>... | 3 | 2016-06-06T07:04:38Z | 37,652,115 | <p>Every language has its own idiomatic constructs, and you should <strong>not</strong> try to mimic Python code in C++. As said by @user2296177 , the closest C++ tool (in current version) is boost::any, which is also included in C++17 as std::any.</p>
<p>But even boost:any has some limitations: types assigned to a bo... | 3 | 2016-06-06T07:49:06Z | [
"python",
"c++",
"types",
"type-safety",
"strong-typing"
] |
sqlite3 create another database from an existing database | 37,651,373 | <p>I have a large dataset from which a subset based on some columns' values is wanted. I want to create another database from this subset. How would I do that with sqlite3 in Python? </p>
<pre><code>The column from which I want to compare to get the subset contain date in the format of YYYYMMDD e.g. 20120429.
I want ... | 0 | 2016-06-06T07:05:33Z | 37,659,892 | <p>You can <code>attach</code> the new DB file to an already existing SQLite connection (which has your existing DB open), then simply use the appropriate <code>insert</code> statement to copy the rows you want, adressing the tables in the attached DB using the DB alias:</p>
<pre><code>attach 'newdb.sqlite' as newdb;
... | 0 | 2016-06-06T14:21:47Z | [
"python",
"sql",
"sqlite3"
] |
Get to self.request.user in test python | 37,651,374 | <p>I want to make tests for app, and I just can't make it right.
I have such function:</p>
<pre><code>def get_queryset(self):
return User.objects.filter(id=self.request.user.id)
</code></pre>
<p>And I wrote such test:</p>
<pre><code> def test_Uzytkownik_get_query(self):
self.c = Client()
self.user = User... | -2 | 2016-06-06T07:05:41Z | 37,652,191 | <p>You're calling <code>get_queryset</code> on your view class, not in an instance. But since it is an instance method, it expects the instance as the first parameter, <code>self</code>. So it takes what you have actually passed as the first parameter, the user, and assigns that to self instead, hence the error.</p>
<... | 2 | 2016-06-06T07:54:20Z | [
"python",
"django",
"django-views",
"django-tests"
] |
How to get the cell at a location in pandas dataframe using a column as the index | 37,651,430 | <p>Example dataframe:</p>
<pre><code>class fred bill
0 a 23 35
1 b 123 45
2 c 34 45
3 d 4 45
</code></pre>
<p>(pandas adds the index (0->3) which isn't needed)</p>
<p>What i want is to say something like:</p>
<pre><code>fred_b_class = df.at['fred','b']
>>> 123
</code></pre>
<p>I ... | 2 | 2016-06-06T07:08:45Z | 37,651,459 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> from column <code>class</code> and then swap arguments in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.at.html" rel="nofollow">... | 2 | 2016-06-06T07:10:37Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
How to get the cell at a location in pandas dataframe using a column as the index | 37,651,430 | <p>Example dataframe:</p>
<pre><code>class fred bill
0 a 23 35
1 b 123 45
2 c 34 45
3 d 4 45
</code></pre>
<p>(pandas adds the index (0->3) which isn't needed)</p>
<p>What i want is to say something like:</p>
<pre><code>fred_b_class = df.at['fred','b']
>>> 123
</code></pre>
<p>I ... | 2 | 2016-06-06T07:08:45Z | 37,669,718 | <p>how about this solution, in case for some reason you do not intend to replace your existing index with dataframe column</p>
<pre><code>df['fred'][df.class=='b']
</code></pre>
| 0 | 2016-06-07T02:49:06Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
summing numerical output from input of word in python / jython | 37,651,444 | <p>very new to programming in general, so forgive me for my ignorance. I am trying to write a function in jython that takes an input (name), assigns each letter a value (1-26), then sums them, and prints the value.
So far, I have:</p>
<pre><code>def enterName():
input = raw_input('Enter your name: ')
input = i... | 0 | 2016-06-06T07:09:24Z | 37,651,508 | <p>For your code change <code>print output</code> to <code>print sum(output)</code>. You are printing a list only. List provides an in build option for finding sum. </p>
<p>Here is an alternative solution in pythonic way.</p>
<pre><code>In [1]: sum([ord(i.lower()) - 96 for i in raw_input('Enter your name: ')])
Enter ... | 0 | 2016-06-06T07:13:17Z | [
"python",
"sum",
"jython",
"raw-input"
] |
summing numerical output from input of word in python / jython | 37,651,444 | <p>very new to programming in general, so forgive me for my ignorance. I am trying to write a function in jython that takes an input (name), assigns each letter a value (1-26), then sums them, and prints the value.
So far, I have:</p>
<pre><code>def enterName():
input = raw_input('Enter your name: ')
input = i... | 0 | 2016-06-06T07:09:24Z | 37,653,364 | <p>You can use simple integer variable and increase it:</p>
<pre><code>output = 0
for character in name:
number = ord(character) - 96
output += number
print output
</code></pre>
| 0 | 2016-06-06T09:01:52Z | [
"python",
"sum",
"jython",
"raw-input"
] |
Pythonic way to get the union of dictionaries | 37,651,455 | <p>Is there a better/pythonic way to do the following:</p>
<p>I have a function that merges dictionaries:</p>
<pre><code>def merge_dicts(a, *dict_args):
for dictionary in dict_args:
for k, v in dictionary.items():
if k not in a:
a[k] = v
return a
</code></pre>
<p>Here is ... | 1 | 2016-06-06T07:10:28Z | 37,651,533 | <p>You can use <code>update</code>. Since the earlier dicts have priority you have to update in reverse order, and update with <code>a</code> last:</p>
<pre><code>def merge_dicts(a, *dict_args):
d = {}
for dictionary in reversed(dict_args):
d.update(dictionary)
d.update(a)
return d
</code></pre... | 2 | 2016-06-06T07:14:25Z | [
"python",
"dictionary"
] |
Pythonic way to get the union of dictionaries | 37,651,455 | <p>Is there a better/pythonic way to do the following:</p>
<p>I have a function that merges dictionaries:</p>
<pre><code>def merge_dicts(a, *dict_args):
for dictionary in dict_args:
for k, v in dictionary.items():
if k not in a:
a[k] = v
return a
</code></pre>
<p>Here is ... | 1 | 2016-06-06T07:10:28Z | 37,651,558 | <p>You don't need to check the existence of keys in dictionaries, since you want to preserve the first key you can use a dict comprehension by looping through the list of dictionaries backward:</p>
<pre><code>{k: v for d in list_of_dict[::-1] for k, v in d.items()}
</code></pre>
<p>Python will replace the existence k... | 1 | 2016-06-06T07:15:57Z | [
"python",
"dictionary"
] |
Formating numpy float values | 37,651,501 | <p>what is the easiest way to format a numpy float64 value like this:</p>
<pre><code>8.928571429999999509e+02
</code></pre>
<p>to:</p>
<pre><code>892.857
</code></pre>
<p>Thank you in advance.</p>
| 2 | 2016-06-06T07:13:06Z | 37,651,579 | <p>You can define a custom function:</p>
<pre><code>>>> myformat = lambda x: "%.3f" % x
>>> myformat(8.928571429999999509e+02)
'892.857'
</code></pre>
| 1 | 2016-06-06T07:17:27Z | [
"python",
"numpy"
] |
Formating numpy float values | 37,651,501 | <p>what is the easiest way to format a numpy float64 value like this:</p>
<pre><code>8.928571429999999509e+02
</code></pre>
<p>to:</p>
<pre><code>892.857
</code></pre>
<p>Thank you in advance.</p>
| 2 | 2016-06-06T07:13:06Z | 37,651,653 | <p>The <em>natural</em> way should be <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.set_printoptions.html" rel="nofollow"><code>numpy.set_printoptions</code></a>.</p>
<p><strong>Example</strong></p>
<pre><code>>>> np.set_printoptions(precision=3)
>>> print np.array([8.928... | 3 | 2016-06-06T07:22:15Z | [
"python",
"numpy"
] |
Formating numpy float values | 37,651,501 | <p>what is the easiest way to format a numpy float64 value like this:</p>
<pre><code>8.928571429999999509e+02
</code></pre>
<p>to:</p>
<pre><code>892.857
</code></pre>
<p>Thank you in advance.</p>
| 2 | 2016-06-06T07:13:06Z | 37,651,765 | <p>You can use string formatters
"%.3f" % 8.928571429999999509e+02</p>
| 2 | 2016-06-06T07:28:11Z | [
"python",
"numpy"
] |
Python Multiplication Table | 37,651,510 | <p>I am having trouble getting my multiplication table to look the way I was instructed to make it look.</p>
<blockquote>
<p>0x0=0 1x0=0.....................................................9x0=0</p>
<p>1x1=1 2x1=1............................................9x1=9</p>
<p>2x2=4 3x2=6............................. | 0 | 2016-06-06T07:13:18Z | 37,651,732 | <p>Here is my solution. I used <code>string.format()</code> to format the string like that <code>0x0=0</code>. The parameter <code>end= " "</code> will add a space <code></code> at the end of the string. </p>
<pre><code>for i in range(10):
for j in range(i, 10):
print("{}x{}={}".format(j, i, i*j), end=" ")... | 2 | 2016-06-06T07:26:44Z | [
"python",
"table"
] |
How to access "locked" files for backup program | 37,651,554 | <p>I am trying to create a google drive like backup program using python that backs up to a Linux box that will further backup to an off site place tbd. I have ran into a few interesting coding and computer challenges in doing this. </p>
<p>The one I am working on right now has to do with "locked" files. So what do I ... | 1 | 2016-06-06T07:15:49Z | 37,652,736 | <p>Many backup tools use snapshots. Then, they'll copy the locked file directly from the snapshot rather than coping it directly from the filesystem. If you're on Windows you should check <a href="https://en.wikipedia.org/wiki/Shadow_Copy" rel="nofollow">Windows VSS</a>, see the <a href="https://msdn.microsoft.com/en-u... | 0 | 2016-06-06T08:26:33Z | [
"python",
"windows",
"locking",
"backup"
] |
Applying same calcuation to each element of dataframe in python | 37,651,648 | <p>I have a dataframe like this.</p>
<pre><code> user tag1 tag2 tag3
0 Roshan ghai 0.0 1.0 1.0
1 mank nion 1.0 1.0 2.0
2 pop rajuel 2.0 0.0 1.0
3 random guy 2.0 1.0 1.0
</code></pre>
<p>I have to apply a calculation to each row. which is for each element x </p>
<pre><code>... | 3 | 2016-06-06T07:21:57Z | 37,654,665 | <p>You can try this:</p>
<pre><code>import io
temp = u""" user tag1 tag2 tag3
0 Roshan-ghai 0.0 1.0 1.0
1 mank-nion 1.0 1.0 2.0
2 pop-rajuel 2.0 0.0 1.0
3 random-guy 2.0 1.0 1.0"""
df = pd.read_csv(io.StringIO(temp), delim_whitespace=True)
maxtag1 = df.tag1.max()
maxtag2 = ... | 1 | 2016-06-06T10:06:04Z | [
"python",
"pandas",
"dataframe",
"large-data",
"data-analysis"
] |
Applying same calcuation to each element of dataframe in python | 37,651,648 | <p>I have a dataframe like this.</p>
<pre><code> user tag1 tag2 tag3
0 Roshan ghai 0.0 1.0 1.0
1 mank nion 1.0 1.0 2.0
2 pop rajuel 2.0 0.0 1.0
3 random guy 2.0 1.0 1.0
</code></pre>
<p>I have to apply a calculation to each row. which is for each element x </p>
<pre><code>... | 3 | 2016-06-06T07:21:57Z | 37,655,328 | <p>You can first select all values without first column by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>. Then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow"><code>max</code></a>, ... | 2 | 2016-06-06T10:41:22Z | [
"python",
"pandas",
"dataframe",
"large-data",
"data-analysis"
] |
Fail to concatenate two numpy array | 37,651,680 | <p>Given two numpy array <code>a1</code> and <code>a2</code>:</p>
<pre><code>>>>np.shape(a1)
(4465, 5000)
>>>np.shape(a2)
(4465, )
</code></pre>
<p>However,</p>
<pre><code>>>>np.concatenate((a1, a2), axis=1)
ValueError: all the input arrays must have the same number of dimensions
</code></... | 1 | 2016-06-06T07:23:57Z | 37,651,812 | <p>As the error message states, <code>a1</code> and <code>a2</code> do not have the same number of dimensions (accessible via attribute <code>ndims</code>). Make <code>a2</code> 2-dimensional with <code>a2 = a2[:, None]</code>. You can also use the more explicit syntax <code>a2 = a2[:, np.newaxis]</code>, but it is str... | 2 | 2016-06-06T07:30:40Z | [
"python",
"numpy"
] |
RuntimeWarning: invalid value encountered in greater | 37,651,803 | <p>I tried to implement <a href="https://en.wikipedia.org/wiki/Softmax_function" rel="nofollow">soft-max</a> with the following code (<code>out_vec</code> is a <code>numpy</code> vector of floats):</p>
<pre><code>numerator = np.exp(out_vec)
denominator = np.sum(np.exp(out_vec))
out_vec = numerator/denominator
</code><... | 1 | 2016-06-06T07:30:16Z | 37,652,508 | <p>Your problem caused by <code>NaN</code> or <code>Inf</code> elements of <code>out_vec</code> array. You could use following code to avoide this problem</p>
<pre><code>if np.isnan(np.sum(out_vec)):
out_vec = out_vec[~numpy.isnan(out_vec)] # just remove nan elements from vector
out_vec[out_vec > 709] = 709
...... | 1 | 2016-06-06T08:13:17Z | [
"python",
"numpy",
"softmax"
] |
Passing numpy arrays from python to javascript | 37,651,859 | <p>I have a written a source program in python that calculates and returns a numpy array of 3 numbers. Now ,i am trying to pass this array to a javascript front end program to display.
So far , i have tried using a child process in js invoking the python program, but i am stuck in the array transfer part.
I have also ... | -1 | 2016-06-06T07:33:08Z | 37,661,682 | <p>Python has a module to encode objects as JSON strings:</p>
<pre><code>import json
In [54]: json.dumps(np.arange(10).tolist())
Out[54]: '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
</code></pre>
<p>Arrays in Javascript are similar to Python lists. <code>numpy</code> arrays add level of complexity that you don't need, especia... | 1 | 2016-06-06T15:48:25Z | [
"python",
"node.js",
"numpy"
] |
Convergence of LSTM network using Tensorflow | 37,652,003 | <p>I am trying to detect micro-events in a long time series. For this purpose, I will train a LSTM network. </p>
<p><strong>Data.</strong> Input for each time sample is 11 different features somewhat normalized to fit 0-1. Output will be either one of two classes.</p>
<p><strong>Batching.</strong> Due to <em>huge</em... | 0 | 2016-06-06T07:41:13Z | 37,665,328 | <h1>Odd elements</h1>
<h2>Weighted loss</h2>
<p>I am not sure your "weighted loss" does what you want it to do:</p>
<pre><code> ratio = (60.00 / 5.00)
class_weights = tf.constant([ratio, 1 - ratio])
weighted_logits = tf.mul(logits, class_weights)
</code></pre>
<p>this is applied before calculating the lo... | 3 | 2016-06-06T19:23:38Z | [
"python",
"machine-learning",
"artificial-intelligence",
"tensorflow",
"lstm"
] |
Convergence of LSTM network using Tensorflow | 37,652,003 | <p>I am trying to detect micro-events in a long time series. For this purpose, I will train a LSTM network. </p>
<p><strong>Data.</strong> Input for each time sample is 11 different features somewhat normalized to fit 0-1. Output will be either one of two classes.</p>
<p><strong>Batching.</strong> Due to <em>huge</em... | 0 | 2016-06-06T07:41:13Z | 37,678,384 | <p>Gunnar has already made lots of good suggestions. A few more small things worth paying attention to in general for this sort of architecture:</p>
<ul>
<li>Try tweaking the Adam learning rate. You should determine the proper learning rate by cross-validation; as a rough start, you could just check whether a smaller ... | 0 | 2016-06-07T11:40:29Z | [
"python",
"machine-learning",
"artificial-intelligence",
"tensorflow",
"lstm"
] |
How to add parameters into the POST | 37,652,172 | <p>I'm trying to create a confirmation page in <code>Django</code>. I have one <code>view</code> which renders a <code>form</code>, then <code>user</code> clicks on <code>Submit</code> and the objects are saved into the database. </p>
<p>What I want to do is not to save objects into the database when user clicks on su... | 1 | 2016-06-06T07:52:30Z | 37,671,204 | <p>There are two ways to do this:</p>
<p>(1) Use a "staging" table / model to store the pending-job-order state without taking any real actions to action the order. This gives the user ability to come back to their session or for you to send reminder to the user later about a job-order in progress, etc. If you choose... | 0 | 2016-06-07T05:30:54Z | [
"python",
"django",
"django-forms",
"django-views"
] |
How to add parameters into the POST | 37,652,172 | <p>I'm trying to create a confirmation page in <code>Django</code>. I have one <code>view</code> which renders a <code>form</code>, then <code>user</code> clicks on <code>Submit</code> and the objects are saved into the database. </p>
<p>What I want to do is not to save objects into the database when user clicks on su... | 1 | 2016-06-06T07:52:30Z | 37,671,521 | <p>Two possible options I would suggest would be</p>
<ul>
<li>You can save an object in your session access later using request.session (See <a href="https://docs.djangoproject.com/en/1.9/topics/http/sessions/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/http/sessions/</a>)</li>
<li>In case you want yo... | 0 | 2016-06-07T05:55:04Z | [
"python",
"django",
"django-forms",
"django-views"
] |
How to create if statements using strings in python 3.x | 37,652,205 | <p>So I decided to make some silly simple code to practice on my own, and I have trouble finding what it is im doing wrong. Python displays 'syntax error' but im not sure what im doing wrong.</p>
<pre><code>>>> x= str(input("Select a colour: Red, Blue or Green"))
Select a colour: Red, Blue or Green:
>>&... | 1 | 2016-06-06T07:55:18Z | 37,652,320 | <p>Couple things here..</p>
<ol>
<li>This isn't necessarily <em>wrong</em> (the code will still work) but there's no reason to convert <code>input</code> to a <code>str</code>, it already is a string</li>
<li>Strings need to be in quotes, not inside <code>str()</code>. Use <code>"Red"</code> instead</li>
<li>Maybe use... | 5 | 2016-06-06T08:01:31Z | [
"python",
"python-3.x"
] |
How do i swap between tabs? | 37,652,484 | <p>I'm using Selenium (with Firefox) to test a web service and i need to be able to swap between multiple tabs but i don't know how to do that. I tried the following but it doesn't work. What am i doing wrong?</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
# OPEN UP THE MULTIPLE TABS
for... | 1 | 2016-06-06T08:11:48Z | 37,652,574 | <p>Here, I give code which open new Tab and Close it.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Firefox()#Chrome("chromedriver.exe")
try:
driver.get("http://www.google.co.in")
driver.find_element_by_tag_name('body').send_keys(... | 2 | 2016-06-06T08:17:33Z | [
"python",
"selenium",
"selenium-webdriver"
] |
How do i swap between tabs? | 37,652,484 | <p>I'm using Selenium (with Firefox) to test a web service and i need to be able to swap between multiple tabs but i don't know how to do that. I tried the following but it doesn't work. What am i doing wrong?</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
# OPEN UP THE MULTIPLE TABS
for... | 1 | 2016-06-06T08:11:48Z | 37,653,616 | <p>To open multiple windows, you could execute <code>window.open</code> with <code>execute_script</code> :</p>
<pre><code>driver = webdriver.Chrome()
driver.get("https://www.google.co.in/search?q=search1")
driver.execute_script("window.open(arguments[0], 'win2')", \
"https://www.google.co.in/search?q=search2")
... | 1 | 2016-06-06T09:15:33Z | [
"python",
"selenium",
"selenium-webdriver"
] |
How do i swap between tabs? | 37,652,484 | <p>I'm using Selenium (with Firefox) to test a web service and i need to be able to swap between multiple tabs but i don't know how to do that. I tried the following but it doesn't work. What am i doing wrong?</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
# OPEN UP THE MULTIPLE TABS
for... | 1 | 2016-06-06T08:11:48Z | 37,654,083 | <p>Following code would take you through all the tabs you have opened. You can index it accordingly modifying the <code>handle</code> parameter to swap between specific indexed tabs :</p>
<pre><code>for handle in browser.window_handles:
print "Handle = ",handle
browser.switch_to_window(handle);
print "I wa... | -1 | 2016-06-06T09:37:41Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Django select_related in reverse | 37,652,520 | <p>I have the following model:</p>
<pre><code>class Campaign(models.Model):
some_campaign_field = models.CharField()
class Position(models.Model):
campaign = models.ForeignKey(Campaign)
some_position_field = models.CharField()
class Trade(models.Model):
position = models.ForeignKey(Position)
some... | 0 | 2016-06-06T08:13:47Z | 37,792,783 | <p>Thanks to the suggestions in the comments, I ended up with the following working solution:</p>
<pre><code>open_campaigns = list(Campaign.objects.prefetch_related(
Prefetch('position_set',
queryset=Position.objects.all(),
... | 0 | 2016-06-13T14:46:59Z | [
"python",
"django"
] |
Need help creating a model in a view | 37,652,556 | <p>models.py</p>
<pre><code>class Match(models.Model):
match_name = models.CharField(max_length=100)
player = models.CharField(max_length=100, choices=match_game, default=2)
time_start = models.DateTimeField(blank=True, default=None, null=True)
match_finished = models.BooleanField(default=False)
... | 0 | 2016-06-06T08:16:24Z | 37,652,891 | <p>First, try to edit this statement</p>
<pre><code>def PlayerSign(request):
...
match = Match.objects.get(pk=Match.pk)
</code></pre>
<p>to</p>
<pre><code>def PlayerSign(request, pk):
...
match = Match.objects.get(pk=pk)
</code></pre>
<p>Because there is an request parameter in URL named pk, you sho... | 2 | 2016-06-06T08:35:24Z | [
"python",
"django"
] |
Scrapy terminated unexpected | 37,652,706 | <p>I follow book published by o'Reilly to create a spider as below:
articleSpider.py</p>
<pre><code>from scrapy.spiders import CrawlSpider, Rule
from TestScrapy.items import Article
from scrapy.linkextractors import LinkExtractor
class ArticleSpider(CrawlSpider):
name = "article"
allowed_domains = ["en.wikip... | 0 | 2016-06-06T08:24:54Z | 37,653,447 | <p>Change the method name from <code>parse</code> to <code>parse_item</code>.</p>
<p>Now you're just crawling the start url but when filtering the rules there is no method to callback, thus the spider ends the execution.</p>
<p>Check this example of CrawlSpider:
<a href="http://doc.scrapy.org/en/latest/topics/spiders... | 1 | 2016-06-06T09:06:31Z | [
"python",
"scrapy",
"web-crawler",
"google-crawlers"
] |
Scrapy terminated unexpected | 37,652,706 | <p>I follow book published by o'Reilly to create a spider as below:
articleSpider.py</p>
<pre><code>from scrapy.spiders import CrawlSpider, Rule
from TestScrapy.items import Article
from scrapy.linkextractors import LinkExtractor
class ArticleSpider(CrawlSpider):
name = "article"
allowed_domains = ["en.wikip... | 0 | 2016-06-06T08:24:54Z | 37,725,711 | <p>You can also use <code>start_product_requests</code> instead of <code>parse</code> here.</p>
| 0 | 2016-06-09T12:13:31Z | [
"python",
"scrapy",
"web-crawler",
"google-crawlers"
] |
How to inherit a python generator and overwrite __iter__ | 37,652,720 | <p>I want to call the mother class but I get this message :</p>
<pre><code>Traceback (most recent call last):
File "***test.py", line 23, in <module>
for i in daughter:
File "***test.py", line 18, in __iter__
for i in super(Mother, self):
TypeError: 'super' object is not iterable
</code></pre>
<p>I ... | 1 | 2016-06-06T08:25:27Z | 37,652,779 | <p>The proxy object returned by <code>super()</code> is not iterable just because there is an <code>__iter__</code> method in the MRO. You need to look up such methods <em>explicitly</em>, as only that'll kick of a search:</p>
<pre><code>for i in super(Daughter, self).__iter__():
yield i * self.multiplier
</code><... | 2 | 2016-06-06T08:29:00Z | [
"python",
"inheritance",
"generator"
] |
Django check if variable contains datetime and format | 37,652,808 | <p>How do I check if a variable contains a datetime and the format it to just include the date, hour, minutes and seconds. Not milliseconds.</p>
<p>The issue I'm having is that the variable isn't in datetime format as it can either contain text or a date time. </p>
<pre><code>return isinstance(new_value, datetime.da... | 0 | 2016-06-06T08:30:27Z | 37,654,126 | <p>At first you need to convert date string to the datetime object, in this way you can check it with 'isinstance()', but I want to suggest better solution, as I think :), because at the Python 2.7, so still popular, we have issue with timezone offset ( %z ) when convert date string to datetime object, so here is my so... | 0 | 2016-06-06T09:40:09Z | [
"python",
"django",
"reversion"
] |
Sublime Text 3 - Hover/click events in gutter? | 37,652,821 | <p>I've currently been working on a plugin that places a random coloured image on each line, based on the SVN commit number. (<a href="http://i.imgur.com/kKYzt4l.png" rel="nofollow">Example here</a>)</p>
<p>Now I'd like to move forward by creating a click (or hover) event from the icon in the gutter that will <a href=... | 1 | 2016-06-06T08:30:59Z | 39,676,781 | <p>This may be possible since Build 3124 of Sublime Text 3. Check the release notes and Sublime's Blog.</p>
| 0 | 2016-09-24T13:20:20Z | [
"python",
"sublimetext3",
"sublimetext",
"sublime-text-plugin"
] |
requests: cannot download zip file properly with verify is False | 37,652,964 | <p>I am using Python 2.7.3 and requests(requests==2.10.0). I am trying to get some zipfile from some link. The website's certificate is not verified but I just want to download that zip so I used <code>verfiy=False</code>.</p>
<pre><code>link = 'https://webapi.yanoshin.jp/rde.php?https%3A%2F%2Fdisclosure.edinet-fsa.go... | 0 | 2016-06-06T08:39:06Z | 37,653,293 | <p>The server is trying to block scripts from downloading ZIP files; you'll see the same issue when using <code>curl</code>:</p>
<pre><code>$ curl -sD - -o /dev/null "https://webapi.yanoshin.jp/rde.php?https%3A%2F%2Fdisclosure.edinet-fsa.go.jp%2FE01EW%2Fdownload%3Fuji.verb%3DW0EZA104CXP001006BLogic%26uji.bean%3Dee.bea... | 0 | 2016-06-06T08:58:33Z | [
"python",
"ssl",
"download",
"python-requests"
] |
Capture RTSP in command line | 37,652,976 | <p>I want to continously <strong>capture the rtsp</strong> video(CCTV) in ubuntu. (in Putty)</p>
<p>I have tried to use <strong>OpenCV</strong> in <strong>Python</strong> to open rtsp, however, the program will terminate suddenly.</p>
<pre><code>video_capture = cv2.VideoCapture("rtsp://stream_link/")
while True:
... | 1 | 2016-06-06T08:39:41Z | 37,661,395 | <p>Using <code>ffmpeg</code> is almost always the best idea:</p>
<pre><code>ffmpeg -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov test.mp4
</code></pre>
<p>To capture only the first 5 seconds you can use <code>-t 00:00:05</code> like this:</p>
<pre><code>ffmpeg -i rtsp://wowzaec2demo.streamlock.... | -1 | 2016-06-06T15:35:08Z | [
"python",
"opencv",
"ubuntu",
"video",
"rtsp"
] |
How I can access the fields without translation through an instance of TranslatableModel? | 37,653,068 | <p>I need the name of the project (field project, no translation) for build the path of upload_to directory in ImageField. But i get this error:</p>
<p>AttributeError at /admin/api/stage/add/
'StageTranslation' object has no attribute 'project' </p>
<pre><code>def stage_name_path(instance, filename):
# get err... | 0 | 2016-06-06T08:45:04Z | 37,653,910 | <p>Try:<code>instance.master.project</code>. The <code>StageTranslation</code> has a <code>ForeignKey</code> field <code>master</code> is a reference to <code>Sage</code>.</p>
| 0 | 2016-06-06T09:29:24Z | [
"python",
"django",
"imagefield",
"django-hvad"
] |
Trying to read the first line of CSV file returns ['/'] | 37,653,172 | <p>I have uploaded a CSV file through Django and I trying to read the first line of it. The file is stored on the server in </p>
<pre><code>/tmp/csv_file/test.csv
</code></pre>
<p>The file looks like this:</p>
<pre><code>column_1,column_2,column_3
2175,294,Nuristan
2179,299,Sar-e-Pul
</code></pre>
<p>I am trying to... | 1 | 2016-06-06T08:51:11Z | 37,653,203 | <p>You passed a string instead of a file object which is why you get the slash, change to this:</p>
<pre><code>with open (absolute_base_file) as csvfile:
csv_reader = csv.reader(csvfile)
</code></pre>
<p>check the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">docs</a></p>
<p>See this workin... | 2 | 2016-06-06T08:53:19Z | [
"python",
"csv"
] |
Trying to read the first line of CSV file returns ['/'] | 37,653,172 | <p>I have uploaded a CSV file through Django and I trying to read the first line of it. The file is stored on the server in </p>
<pre><code>/tmp/csv_file/test.csv
</code></pre>
<p>The file looks like this:</p>
<pre><code>column_1,column_2,column_3
2175,294,Nuristan
2179,299,Sar-e-Pul
</code></pre>
<p>I am trying to... | 1 | 2016-06-06T08:51:11Z | 37,653,238 | <p>You should pass a file object to your <code>csv.reader</code> not a string literal.</p>
<pre><code>absolute_base_file = open(r'/tmp/csv_file/test.csv') # notice open
csv_reader = csv.reader(absolute_base_file)
csv_headings = next(csv_reader)
print csv_headings
</code></pre>
| 1 | 2016-06-06T08:55:24Z | [
"python",
"csv"
] |
GAE xmpp app shows invalid JID error | 37,653,184 | <p>Currently I'm testing <a href="https://github.com/googlearchive/appengine-crowdguru-python" rel="nofollow">appengine-crowdguru-python</a> this app by sending xmpp messages from <code>http://localhost:8000/xmpp</code> which has a form to post data .. I have filled from, to, chat (message) fields.</p>
<pre><code>From... | 2 | 2016-06-06T08:52:16Z | 37,743,438 | <p>A common behaviour of "get Jid" it's error if Resource (in login phase) it's not definied due to the Jid composition ( user @ server /resource). A "full jid" it's complete of Resource, so if it's null you can have a null pointer and so an error.</p>
<p>How to handle:
SOLUTION 1: retrive just "bare Jid"</p>
<p>SOLU... | 0 | 2016-06-10T08:26:34Z | [
"python",
"google-app-engine",
"xmpp"
] |
regex for certain html links | 37,653,257 | <p>EDOT: you guys are right, bs4 is much better and have started using it, its much more intuitive and actually finds links
although I'm still struggling at points haha
thank you all very much</p>
<p>had a look and this doesnt seem to be in the other posts </p>
<p>so i am pretty sure I can use regex for this as the... | 1 | 2016-06-06T08:56:36Z | 37,653,480 | <p>Use regexp below:</p>
<pre><code>s = """<a href="\n\n\n\n\n\n https://www.amazon.co.uk/Nikon-Coolpix-L340-Bridge-Camera/dp/B00THKEKEQ/ref=zg_bs_560836_2&#10;">Nikon Coolpix L340 Bridge Camera - Bl...</a>"""
re.findall('(?<=\n\n\n\n\n\n)(.*?)"', s)
</code></pre>
<p>Previous regexp was looking fo... | 0 | 2016-06-06T09:07:54Z | [
"python",
"regex"
] |
regex for certain html links | 37,653,257 | <p>EDOT: you guys are right, bs4 is much better and have started using it, its much more intuitive and actually finds links
although I'm still struggling at points haha
thank you all very much</p>
<p>had a look and this doesnt seem to be in the other posts </p>
<p>so i am pretty sure I can use regex for this as the... | 1 | 2016-06-06T08:56:36Z | 37,653,830 | <p>This might also work.
The regex doesn't care about the \n, just assumes a link starts with http</p>
<pre class="lang-python prettyprint-override"><code>links = re.findall('http.*(?=">)', page)
</code></pre>
<p>Or perhaps grab the whole <code><a></code> tag and get the url from the capture group?</p>
<pr... | 0 | 2016-06-06T09:25:34Z | [
"python",
"regex"
] |
Exact Online API: deleting and updating items like BankEntryLines | 37,653,276 | <p>We are building an exensive api-link with the Exact online odata API. Problem we are having is that many objects cant be updated or deleted. For instance BankEntryLines, GeneralJournalEntryLines.
We have now worked around this by creating new EntryLines upon each update or delete, but this creates much unclarity in ... | 2 | 2016-06-06T08:57:30Z | 37,654,113 | <p>As the Exact Online REST API doesn't support modifying on quite some objects, there is no way to achieve what you want using the REST API. If the Exact Online XML API doesn't support updating either, there is only one solution left.</p>
<p>That solution is forbidden by Exact, and it could risk you lose you applicat... | 1 | 2016-06-06T09:39:22Z | [
"python",
"api",
"rest",
"odata",
"exact-online"
] |
Python TCP socket to send AES encrypted dictionary | 37,653,423 | <p>I'm currently drafting an upcoming Python project, where I'm required to securely send a Python dictionary form a client to a server over the internet.</p>
<p>As of now, I'm considering a simple <a href="https://wiki.python.org/moin/TcpCommunication" rel="nofollow">TCP communication</a> and use <a href="https://pyp... | -1 | 2016-06-06T09:05:01Z | 37,653,916 | <p>There are some libraries that support the encryption of arbitrary objects, because they internally have a serializer/unserializer, but PyCrypto is not such a library. You will need to provide a binary string in Python 2 or a <code>bytes</code> object in Python 3.</p>
<p>In order to get those, you need to serialize ... | 1 | 2016-06-06T09:29:47Z | [
"python",
"sockets",
"dictionary",
"encryption",
"tcp"
] |
Python Loop with same key | 37,653,474 | <p>I have this :</p>
<pre><code>aa = [
{'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.018406, 'date': u'2015-12-03', 'calc': -0.018406},
{'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.043895, 'date': u'2015-12-04', 'calc': -0.043895},
{'id_o': 14285, 'id': 253004, 'value1': '0', ... | -2 | 2016-06-06T09:07:41Z | 37,653,623 | <p>Use <code>itertools.groupby</code> for an easy transformation to a dict: <code>{id: [dict]}</code>:</p>
<pre><code>from itertools import groupby
# from operator import itemgetter
key = lambda d: d['id']
# key = itemgetter('id')
# mostly a matter of taste, but itemgetter is more performant in some contexts
id_di... | 2 | 2016-06-06T09:15:47Z | [
"python",
"dictionary"
] |
update records in file2 with data found in file1 | 37,653,486 | <p>There is a large file with fixed format,file1. Another CSV file, file2 has id's and values, using which, specific portions of a record with same id in file1 need to be updated. Here is my attempt. I really appreciate any help you can offer to make this work. </p>
<p>file2 comma separated</p>
<pre><code>clr,code,ty... | 0 | 2016-06-06T09:08:07Z | 37,657,002 | <p>If I get you right, you need something like this:</p>
<pre><code># declare file names and necessary lists
file1 = "file1.txt"
file2 = "file2.txt"
file1_new = "file1.txt.EDIT"
clrs = {}
# read clrs to update
with open(file1, "r") as f:
# skip header line
f.next()
for line in f:
clrs[line[:3]] = ... | 1 | 2016-06-06T12:06:24Z | [
"python",
"algorithm",
"file-io"
] |
PyOpenSSL - where are all the encryption functions? | 37,653,670 | <p>In answering <a href="http://security.stackexchange.com/q/126151/61443">this question</a>, I'm looking at <a href="http://www.pyopenssl.org/en/stable/api/crypto.html" rel="nofollow">the docs for PyOpenSSL</a> - a python wrapper for OpenSSL.</p>
<p>It's got signatures and certificate stuff, but where's all the encry... | 1 | 2016-06-05T17:44:42Z | 37,659,246 | <p>Self-answer:</p>
<p>It seems that Python's <a href="https://cryptography.io/en/latest/" rel="nofollow">Cryptography package</a> is what I was looking for; it provides all the cryptographic primitives that I would have expected to find in OpenSSL.</p>
| 1 | 2016-06-06T13:50:43Z | [
"openssl",
"python"
] |
Python pandas pivot from long to wide | 37,653,779 | <p>My data is currently in a long format. Below is a sample:</p>
<pre><code> Stock Date Time Price Year
AAA 2001-01-05 15:20:09 2.380 2001
AAA 2002-02-23 10:13:24 2.440 2002
AAA 2002-02-27 17:17:55 2.460 2002
BBB 2006-05-13 16:03:... | 2 | 2016-06-06T09:23:15Z | 37,654,051 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>, but need some <code>aggfunc</code>. I choose <code>first</code>, because there is problem use default <code>np.mean</code> with <code>datetime</code>.</p>
<p>Bette... | 1 | 2016-06-06T09:36:10Z | [
"python",
"pandas",
"dataframe",
"pivot-table",
"reshape"
] |
How do I use cache_clear() on python @functools.lru_cache | 37,653,784 | <p><a href="https://docs.python.org/3/library/functools.html" rel="nofollow">The documentation</a> states:</p>
<blockquote>
<p>The decorator also provides a <code>cache_clear()</code> function for clearing or
invalidating the cache.</p>
</blockquote>
<p>It doesn't provide any examples or guidance on how to use <c... | 4 | 2016-06-06T09:23:34Z | 37,654,201 | <p>Besides caching, <code>lru_cache</code> decorator also adds new functions, to the decorated function - <code>cache_info</code> and <code>cache_clear</code>. Below is a simple example that should explain how they work:</p>
<pre><code>>>> @lru_cache(5)
... def foo():
... print('Executing foo...')
...
&g... | 3 | 2016-06-06T09:44:17Z | [
"python",
"python-3.x"
] |
vectorized backtest creation of pandas DataFrame | 37,653,822 | <p>This is my final try after posting several questions that might have been badly addressed/described. I want to achive this DataFrame as result:</p>
<pre><code> Signal price buy_units sell_units cashflow balance
Index
0 0 40 0 0 0 100000
1 1 ... | 2 | 2016-06-06T09:25:22Z | 37,654,029 | <p>If <code>-1</code> and <code>+1</code> signals always alternate as in the example, then the balance in step <code>n+2</code> is equal to the balance in step <code>n</code> multiplied by the price return between <code>n+1</code> and <code>n+2</code>.</p>
<p>I use the cumulated product to translate this into vectoriz... | 0 | 2016-06-06T09:35:14Z | [
"python",
"pandas",
"vectorization"
] |
vectorized backtest creation of pandas DataFrame | 37,653,822 | <p>This is my final try after posting several questions that might have been badly addressed/described. I want to achive this DataFrame as result:</p>
<pre><code> Signal price buy_units sell_units cashflow balance
Index
0 0 40 0 0 0 100000
1 1 ... | 2 | 2016-06-06T09:25:22Z | 37,656,622 | <p>You can create a temporary dataframe in order to do your computation:</p>
<pre><code>temp = df[df.balance == 1]
</code></pre>
<p>Then perform computations on this dataframe:</p>
<pre><code>df.ix[df.balance == 1,'buy_units'] = temp.balance/temp.price
</code></pre>
<p>And delete the temporary dataframe:</p>
<pre>... | 0 | 2016-06-06T11:46:09Z | [
"python",
"pandas",
"vectorization"
] |
AttributeError: 'generator' object has no attribute 'set_configuration' | 37,653,827 | <p>I would want to collect DATA from a USB audio codec connected to a raspberry pi.
So first I'm trying a simple program to write some data</p>
<pre><code>import usb.core
import usb.util
# find our device
dev = usb.core.find(idVendor=0xfffe, idProduct=0x0001)
# was it found?
if dev is None:
raise ValueError('Device ... | 0 | 2016-06-06T09:25:26Z | 37,654,107 | <p>The error messages suggests that <code>usb.core.find</code> is a generator function. That is, it returns an iterable generator object, not a single device object, like you seem to expect. You need to iterate over the generator in some way (e.g. with a <code>for</code> loop, or by passing it to <code>list</code>) to ... | 0 | 2016-06-06T09:39:03Z | [
"python",
"raspberry-pi",
"codec"
] |
Python3.5 multiprocessing with pandas : Process never stop | 37,653,894 | <p>My problem is to execute something like :</p>
<pre><code>multicore_apply(serie, func)
</code></pre>
<p>to run</p>
<p>So I tried to create a function doing it :</p>
<h1>function used to run the apply method in a process :</h1>
<pre><code>def adaptator(func, queue) :
serie = queue.get().apply(func)
queue.... | 3 | 2016-06-06T09:27:54Z | 37,658,659 | <p>May be that will helps - you can use <code>multiprocessing</code> lib.
Your <code>multicore_apply(serie, func)</code> should look like:</p>
<pre><code>from multiprocessing import Pool
pool = Pool()
pool.map(func, series)
pool.terminate()
</code></pre>
<p>You can specify count of process to be created like this <co... | 0 | 2016-06-06T13:23:17Z | [
"python",
"pandas",
"multiprocessing"
] |
Python3.5 multiprocessing with pandas : Process never stop | 37,653,894 | <p>My problem is to execute something like :</p>
<pre><code>multicore_apply(serie, func)
</code></pre>
<p>to run</p>
<p>So I tried to create a function doing it :</p>
<h1>function used to run the apply method in a process :</h1>
<pre><code>def adaptator(func, queue) :
serie = queue.get().apply(func)
queue.... | 3 | 2016-06-06T09:27:54Z | 37,785,139 | <p>After many nights of intense search, I solved the problem with a post on the python development website about the max size of an object in a queue : the problem was here. I used another post on stackoverflow found <a href="http://stackoverflow.com/questions/22487296/multiprocessing-in-python-sharing-large-object-e-g... | 0 | 2016-06-13T08:36:28Z | [
"python",
"pandas",
"multiprocessing"
] |
Sorting row values and displaying the column order | 37,653,926 | <p>I am trying to a data frame which is something like this</p>
<pre><code>user_name tag1 tag2 tag3 tag4
user1 .65 .32 .91 0
user2 .34 .44 .21 .56
user3 .21 0 0 .19
</code></pre>
<p>I need to sort each row on the values of column and get the result columns... | 3 | 2016-06-06T09:30:24Z | 37,654,501 | <p>You can use <code>list.sort()</code> function. If you enter all the tags of an user in a list and then sort the list, you should find the desired result</p>
| -1 | 2016-06-06T09:58:38Z | [
"python",
"python-2.7",
"pandas",
"data-analysis"
] |
Sorting row values and displaying the column order | 37,653,926 | <p>I am trying to a data frame which is something like this</p>
<pre><code>user_name tag1 tag2 tag3 tag4
user1 .65 .32 .91 0
user2 .34 .44 .21 .56
user3 .21 0 0 .19
</code></pre>
<p>I need to sort each row on the values of column and get the result columns... | 3 | 2016-06-06T09:30:24Z | 37,654,967 | <p>If you replace the <code>0</code> values with <code>NaN</code> then you can <code>apply</code> a <code>lambda</code> to mask the index:</p>
<pre><code>In [28]:
df.replace(0,np.NaN, inplace=True)
def func(x):
val = x.sort_values(ascending=False).index.to_series()
mask = pd.isnull(x)
val[mask] = ''
re... | 2 | 2016-06-06T10:21:25Z | [
"python",
"python-2.7",
"pandas",
"data-analysis"
] |
Python - Django - cardav - How to implement a server | 37,653,929 | <p>I have a server application written with Django which has a contacts database.</p>
<p>I wish to add a cardav webservice in order to share my contacts on my phone. I have made many search but I am completely lost.</p>
<p>I found some server as Radical, some API which uses files ... but nothing help me.</p>
<p>I ne... | 0 | 2016-06-06T09:30:28Z | 37,660,800 | <p>Your question seems a bit generic nor do you list what resources you looked at and why you are lost.</p>
<p><a href="https://www.youtube.com/watch?v=LzgomnabxdM" rel="nofollow">This presentation</a> is a little old, but shows the fundamentals on how the *DAV protocols work. <a href="http://sabre.io/dav/building-a-c... | 2 | 2016-06-06T15:06:09Z | [
"python",
"django",
"python-2.7",
"caldav"
] |
Python - Django - cardav - How to implement a server | 37,653,929 | <p>I have a server application written with Django which has a contacts database.</p>
<p>I wish to add a cardav webservice in order to share my contacts on my phone. I have made many search but I am completely lost.</p>
<p>I found some server as Radical, some API which uses files ... but nothing help me.</p>
<p>I ne... | 0 | 2016-06-06T09:30:28Z | 37,671,223 | <p>Thank you for your responses.</p>
<p>I will look radical and the modular backend, If I can create a communication between radical and my databases it will be perfect.</p>
| 0 | 2016-06-07T05:32:19Z | [
"python",
"django",
"python-2.7",
"caldav"
] |
Matplotlib - place pie charts in a grid | 37,653,943 | <p>I am trying to organize pie charts in a grid, with another column on the left in which I write some relevant data on the pie charts of the specific row. Right now my code is:</p>
<pre><code>data = [[0.3,0.3,0.3,0.1],[0.2,0.2,0.2,0.4],[0.1,0.1,0.4,0.4]]
def main():
createPieCharts(data)
return 0
def crea... | 3 | 2016-06-06T09:31:32Z | 37,656,302 | <p>It is possible if you use special functions for an axis object <code>is_first_col</code> to label y axis and <code>is_last_row</code> for x axis:</p>
<pre><code>def createPieCharts(data,piecharts_fname="piecharts"):
""" """
import datetime
from matplotlib.backends.backend_pdf import PdfPages
import ... | 0 | 2016-06-06T11:30:51Z | [
"python",
"matplotlib",
"charts",
"pie-chart"
] |
Matplotlib - place pie charts in a grid | 37,653,943 | <p>I am trying to organize pie charts in a grid, with another column on the left in which I write some relevant data on the pie charts of the specific row. Right now my code is:</p>
<pre><code>data = [[0.3,0.3,0.3,0.1],[0.2,0.2,0.2,0.4],[0.1,0.1,0.4,0.4]]
def main():
createPieCharts(data)
return 0
def crea... | 3 | 2016-06-06T09:31:32Z | 37,656,998 | <p>Add an extra column, and put your text in there. </p>
<p>You then just need to turn off the axes lines and ticks from the axes in the left column (<a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_axis_off" rel="nofollow"><code>ax.set_axis_off()</code></a>), and the add your text labels usin... | 2 | 2016-06-06T12:06:14Z | [
"python",
"matplotlib",
"charts",
"pie-chart"
] |
python Traceback Keyerror using beautifulsoup | 37,654,024 | <p>I have an error in my python code:</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
import traceback
from time import localtime, strftime
def display(result):
print ('Weather in Suwon, Asia at ' + strftime('%H:%M', localtime()) + '\n')
print ('Condition: ' + result['cond... | 1 | 2016-06-06T09:35:04Z | 37,654,864 | <p>None of your conditions evaluate to True so you never create the cond key in your dict, you are also going the wrong way about parsing, use the classes to get the data you want:</p>
<pre><code>def display(result):
print('Weather in Suwon, Asia at ' + strftime('%H:%M', localtime()) + '\n')
print('Condition: ... | 0 | 2016-06-06T10:16:53Z | [
"python",
"python-2.7",
"python-3.x",
"python-import",
"python-3.5"
] |
Django: IntegrityError during Many To Many add() | 37,654,072 | <p>We run into a known issue in django:</p>
<p><a href="https://code.djangoproject.com/ticket/19544">IntegrityError during Many To Many add()
</a></p>
<p>There is a race condition if several processes/requests try to add the same row to a ManyToManyRelation.</p>
<p>How to work around this?</p>
<p>Envionment:</p>
<... | 10 | 2016-06-06T09:37:09Z | 37,944,497 | <p>From what I'm seeing in the code provided. I believe that you have a constraint for uniqueness in pairs (user_id, group_id) in groups. So that's why running 2 times the same query will fail as you are trying to add 2 rows with the same user_id and group_id, the first one to execute will pass, but the second will rai... | -1 | 2016-06-21T12:30:13Z | [
"python",
"django",
"postgresql",
"race-condition"
] |
Django: IntegrityError during Many To Many add() | 37,654,072 | <p>We run into a known issue in django:</p>
<p><a href="https://code.djangoproject.com/ticket/19544">IntegrityError during Many To Many add()
</a></p>
<p>There is a race condition if several processes/requests try to add the same row to a ManyToManyRelation.</p>
<p>How to work around this?</p>
<p>Envionment:</p>
<... | 10 | 2016-06-06T09:37:09Z | 37,946,933 | <p>If you are ready to solve it in PostgreSQL you may do the following in <code>psql</code>:</p>
<pre><code>-- Create a RULE and function to intercept all INSERT attempts to the table and perform a check whether row exists:
CREATE RULE auth_user_group_ins AS
ON INSERT TO auth_user_groups
WHERE (EXISTS (SELE... | 0 | 2016-06-21T14:16:55Z | [
"python",
"django",
"postgresql",
"race-condition"
] |
Django: IntegrityError during Many To Many add() | 37,654,072 | <p>We run into a known issue in django:</p>
<p><a href="https://code.djangoproject.com/ticket/19544">IntegrityError during Many To Many add()
</a></p>
<p>There is a race condition if several processes/requests try to add the same row to a ManyToManyRelation.</p>
<p>How to work around this?</p>
<p>Envionment:</p>
<... | 10 | 2016-06-06T09:37:09Z | 37,968,648 | <h2>Can the error be reproduced?</h2>
<p>Yes, let us use the famed <code>Publication</code> and <code>Article</code> models from <a href="https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/" rel="nofollow">Django docs</a>. Then, let's create a few threads.</p>
<pre><code>import threading
import ran... | 4 | 2016-06-22T12:53:23Z | [
"python",
"django",
"postgresql",
"race-condition"
] |
How to redirect to another form view in python code - Odoo 8 | 37,654,086 | <p>Through clicking a button the user should create a new order from given values and be <em>directly redirected to the form view</em> of the newly created order. Following method is called through the button:</p>
<pre><code>@api.one
def method_name(self):
[...]
vals = [...]
new_order = self.env['sa... | 2 | 2016-06-06T09:37:49Z | 37,655,498 | <p>To execute a method of your model from a button, you must define the button as a <code>object</code> type like this in your xml view:</p>
<pre><code><button name="method_name" string="My Button" type="object"/>
</code></pre>
<p>Then in your <code>model</code>, if you want to redirect to another view after do... | 3 | 2016-06-06T10:50:28Z | [
"python",
"openerp",
"odoo-8",
"odoo-view"
] |
File Field can't hold the file when another validation error occurred in wtforms | 37,654,215 | <p>I am trying to validate the email and phone number in my form. This is done but when this validation error occurred , the file field can't hold the uploaded file. My form is given below.</p>
<h1>forms.py</h1>
<pre><code>from wtforms import Form ,SelectField,StringField, validators , IntegerField , DateField , Sel... | 1 | 2016-06-06T09:45:20Z | 37,689,083 | <p>It's a feature of HTML, you can't easily work around it. If the server <em>could</em> send a html page to the client with a little extra information saying <em>"Hey, you tried to upload REALLY_SECRET_FILE, please automatically attach it again please"</em> you could easily picture it being used for bad purposes (esp... | 1 | 2016-06-07T20:49:12Z | [
"python",
"jinja2",
"wtforms",
"flask-wtforms"
] |
Unittest Flask flask.g | 37,654,390 | <p>When I unittest, I want to be able to set and access <code>flask.g</code>.</p>
<pre><code>flask.g['test'] = {'test': '123'}
test_dict = flask.g['test']
</code></pre>
<p>produces this error:</p>
<pre><code>Error
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", l... | 1 | 2016-06-06T09:53:44Z | 37,654,659 | <p>These two usages are now equivalent</p>
<pre><code>user = getattr(flask.g, 'user', None)
user = flask.g.get('user', None)
</code></pre>
<p>example of usage</p>
<pre><code>def get_user():
user = getattr(g, 'user', None)
if user is None:
user = fetch_current_user_from_database()
g.user = use... | 2 | 2016-06-06T10:05:47Z | [
"python",
"python-2.7",
"unit-testing",
"flask",
"python-unittest"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.