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
graphlab adding variable columns from existing sframe
39,189,416
<p>I have a SFrame e.g.</p> <pre><code>a | b ----- 2 | 31 4 5 0 | 1 9 1 | 2 84 </code></pre> <p>now i want to get following result</p> <pre><code>a | b | c | d | e ---------------------- 2 | 31 4 5 | 31|4 | 5 0 | 1 9 | 1 | 9 | 0 1 | 2 84 | 2 | 84 | 0 </code></pre> <p>any idea how to do it? or maybe i have to use some other tools? </p> <p>thanks</p>
0
2016-08-28T08:36:20Z
39,189,659
<p>Using pandas:</p> <pre><code>In [409]: sf Out[409]: Columns: a int b str Rows: 3 Data: +---+--------+ | a | b | +---+--------+ | 2 | 31 4 5 | | 0 | 1 9 | | 1 | 2 84 | +---+--------+ [3 rows x 2 columns] In [410]: df = sf.to_dataframe() In [411]: newdf = pd.DataFrame(df.b.str.split().tolist(), columns = ['c', 'd', 'e']).fillna('0') In [412]: df.join(newdf) Out[412]: a b c d e 0 2 31 4 5 31 4 5 1 0 1 9 1 9 0 2 1 2 84 2 84 0 </code></pre> <p>Converting back to SFrame:</p> <pre><code>In [498]: SFrame(df.join(newdf)) Out[498]: Columns: a int b str c str d str e str Rows: 3 Data: +---+--------+----+----+---+ | a | b | c | d | e | +---+--------+----+----+---+ | 2 | 31 4 5 | 31 | 4 | 5 | | 0 | 1 9 | 1 | 9 | 0 | | 1 | 2 84 | 2 | 84 | 0 | +---+--------+----+----+---+ [3 rows x 5 columns] </code></pre> <p>If you want integers/floats, you can also do:</p> <pre><code>In [506]: newdf = pd.DataFrame(map(lambda x: [int(y) for y in x], df.b.str.split().tolist()), columns = ['c', 'd', 'e']) In [507]: newdf Out[507]: c d e 0 31 4 5.0 1 1 9 NaN 2 2 84 NaN In [508]: SFrame(df.join(newdf)) Out[508]: Columns: a int b str c int d int e float Rows: 3 Data: +---+--------+----+----+-----+ | a | b | c | d | e | +---+--------+----+----+-----+ | 2 | 31 4 5 | 31 | 4 | 5.0 | | 0 | 1 9 | 1 | 9 | nan | | 1 | 2 84 | 2 | 84 | nan | +---+--------+----+----+-----+ [3 rows x 5 columns] </code></pre>
1
2016-08-28T09:10:58Z
[ "python", "pandas", "graphlab" ]
graphlab adding variable columns from existing sframe
39,189,416
<p>I have a SFrame e.g.</p> <pre><code>a | b ----- 2 | 31 4 5 0 | 1 9 1 | 2 84 </code></pre> <p>now i want to get following result</p> <pre><code>a | b | c | d | e ---------------------- 2 | 31 4 5 | 31|4 | 5 0 | 1 9 | 1 | 9 | 0 1 | 2 84 | 2 | 84 | 0 </code></pre> <p>any idea how to do it? or maybe i have to use some other tools? </p> <p>thanks</p>
0
2016-08-28T08:36:20Z
39,189,808
<pre><code>def customsplit(string,column): val = string.split(' ') diff = column - len(val) val += ['0']*diff return val a = sf['b'].apply(lambda x: customsplit(x,3)) sf['c'] = [i[0] for i in a] sf['d'] = [i[1] for i in a] sf['e'] = [i[2] for i in a] sf </code></pre> <p>Output:</p> <pre><code>a | b | c | d | e ---------------------- 2 | 31 4 5 | 31|4 | 5 0 | 1 9 | 1 | 9 | 0 1 | 2 84 | 2 | 84 | 0 </code></pre>
1
2016-08-28T09:26:40Z
[ "python", "pandas", "graphlab" ]
graphlab adding variable columns from existing sframe
39,189,416
<p>I have a SFrame e.g.</p> <pre><code>a | b ----- 2 | 31 4 5 0 | 1 9 1 | 2 84 </code></pre> <p>now i want to get following result</p> <pre><code>a | b | c | d | e ---------------------- 2 | 31 4 5 | 31|4 | 5 0 | 1 9 | 1 | 9 | 0 1 | 2 84 | 2 | 84 | 0 </code></pre> <p>any idea how to do it? or maybe i have to use some other tools? </p> <p>thanks</p>
0
2016-08-28T08:36:20Z
39,197,008
<p>This can be done by SFrame itself not using Pandas. Just utilize '<strong><a href="https://turi.com/products/create/docs/generated/graphlab.SFrame.unpack.html?highlight=unpack#graphlab.SFrame.unpack" rel="nofollow">unpack</a></strong>' function. </p> <p>Pandas provides a variety of functions to handle dataset, but it is inconvenient to convert SFrame to Pandas DataFrame and vice versa. </p> <p>If you handles over 10 Giga bytes data, Pandas can not properly handle the dataset. (But SFrame can) </p> <pre><code># your SFrame sf=sframe.SFrame({'a' : [2,0,1], 'b' : [[31,4,5],[1,9,],[2,84,]]}) # just use 'unpack()' function sf2= sf.unpack('b') # change the column names sf2.rename({'b.0':'c', 'b.1':'d', 'b.2':'e'}) # filling-up the missing values to zero sf2 = sf2['e'].fillna(0) # merge the original SFrame and new SFrame sf.join(sf2, 'a') </code></pre>
0
2016-08-29T00:21:56Z
[ "python", "pandas", "graphlab" ]
Number of rows in 40GB tar.gz file without uncompressing it?
39,189,464
<p>I have over 40 gb tar.gz file at <a href="https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz" rel="nofollow">https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz</a> How can I find the number of rows in the CSV file that is compressed inside this tar.gz file without uncompressing the entire file which might be in 100+ GBs? </p>
3
2016-08-28T08:43:35Z
39,189,614
<p>If there is only one csv file in that tar.gz, you could do this as a bash one-liner:</p> <p><code>tar -zxOf mysql-2016-06-16.tar.gz | wc -l</code></p> <p>It uses tar to extract all the files in the archive to standard output (-O, capital o, not zero), and wc to count the lines.</p> <p>If there is more files, and only want that one file, you can count the lines in that file like this:</p> <p><code>tar -zxOf mysql-2016-06-16.tar.gz mysql-2016-06-16/commit_comments.csv| wc -l</code></p> <p>Here's how to list all files in the archive:</p> <p><code>tar -zlf mysql-2016-06-16.tar.gz</code></p> <p>CSV files usually have a header, so remove one line per file and you have the number of rows.</p>
3
2016-08-28T09:05:18Z
[ "python", "csv", "gzip", "tar" ]
Number of rows in 40GB tar.gz file without uncompressing it?
39,189,464
<p>I have over 40 gb tar.gz file at <a href="https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz" rel="nofollow">https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz</a> How can I find the number of rows in the CSV file that is compressed inside this tar.gz file without uncompressing the entire file which might be in 100+ GBs? </p>
3
2016-08-28T08:43:35Z
39,189,631
<blockquote> <p>without uncompressing the entire file which might be in 100+ GBs</p> </blockquote> <p>I suppose you mean without extracting the file to disk first. Here's a Python approach to achieve this:</p> <pre><code>import tarfile as tf import gzip as gz from StringIO import StringIO infile = '/path/to/mysql-2016-06-16.tar.gz' def linecount(infile, member): lc = 0 with gz.GzipFile(infile) as zipf: with tf.TarFile(fileobj=zipf) as tarf: dataf = tarf.extractfile(member) while dataf.readline(): lc += 1 dataf.close() return lc print linecount(infile, 'test.csv') </code></pre> <blockquote> <p>it say's "filename 'test.csv' not found".</p> </blockquote> <p>To know what members the tar file has:</p> <pre><code>def listmembers(infile): with gz.GzipFile(infile) as zipf: with tf.TarFile(fileobj=zipf) as tarf: return list(m.name for m in tarf) </code></pre> <p>To count the lines of all files in the tarfile:</p> <pre><code>for member in listmembers(infile): print member, linecount(infile, member) </code></pre> <p>Before you start it will be useful to <a href="https://en.wikipedia.org/wiki/Tar_(computing)#File_format" rel="nofollow">know how tar files are structured</a>.</p>
1
2016-08-28T09:07:27Z
[ "python", "csv", "gzip", "tar" ]
Python function that takes one compulsory argument from two choices
39,189,472
<p>I have a function:</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID ... pass </code></pre> <p>However, my intention is for the function to take only one argument (either <code>title</code> OR <code>pageid</code>). For example, <code>delete(title="MyPage")</code> or <code>delete(pageid=53342)</code> are valid, while <code>delete(title="MyPage", pageid=53342)</code>, is not. Zero arguments can not be passed. How would I go about doing this?</p>
1
2016-08-28T08:45:35Z
39,189,491
<p>There is no Python syntax that'll let you define exclusive-or arguments, no. You'd have to explicitly raise an exception is both or none are specified:</p> <pre><code>if (title and pageid) or not (title or pageid): raise ValueError('Can only delete by title OR pageid') </code></pre>
2
2016-08-28T08:47:51Z
[ "python", "function", "arguments" ]
Python function that takes one compulsory argument from two choices
39,189,472
<p>I have a function:</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID ... pass </code></pre> <p>However, my intention is for the function to take only one argument (either <code>title</code> OR <code>pageid</code>). For example, <code>delete(title="MyPage")</code> or <code>delete(pageid=53342)</code> are valid, while <code>delete(title="MyPage", pageid=53342)</code>, is not. Zero arguments can not be passed. How would I go about doing this?</p>
1
2016-08-28T08:45:35Z
39,189,517
<p>I don't think there's any way to do this in the function signature itself. However, you could always have a check inside your function to see if both arguments are set</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID if title and pageid: # throw error or return an error value pass </code></pre> <p>Arguably a better way of doing it would be to define 2 methods that call the delete method</p> <pre><code>def delete_by_title(title): delete(title=title) def delete_by_id(id): delete(pageid=id) </code></pre> <p>The second method won't stop people calling the delete function directly, so if that's really important to you I'd advise having it throw an exception as per my first example, or else a combination of the 2.</p>
1
2016-08-28T08:51:30Z
[ "python", "function", "arguments" ]
Python function that takes one compulsory argument from two choices
39,189,472
<p>I have a function:</p> <pre><code>def delete(title=None, pageid=None): # Deletes the page given, either by its title or ID ... pass </code></pre> <p>However, my intention is for the function to take only one argument (either <code>title</code> OR <code>pageid</code>). For example, <code>delete(title="MyPage")</code> or <code>delete(pageid=53342)</code> are valid, while <code>delete(title="MyPage", pageid=53342)</code>, is not. Zero arguments can not be passed. How would I go about doing this?</p>
1
2016-08-28T08:45:35Z
39,189,525
<p>If both arguments can have any value, including <code>None</code>, then the solution is to use a sentinel object for them. Then you can calculate a sum over the number of arguments that are set to non-default value:</p> <pre><code>NOT_SET = object() def delete(title=NOT_SET, pageid=NOT_SET): if sum(i is not NOT_SET for i in [title, page_id]) != 1: raise ValueError('Can set only one of these') </code></pre> <p>This pattern is easily expandable to more arguments as well.</p>
0
2016-08-28T08:52:43Z
[ "python", "function", "arguments" ]
cannot import name SQLALchemy
39,189,548
<p>I have installed flask-sqlalchemy via pip.But something wrong happened when I run the program,that is, "cannot import name SQLALchemy"At first,I thought the problem was the improper installation.However,I still couldn't solve the problem after several uninstall and installation.Then I change the first line into "from flask_sqlalchemy import sqlalchemy" ,it became "name SQLALchemy is not defined",Still didn't work...What should I do?<a href="http://i.stack.imgur.com/ZKhwv.jpg" rel="nofollow">enter image description here</a><a href="http://i.stack.imgur.com/Nc1TG.jpg" rel="nofollow">enter image description here</a></p>
1
2016-08-28T08:56:39Z
39,189,700
<p>Try to run your Python interpreter and then use:</p> <pre><code>&gt;&gt;&gt; from flask import Flask &gt;&gt;&gt; from flask_sqlalchemy import SQLAlchemy </code></pre> <p>this should work. Your original code has a typo </p>
0
2016-08-28T09:15:39Z
[ "python", "flask-sqlalchemy" ]
cannot import name SQLALchemy
39,189,548
<p>I have installed flask-sqlalchemy via pip.But something wrong happened when I run the program,that is, "cannot import name SQLALchemy"At first,I thought the problem was the improper installation.However,I still couldn't solve the problem after several uninstall and installation.Then I change the first line into "from flask_sqlalchemy import sqlalchemy" ,it became "name SQLALchemy is not defined",Still didn't work...What should I do?<a href="http://i.stack.imgur.com/ZKhwv.jpg" rel="nofollow">enter image description here</a><a href="http://i.stack.imgur.com/Nc1TG.jpg" rel="nofollow">enter image description here</a></p>
1
2016-08-28T08:56:39Z
39,189,711
<p>I believe that imports are case sensitive. </p> <p>Try <code>from flask_sqlalchemy import SQLAlchemy</code> instead of <code>SQLALchemy</code></p>
0
2016-08-28T09:16:38Z
[ "python", "flask-sqlalchemy" ]
OSX PyGame Failed loading libpng.dylib: dlopen(libpng.dylib, 2)
39,189,550
<p>I'm getting this error <code>pygame.error: Failed loading libpng.dylib: dlopen(libpng.dylib, 2): image not found</code> when running a program on OSX (10.11.6) using Python 2.7</p> <p>I've tried following <a href="http://stackoverflow.com/questions/38645391/python-pygame-error-failed-loading-libpng-dylib-dlopenlibpng-dylib-2-imag">this</a> but I've had no luck and I can't seem to find much else on this issue. Any help on this would be greatly appreciated. </p>
1
2016-08-28T08:56:52Z
39,425,882
<p>Use python3 interpreter in terminal e.g. python3 xx.py</p>
-1
2016-09-10T12:02:43Z
[ "python", "osx", "pygame" ]
Inheriting Base from C++ in Python, call abstract method using SWIG
39,189,594
<p>I'm having some trouble coupling C++ (98) with python 3. I have some base classes in C++ which I'd like to extend in Python. Some methods in question are pure virtual on the C++ side and will thus be implemented on the Python side.</p> <p>Currently, I can call the abstract methods from C++ and, over swig, the specialization gets called in Python. Cool. I'm having trouble handing over parameters to Python..</p> <p>Minimal complete example to simplify my problem:</p> <pre><code>// iBase.h #pragma once #include &lt;memory&gt; typedef enum EMyEnumeration{ EMyEnumeration_Zero, EMyEnumeration_One, EMyEnumeration_Two }TEMyEnumeration; class FooBase{ protected: int a; public: virtual int getA() = 0 ; }; class Foo : public FooBase{ public: Foo() {a = 2;} int getA(){return a;} }; class iBase{ public: virtual void start() =0; virtual void run(std::shared_ptr&lt;FooBase&gt; p, TEMyEnumeration enumCode) = 0; }; </code></pre> <p>On the swig side: </p> <pre><code>// myif.i %module(directors="1") DllWrapper %{ #include &lt;iostream&gt; #include "iBase.h" %} %include &lt;std_shared_ptr.i&gt; %shared_ptr(FooBase) %shared_ptr(Foo) %feature("director") FooBase; %feature("director") iBase; %include "iBase.h" </code></pre> <p>Run swig as:</p> <pre><code>swig -c++ -python myif.i swig -Wall -c++ -python -external-runtime runtime.h </code></pre> <p>Compile myif_wrap.cxx -> _DllWrapper.pyd </p> <p>Create an *.exe with the following code, it will load up the _DllWrapper.pyd library (make sure it's in the same directory!). Also, copy DllWrapper.py generated by swig to the exe directory.</p> <pre><code>//Main_SmartPtr.cpp #include "stdafx.h" #include &lt;Python.h&gt; #include &lt;windows.h&gt; #include &lt;string&gt; #include &lt;memory&gt; #include "iBase.h" #include "runtime.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string moduleName = "ExampleSmartPtr"; // load *.pyd (actually a dll file which implements PyInit__&lt;swigWrapperName&gt;) auto handle =LoadLibrary("_DllWrapper.pyd"); // getting an instance handle.. Py_Initialize(); PyObject *main = PyImport_AddModule("__main__"); PyObject *dict = PyModule_GetDict(main); PyObject *module = PyImport_Import(PyString_FromString(moduleName.c_str())); PyModule_AddObject(main, moduleName.c_str(), module); PyObject *instance = PyRun_String(string(moduleName+string(".")+moduleName+string("()")).c_str(), Py_eval_input, dict, dict); //calling start() in the Python derived class.. //PyObject *result = PyObject_CallMethod(instance, "start", (char *)"()"); // trying to call run in the Python derived class.. shared_ptr&lt;Foo&gt; foo = make_shared&lt;Foo&gt;(); EMyEnumeration enumCode = EMyEnumeration_Two; string typeName1 = "std::shared_ptr &lt;FooBase&gt; *"; swig_type_info* info1 = SWIG_TypeQuery(typeName1.c_str()); auto swigData1 = SWIG_NewPointerObj((void*)(&amp;foo), info1, SWIG_POINTER_OWN); string typeName2 = "TEMyEnumeration *"; swig_type_info* info2 = SWIG_TypeQuery(typeName2.c_str()); auto swigData2 = SWIG_NewPointerObj((void*)(&amp;enumCode), info2, SWIG_POINTER_OWN); auto result = PyObject_CallMethod(instance, "run", (char *)"(O)(O)", swigData1, swigData2); return 0; } </code></pre> <p>Create a new Python file and put it in the exe's directory: </p> <pre><code>#ExampleSmartPtr.py import DllWrapper class ExampleSmartPtr(DllWrapper.iBase): def __init__(self): # constructor print("__init__!!") DllWrapper.iBase.__init__(self) def start(self): print("start") return 0 def run(self, data, enumCode): print("run") print("-&gt; data: "+str(data)) print("-&gt; enumCode: "+str(enumCode)) print (data.getA()) return 1 </code></pre> <p>The output of running the exe is :</p> <pre><code>__init__!! run -&gt; data: (&lt;DllWrapper.FooBase; proxy of &lt;Swig Object of type 'std::shared_ptr&lt; FooBase &gt; *' at 0x00000000014F8B70&gt; &gt;,) -&gt; enumCode: (&lt;Swig Object of type 'TEMyEnumeration *' at 0x00000000014F89F0&gt;,) </code></pre> <p>How can one 'dereference' the enumCode to a simple int? How does one call print (data.getA()) in python class run()? In its current form it doesn't print anything..</p>
0
2016-08-28T09:02:12Z
39,230,663
<p>This is not really an answer, but I read the discussion <a href="https://bytes.com/topic/python/answers/38519-extending-classes-written-c-using-swig" rel="nofollow">Discussion from 2005</a> and it makes sense, that it shouldn't be possible. If you on the Python side, do the following, you get your enumeration 'dereferenced' to a simple integer.</p> <pre><code>import ExampleSmartPtr instance = ExampleSmartPtr.ExampleSmartPtr() swigData1 = ExampleSmartPtr.DllWrapper.Foo() swigData2 = ExampleSmartPtr.DllWrapper.EMyEnumeration_Two instance.run(swigData1,swigData2) </code></pre> <p>This will print</p> <pre><code>__init__!! run -&gt; data: &lt;DllWrapper.Foo; proxy of &lt;Swig Object of type 'std::shared_ptr&lt; Foo &gt; *' at 0x7f8825c0b7e0&gt; &gt; -&gt; enumCode: 2 </code></pre> <p>I think that the issue is that two different vtables are into play. The original C++ vtable and that of the <code>Swig Object</code>. Just curious, in what scenario is it of interest to use a Python descendant of a C++ class from within C++?</p>
1
2016-08-30T14:46:01Z
[ "python", "c++", "swig" ]
Inheriting Base from C++ in Python, call abstract method using SWIG
39,189,594
<p>I'm having some trouble coupling C++ (98) with python 3. I have some base classes in C++ which I'd like to extend in Python. Some methods in question are pure virtual on the C++ side and will thus be implemented on the Python side.</p> <p>Currently, I can call the abstract methods from C++ and, over swig, the specialization gets called in Python. Cool. I'm having trouble handing over parameters to Python..</p> <p>Minimal complete example to simplify my problem:</p> <pre><code>// iBase.h #pragma once #include &lt;memory&gt; typedef enum EMyEnumeration{ EMyEnumeration_Zero, EMyEnumeration_One, EMyEnumeration_Two }TEMyEnumeration; class FooBase{ protected: int a; public: virtual int getA() = 0 ; }; class Foo : public FooBase{ public: Foo() {a = 2;} int getA(){return a;} }; class iBase{ public: virtual void start() =0; virtual void run(std::shared_ptr&lt;FooBase&gt; p, TEMyEnumeration enumCode) = 0; }; </code></pre> <p>On the swig side: </p> <pre><code>// myif.i %module(directors="1") DllWrapper %{ #include &lt;iostream&gt; #include "iBase.h" %} %include &lt;std_shared_ptr.i&gt; %shared_ptr(FooBase) %shared_ptr(Foo) %feature("director") FooBase; %feature("director") iBase; %include "iBase.h" </code></pre> <p>Run swig as:</p> <pre><code>swig -c++ -python myif.i swig -Wall -c++ -python -external-runtime runtime.h </code></pre> <p>Compile myif_wrap.cxx -> _DllWrapper.pyd </p> <p>Create an *.exe with the following code, it will load up the _DllWrapper.pyd library (make sure it's in the same directory!). Also, copy DllWrapper.py generated by swig to the exe directory.</p> <pre><code>//Main_SmartPtr.cpp #include "stdafx.h" #include &lt;Python.h&gt; #include &lt;windows.h&gt; #include &lt;string&gt; #include &lt;memory&gt; #include "iBase.h" #include "runtime.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string moduleName = "ExampleSmartPtr"; // load *.pyd (actually a dll file which implements PyInit__&lt;swigWrapperName&gt;) auto handle =LoadLibrary("_DllWrapper.pyd"); // getting an instance handle.. Py_Initialize(); PyObject *main = PyImport_AddModule("__main__"); PyObject *dict = PyModule_GetDict(main); PyObject *module = PyImport_Import(PyString_FromString(moduleName.c_str())); PyModule_AddObject(main, moduleName.c_str(), module); PyObject *instance = PyRun_String(string(moduleName+string(".")+moduleName+string("()")).c_str(), Py_eval_input, dict, dict); //calling start() in the Python derived class.. //PyObject *result = PyObject_CallMethod(instance, "start", (char *)"()"); // trying to call run in the Python derived class.. shared_ptr&lt;Foo&gt; foo = make_shared&lt;Foo&gt;(); EMyEnumeration enumCode = EMyEnumeration_Two; string typeName1 = "std::shared_ptr &lt;FooBase&gt; *"; swig_type_info* info1 = SWIG_TypeQuery(typeName1.c_str()); auto swigData1 = SWIG_NewPointerObj((void*)(&amp;foo), info1, SWIG_POINTER_OWN); string typeName2 = "TEMyEnumeration *"; swig_type_info* info2 = SWIG_TypeQuery(typeName2.c_str()); auto swigData2 = SWIG_NewPointerObj((void*)(&amp;enumCode), info2, SWIG_POINTER_OWN); auto result = PyObject_CallMethod(instance, "run", (char *)"(O)(O)", swigData1, swigData2); return 0; } </code></pre> <p>Create a new Python file and put it in the exe's directory: </p> <pre><code>#ExampleSmartPtr.py import DllWrapper class ExampleSmartPtr(DllWrapper.iBase): def __init__(self): # constructor print("__init__!!") DllWrapper.iBase.__init__(self) def start(self): print("start") return 0 def run(self, data, enumCode): print("run") print("-&gt; data: "+str(data)) print("-&gt; enumCode: "+str(enumCode)) print (data.getA()) return 1 </code></pre> <p>The output of running the exe is :</p> <pre><code>__init__!! run -&gt; data: (&lt;DllWrapper.FooBase; proxy of &lt;Swig Object of type 'std::shared_ptr&lt; FooBase &gt; *' at 0x00000000014F8B70&gt; &gt;,) -&gt; enumCode: (&lt;Swig Object of type 'TEMyEnumeration *' at 0x00000000014F89F0&gt;,) </code></pre> <p>How can one 'dereference' the enumCode to a simple int? How does one call print (data.getA()) in python class run()? In its current form it doesn't print anything..</p>
0
2016-08-28T09:02:12Z
39,251,709
<p>It seems somebody else tried <a href="http://stackoverflow.com/questions/9040669/how-can-i-implement-a-c-class-in-python-to-be-called-by-c">the exact same thing</a> !</p> <p>What I did was compile the *.pyd with -DSWIG_TYPE_TABLE=iBase.</p> <p>Then I added this to the main application on the cpp side:</p> <pre><code>iBase *python2interface(PyObject *obj) { void *argp1 = 0; swig_type_info * pTypeInfo = SWIG_TypeQuery("iBase *"); const int res = SWIG_ConvertPtr(obj, &amp;argp1,pTypeInfo, 0); if (!SWIG_IsOK(res)) { abort(); } return reinterpret_cast&lt;iBase*&gt;(argp1); } </code></pre> <p>and called the implementation form python like this: </p> <pre><code>auto foo = make_shared&lt;Foo&gt;(); TEMyEnumeration enumCode = EMyEnumeration_Two; python2interface(instance)-&gt;run(foo, enumCode); </code></pre> <p>To finish off, I compiled the C++ implementation again with -DSWIG_TYPE_TABLE=iBase.</p> <p>Works like a charm!</p>
0
2016-08-31T13:58:59Z
[ "python", "c++", "swig" ]
Conditional length of a binary data series in Pandas
39,189,605
<p>Having a DataFrame with the following column:</p> <pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1] </code></pre> <p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p> <pre><code> A B 0 1 1 1 1 1 2 1 0 3 0 0 4 1 1 5 1 1 6 1 0 7 1 0 8 0 0 9 1 1 </code></pre>
0
2016-08-28T09:04:08Z
39,189,829
<p>One fully-vectorized solution is to use the <code>shift</code>-<code>groupby</code>-<code>cumsum</code>-<code>cumcount</code> combination<sup>1</sup> to indicate where consecutive runs are shorter than 2 (or whatever limiting value you like). Then, <code>&amp;</code> this new boolean Series with the original column:</p> <pre><code>df['B'] = ((df.groupby((df.A != df.A.shift()).cumsum()).cumcount() &lt;= 1) &amp; df.A)\ .astype(int) # cast the boolean Series back to integers </code></pre> <p>This produces the new column in the DataFrame:</p> <pre><code> A B 0 1 1 1 1 1 2 1 0 3 0 0 4 1 1 5 1 1 6 1 0 7 1 0 8 0 0 9 1 1 </code></pre> <hr> <p><sup>1</sup> See the <a href="http://pandas.pydata.org/pandas-docs/stable/cookbook.html#grouping" rel="nofollow">pandas cookbook</a>; the section on grouping, "Grouping like Python’s itertools.groupby"</p>
3
2016-08-28T09:28:21Z
[ "python", "pandas", "vectorization" ]
Conditional length of a binary data series in Pandas
39,189,605
<p>Having a DataFrame with the following column:</p> <pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1] </code></pre> <p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p> <pre><code> A B 0 1 1 1 1 1 2 1 0 3 0 0 4 1 1 5 1 1 6 1 0 7 1 0 8 0 0 9 1 1 </code></pre>
0
2016-08-28T09:04:08Z
39,189,842
<p>Another way (checking if previous two are 1):</p> <pre><code>In [443]: df = pd.DataFrame({'A': [1,1,1,0,1,1,1,1,0,1]}) In [444]: limit = 2 In [445]: df['B'] = map(lambda x: df['A'][x] if x &lt; limit else int(not all(y == 1 for y in df['A'][x - limit:x])), range(len(df))) In [446]: df Out[446]: A B 0 1 1 1 1 1 2 1 0 3 0 0 4 1 1 5 1 1 6 1 0 7 1 0 8 0 0 9 1 1 </code></pre>
2
2016-08-28T09:30:03Z
[ "python", "pandas", "vectorization" ]
Conditional length of a binary data series in Pandas
39,189,605
<p>Having a DataFrame with the following column:</p> <pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1] </code></pre> <p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p> <pre><code> A B 0 1 1 1 1 1 2 1 0 3 0 0 4 1 1 5 1 1 6 1 0 7 1 0 8 0 0 9 1 1 </code></pre>
0
2016-08-28T09:04:08Z
39,189,964
<p>If you know that the values in the series will all be either <code>0</code> or <code>1</code>, I think you can use a little trick involving convolution. Make a copy of your column (which need not be a Pandas object, it can just be a normal Numpy array)</p> <pre><code>a = df['A'].as_matrix() </code></pre> <p>and convolve it with a sequence of 1's that is one longer than the <code>cutoff</code> you want, then chop off the last <code>cutoff</code> elements. E.g. for a <code>cutoff</code> of 2, you would do</p> <pre><code>long_run_count = numpy.convolve(a, [1, 1, 1])[:-2] </code></pre> <p>The resulting array, in this case, gives the number of <code>1</code>'s that occur in the 3 elements prior to and including that element. If that number is 3, then you are in a run that has exceeded length 2. So just set those elements to zero.</p> <pre><code>a[long_run_count &gt; 2] = 0 </code></pre> <p>You can now assign the resulting array to a new column in your <code>DataFrame</code>.</p> <pre><code>df['B'] = a </code></pre> <p>To turn this into a more general method:</p> <pre><code>def trim_runs(array, cutoff): a = numpy.asarray(array) a[numpy.convolve(a, numpy.ones(cutoff + 1))[:-cutoff] &gt; cutoff] = 0 return a </code></pre>
2
2016-08-28T09:45:33Z
[ "python", "pandas", "vectorization" ]
Python calculate ageing of outlook mail items
39,189,689
<p>I am trying to develop an application in wxPython in which I will fetch all e-mails into a listctrl and sort them based on their remaining SLA (3 days) for further action. For this I will calculate the ageing of the items in the mailbox by deducting the receivedTime from current time. Below is my complete code:-</p> <pre><code>from datetime import datetime import time import win32com.client import wx class MainFrame(wx.Frame): def __init__(self, parent, myTitle): super(MainFrame, self).__init__(parent, title = myTitle, size = (1300,600)) #set the background color self.index = 0 self.SetBackgroundColour((230, 230, 250)) #create fonts FrameLabels_Font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.BOLD, True, u'Bookman Old Style') listItems_Font = wx.Font(8, wx.DECORATIVE, wx.NORMAL, wx.NORMAL, True, u'Bookman Old Style') #set the frame self.frame_Controls = wx.StaticBox(self, label="Controls:-", pos=(10, 275), size=(300, 250), style=wx.RAISED_BORDER) self.frame_Controls.SetBackgroundColour((230, 230, 250)) self.frame_Controls.SetFont(FrameLabels_Font) self.frame_Summary = wx.StaticBox(self, label="Stats:-", pos=(10, 10), size=(300, 250), style=wx.RAISED_BORDER) self.frame_Summary.SetBackgroundColour((230, 230, 250)) self.frame_Summary.SetFont(FrameLabels_Font) self.frame_Queue = wx.StaticBox(self, label="Work Items:-", pos=(320, 10), size=(950, 515), style=wx.RAISED_BORDER) self.frame_Queue.SetBackgroundColour((230, 230, 250)) self.frame_Queue.SetFont(FrameLabels_Font) #controls for queue frame LblRegion = wx.StaticText(self.frame_Queue, -1, 'Region:-', (20, 25), (150, 25)) LblMailbox = wx.StaticText(self.frame_Queue, -1, 'Mailbox:-', (190, 25), (150, 25)) LblSortBy = wx.StaticText(self.frame_Queue, -1, 'Sort By:-', (360, 25), (150, 25)) LblSortOrder = wx.StaticText(self.frame_Queue, -1, 'Sort Order:-', (530, 25), (150, 25)) rdoUnallocated = myRadioButton(self.frame_Queue, 'UnAllocated', (700,25), (110,25)) rdoAllocated = myRadioButton(self.frame_Queue, 'Allocated', (820, 25), (110, 25)) rgnCombo = myComboBox(self.frame_Queue,(20,60),(150,25)) rgnCombo = myComboBox(self.frame_Queue, (190, 60), (150, 25)) rgnCombo = myComboBox(self.frame_Queue, (360, 60), (150, 25)) rgnCombo = myComboBox(self.frame_Queue, (530, 60), (150, 25)) self.subList = myListCtrl(self.frame_Queue,(20,95),(910,390)) self.subList.InsertColumn(0, 'Rush') self.subList.InsertColumn(1, 'Subject') self.subList.InsertColumn(2, 'Recevd DtTm') self.subList.InsertColumn(3, 'Allocated To') self.subList.InsertColumn(4, 'Allo. ID') self.subList.InsertColumn(5, 'Unique Key') self.subList.InsertColumn(6, 'Rem. SLA') self.subList.InsertColumn(7, 'Ageing') self.subList.InsertColumn(8, 'Duplicate') self.subList.InsertColumn(9, 'Actionable') self.subList.InsertColumn(10, 'Status') self.subList.InsertColumn(11, 'Start DtTm') self.subList.InsertColumn(12, 'Query DtTm') self.subList.InsertColumn(13, 'Hold DtTm') self.subList.InsertColumn(14, 'Continue DtTm') self.subList.InsertColumn(15, 'Final Status') self.subList.InsertColumn(16, 'Final Status DtTm') self.subList.InsertColumn(17, 'Final Status Date') #update the listctrl getConn = OutlookConnection() messages = getConn.fetchUnallocated() for msg in messages: self.subList.InsertStringItem(self.index, '') self.subList.SetItemFont(self.index, listItems_Font) self.subList.SetStringItem(self.index, 1, msg.subject) self.subList.SetStringItem(self.index, 2, str(msg.receivedtime)) if msg.Importance == 2: self.subList.SetStringItem(self.index, 0, 'Y') self.subList.SetItemBackgroundColour(self.index, (255,0,0)) #tm = datetime.now().strftime("%m-%d-%Y %H:%M:%S") - msg.receivedtime #tm = datetime.now() - msg.receivedtime tm = time.mktime(datetime.now().timetuple()) - msg.receivedtime #tm = datetime.now() - datetime.fromtimestamp(time.mktime(msg.receivedtime)) #self.subList.SetStringItem(self.index, 7, str(datetime.now().strftime("%m-%d-%Y %H:%M:%S"))) self.subList.SetStringItem(self.index, 7, str(tm)) #add the menu here self.AddMenu() #display the frame self.Centre() self.Show() #create the AddMenu def def AddMenu(self): menuBar = wx.MenuBar() #file menu File_btn = wx.Menu() #sub menu items of file menu #Logout Logout_btn = File_btn.Append(wx.ID_EXIT,'&amp;Logout', 'Close the application') #now put the File_btn to the menuBar menuBar.Append(File_btn, '&amp;File') #set the menu bar in the application main frame self.SetMenuBar(menuBar) #now bind the code which will run upon clicking the Logout button self.Bind(wx.EVT_MENU, self.Quit, Logout_btn) #def the self.Quit process def Quit(self,x): self.Close() #class for querying database class dbQuery(): #method for getting the list of regions def RegionsList(self): myDb = 'H:\\Python\\wxPython\\Programs\\References.accdb' DRV = '{Microsoft Access Driver (*.mdb)}' PWD = 'pw' # connect to db conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s' % (myDb)) cur = conn.cursor() # run a query and get the results SQL = 'SELECT * FROM Regions' return cur.execute(SQL, self.Tname).fetchall() cur.close() conn.close() class myRadioButton(wx.RadioButton): def __init__(self, parent, mylabel, vPosition, vSize): super(myRadioButton, self).__init__(parent, -1, label = mylabel, pos = vPosition, size = vSize) class myComboBox(wx.ComboBox): def __init__(self, parent, lstposition, lstsize): super(myComboBox, self).__init__(parent, -1, value="", pos=lstposition, size=lstsize) #this method will be used to add items from a list to the instance of the mycombobox def addItem(self, Lst=[]): for itm in Lst: self.Append(itm) class myListCtrl(wx.ListCtrl): def __init__(self,parent, vPosition, vSize): super(myListCtrl, self).__init__(parent, -1, pos = vPosition, size = vSize, style=wx.LC_REPORT |wx.BORDER_SUNKEN) class OutlookConnection(): def fetchUnallocated(self): outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case inbox, return inbox.Items app = wx.App() FIR_Frame = MainFrame(None, 'F.I.R - TL Interface') app.MainLoop() </code></pre> <p>The challenge I am facing is in the line where I am trying to calculate the ageing of the mail item:-</p> <pre><code>tm = datetime.now() - msg.receivedtime self.subList.SetStringItem(self.index, 7, str(tm)) </code></pre> <p>I am getting error :- <em>tm = datetime.now() - msg.receivedtime TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'time'</em></p> <p>I have tried more formats/ways... you can see them in the above code resulting in similar errors</p> <p>Can someone please help me with calculating the ageing in 'HH:MM:SS' format. Also the hours should populate in greater than 24 wherever required (i.e if ageing is more than 24 hours).</p> <p>Thank you so much in advance.</p> <p>Regards, Premanshu</p>
0
2016-08-28T09:14:38Z
39,224,240
<p>There are many ways to do this, here is one way.<br> Check what the structure of <code>msg.receivedtime</code> is and then convert it into seconds to be able to manipulate it. I am assuming the following structure of <code>msg.receivedtime</code> "2016-08-30 10:30:15"<br> Use <code>time.time()</code> rather than <code>datetime.now()</code> to get <code>now</code></p> <pre><code>&gt;&gt;&gt; tm = int(time.time()) &gt;&gt;&gt; tm 1472550462 &gt;&gt;&gt; msg_receivedtime = "2016-08-30 10:30:15" &gt;&gt;&gt; msg_tuple = time.strptime(msg_receivedtime, "%Y-%m-%d %H:%M:%S") &gt;&gt;&gt; msg_stamp = int(time.mktime(msg_tuple)) &gt;&gt;&gt; msg_stamp 1472545815 &gt;&gt;&gt; print tm - msg_stamp 4647 </code></pre> <p>Note: I have reduced the time stamps to integer seconds in both cases<br> Edit:<br> to convert seconds to hh:mm:ss </p> <pre><code>&gt;&gt;&gt; x = 4647 &gt;&gt;&gt; m,s =divmod(x,60) &gt;&gt;&gt; h,m =divmod(m,60) &gt;&gt;&gt; print h,m,s 1 17 27 </code></pre> <p>Edit: Concerning comment about date stamps more than 48 hours old </p> <p>You must be doing something wrong!<br> Here is the code from above, using a value of time.time() as of Monday 5th September 2016.</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; tm = int(time.time()) &gt;&gt;&gt; tm 1473064274 &gt;&gt;&gt; msg_receivedtime = "2016-08-30 10:30:15" &gt;&gt;&gt; msg_tuple = time.strptime(msg_receivedtime, "%Y-%m-%d %H:%M:%S") &gt;&gt;&gt; msg_stamp = int(time.mktime(msg_tuple)) &gt;&gt;&gt; msg_stamp 1472545815 &gt;&gt;&gt; x = tm - msg_stamp &gt;&gt;&gt; x 518459 &gt;&gt;&gt; m,s =divmod(x,60) &gt;&gt;&gt; h,m =divmod(m,60) &gt;&gt;&gt; print h,m,s 144 0 59 </code></pre> <p>Note that 144 hours is 6 days<br> Which is what you required: </p> <blockquote> <p>Can someone please help me with calculating the ageing in 'HH:MM:SS' format. Also the hours should populate in greater than 24 wherever required (i.e if ageing is more than 24 hours).</p> </blockquote>
0
2016-08-30T09:51:05Z
[ "python", "email" ]
pandas groupby sort on summary statistics
39,189,722
<pre><code> date shown clicked converted avg_cost_per_click total_revenue ad 0 2015-10-01 65877 2339 43 0.90 641.62 ad_group_1 1 2015-10-02 65100 2498 38 0.94 756.37 ad_group_2 2 2015-10-03 70658 2313 49 0.86 970.90 ad_group_3 3 2015-10-04 69809 2833 51 1.01 907.39 ad_group_4 4 2015-10-05 68186 2696 41 1.00 879.45 ad_group_5 </code></pre> <p>This is my dataframe <code>df</code></p> <p>i group by 'ad' and then i want to sort the output when i get the mean, max ect..</p> <pre><code>df_ad = df.groupby('ad') </code></pre> <p>How do i sort the below?</p> <pre><code>df_ad['shown'].mean().sort(ascending=True) </code></pre>
0
2016-08-28T09:17:31Z
39,190,210
<p>You need to aggregate the mean on every grouped key and use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html#pandas.DataFrame.sort_values" rel="nofollow"><code>sort_values</code></a> to sort those output values.</p> <pre><code>df_grouped = df.groupby(['ad'])['shown'].agg({'mean': np.mean, 'max': np.max}) df_grouped.sort_values(['mean', 'max'], ascending=[True, False], inplace=True) </code></pre>
1
2016-08-28T10:12:27Z
[ "python", "pandas" ]
I got error while using "git push heroku master"
39,189,780
<p>I'm using the below given commands for push data to heroku app.</p> <pre><code>git clone https://git.heroku.com/bigpro.git cd bigpro git add . git commit . -m "my test on commit" git push heroku master </code></pre> <p>When I used <code>git push heroku master</code> I got something like this..</p> <pre><code>fatal: 'heroku' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. </code></pre> <p>Then I gave <code>heroku open</code> command, I got an error which is </p> <pre><code>▸ ENOTFOUND: getaddrinfo ENOTFOUND api.heroku.com api.heroku.com:443 </code></pre> <p>When I got the above error I tried to change commands on terminal by using <code>heroku git:clone -a bigpro</code> and after made my changes, I gave <code>git push heroku master</code> ,I got an error</p> <pre><code> remote: ! Push rejected to bigpro. remote: To git.heroku.com/bigpro.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'git.heroku.com/bigpro.git'; </code></pre>
5
2016-08-28T09:23:13Z
39,189,821
<p>First, install the <a href="https://toolbelt.heroku.com" rel="nofollow">heroku toolbelt</a>, and then type <code>heroku login</code> to setup your account properly.</p> <p>Next, type <code>heroku git:clone -a myapp</code> where <code>myapp</code> is the name of your application in Heroku. This will pull the repository and setup the remotes correctly for you.</p> <p>Next, make your changes as usual.</p> <p>Then you can do <code>git push heroku master</code></p>
2
2016-08-28T09:27:40Z
[ "python", "heroku", "github" ]
I got error while using "git push heroku master"
39,189,780
<p>I'm using the below given commands for push data to heroku app.</p> <pre><code>git clone https://git.heroku.com/bigpro.git cd bigpro git add . git commit . -m "my test on commit" git push heroku master </code></pre> <p>When I used <code>git push heroku master</code> I got something like this..</p> <pre><code>fatal: 'heroku' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. </code></pre> <p>Then I gave <code>heroku open</code> command, I got an error which is </p> <pre><code>▸ ENOTFOUND: getaddrinfo ENOTFOUND api.heroku.com api.heroku.com:443 </code></pre> <p>When I got the above error I tried to change commands on terminal by using <code>heroku git:clone -a bigpro</code> and after made my changes, I gave <code>git push heroku master</code> ,I got an error</p> <pre><code> remote: ! Push rejected to bigpro. remote: To git.heroku.com/bigpro.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'git.heroku.com/bigpro.git'; </code></pre>
5
2016-08-28T09:23:13Z
40,142,561
<p>This happened to me after I cloned from heroku a second copy of my files. Suddenly <code>git push heroku master</code> wouldn't work and I'd get the same error as you. But when I tried <code>git push origin master</code>, it worked fine.</p>
1
2016-10-19T22:29:36Z
[ "python", "heroku", "github" ]
Conditional editing of strings in a Pandas DataFrame
39,189,794
<p>I am learning Pandas and have a DataFrame of strings which looks a little like this:</p> <pre><code>df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B']) df A B 0 Apple Med6g7867 1 Orange Med7g8976 2 Banana Signal 3 Peach Med8g8989 4 Mango Possible result %gggyy </code></pre> <p>Note column B has two types of value, either a unique identifier of the form MedXgXXXX or a descriptive string. I would like to do two related things.</p> <ol> <li>Substitute all the values of B with the unique identifier to NaN</li> <li>Retain the descriptive string but truncate any that have a % sign so that I only retain the string prior to the % sign.</li> </ol> <p>I would like a table like this:</p> <pre><code> A B 0 Apple NaN 1 Orange NaN 2 Banana Signal 3 Peach NaN 4 Mango Possible result </code></pre> <p>Currently I can subset the table like so:</p> <pre><code>df[df['B'].str.contains("Med")] df[df['B'].str.contains("%")] </code></pre> <p>but no implementation of <code>replace()</code> I try allows me to do this.</p> <p>Any help appreciated.</p>
2
2016-08-28T09:24:59Z
39,189,946
<p>You can apply replace twice like this:</p> <pre><code>In [460]: df Out[460]: A B 0 Apple Med6g7867 1 Orange Med7g8976 2 Banana Signal 3 Peach Med8g8989 4 Mango Possible result %gggyy In [461]: df.replace(r'Med\dg\d{4}', np.nan, regex=True).replace(r'\s+%.*', '', regex=True) Out[461]: A B 0 Apple NaN 1 Orange NaN 2 Banana Signal 3 Peach NaN 4 Mango Possible result </code></pre>
2
2016-08-28T09:43:17Z
[ "python", "regex", "pandas" ]
Conditional editing of strings in a Pandas DataFrame
39,189,794
<p>I am learning Pandas and have a DataFrame of strings which looks a little like this:</p> <pre><code>df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B']) df A B 0 Apple Med6g7867 1 Orange Med7g8976 2 Banana Signal 3 Peach Med8g8989 4 Mango Possible result %gggyy </code></pre> <p>Note column B has two types of value, either a unique identifier of the form MedXgXXXX or a descriptive string. I would like to do two related things.</p> <ol> <li>Substitute all the values of B with the unique identifier to NaN</li> <li>Retain the descriptive string but truncate any that have a % sign so that I only retain the string prior to the % sign.</li> </ol> <p>I would like a table like this:</p> <pre><code> A B 0 Apple NaN 1 Orange NaN 2 Banana Signal 3 Peach NaN 4 Mango Possible result </code></pre> <p>Currently I can subset the table like so:</p> <pre><code>df[df['B'].str.contains("Med")] df[df['B'].str.contains("%")] </code></pre> <p>but no implementation of <code>replace()</code> I try allows me to do this.</p> <p>Any help appreciated.</p>
2
2016-08-28T09:24:59Z
39,190,786
<pre><code>import pandas as pd df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B']) df['B'] = df['B'].str.extract(r'(?:^Med.g.{4})|([^%]+)', expand=False) print(df) </code></pre> <p>yields</p> <pre><code> A B 0 Apple NaN 1 Orange NaN 2 Banana Signal 3 Peach NaN 4 Mango Possible result </code></pre> <hr> <p>The regex pattern has the following meaning:</p> <pre><code>(?: # start a non-capturing group ^ # match the start of the string Med # match the literal string Med . # followed by any character g # a literal g .{4} # followed by any 4 characters ) # end the non-capturing group | # OR ( # start a capturing group [^%]+ # 1-or-more of any characters except % ) # end capturing group </code></pre> <p>If the value in the <code>B</code> column starts with a unique indentifier of the form <code>MedXgXXXX</code> then the non-capturing group will be matched. Since <code>str.extract</code> only returns the value from capturing groups, the <code>Series</code> returned by <code>str.extract</code> will have a <code>NaN</code> at this location.</p> <p>If instead the capturing group is matched, then <code>str.extract</code> will return the matched value.</p>
2
2016-08-28T11:28:45Z
[ "python", "regex", "pandas" ]
show price based on product selected in form box
39,189,811
<p>I have a model of product and sale. A product contains a list of product with name, price and quantity where a sales model has product(Foreign key), quantity and price. There is a form for sale which shows list of products, quantity and price. Whenever a user selects for the product, the price field should show the price of that product and which should be uneditable. How can it be done?</p> <p>My code</p> <p><strong>Product</strong></p> <pre><code>class Product(models.Model): name = models.CharField(max_length=120, blank=True, null=True, help_text="name of the product") quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return self.name </code></pre> <p><strong>product/forms.py</strong></p> <pre><code>PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' </code></pre> <p><strong>product/views.py</strong></p> <pre><code>def add_product(request): if request.method=='POST': form = ProductForm(request.POST or None) if form.is_valid(): # product = form.save(commit=false) # product.save() name = form.cleaned_data['name'] price = form.cleaned_data['price'] quantity = form.cleaned_data['quantity'] Product.objects.create(name=name, quantity=quantity, price=price) messages.success(request, 'Product is successfully added.') return redirect('/product/') else: form = ProductForm() return render(request, 'product/product_add.html', {'form':form}) </code></pre> <p><strong>sales/models.py</strong></p> <pre><code>class Sale(models.Model): product = models.ForeignKey(Product) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return self.product.name </code></pre> <p><strong>sales/forms.py</strong></p> <pre><code>class SaleForm(forms.ModelForm): class Meta: model = Sale fields = '__all__' </code></pre> <p>In the image(sale form), i have selected the product shoe and its price is say $70, now after selecting the product shoe my price box should show $70 inside it. Likewise, if i selected the product football, the price box should show price of football. <a href="http://i.stack.imgur.com/fXBP0.png" rel="nofollow"><img src="http://i.stack.imgur.com/fXBP0.png" alt="enter image description here"></a></p> <p><strong>UPDATE</strong></p> <p><strong>sales/urls.py</strong></p> <pre><code>url(r'^price/(?P&lt;pk&gt;\d+)$', views.fetch_price, name='fetch_price'), </code></pre> <p><strong>sales/views.py for ajax</strong></p> <pre><code>def add_sale(request): if request.method=='POST': form = SaleForm(request.POST or None) form.fields['price'].widget.attrs['disabled']=True if form.is_valid(): # product = form.save(commit=false) # product.save() product = form.cleaned_data['product'] price = form.cleaned_data['price'] quantity = form.cleaned_data['quantity'] Sale.objects.create(product=product, quantity=quantity, price=price) messages.success(request, 'Product is successfully sold.') return redirect('/product/') else: form = SaleForm() return render(request, 'sale/add_sale.html', {'form':form}) def fetch_price(request, pk): product = get_object_or_404(Product, pk=pk) print('product',product) if request.method=='GET': response = HttpResponse('') price = product.price print('price',price) response['price-pk'] = product.pk response['price'] = price return response </code></pre> <p><strong>add_sale.html</strong></p> <pre><code>&lt;script&gt; $('#id_product').on('change', function() { price_value = $(this).val(); console.log(price_value); $.ajax({ type:'GET', url:'/sale/price/'+price_value+"/", success: function(data){ console.log('price will be updated based on product selected'); $('#id_price').val(data.price); } }) }); &lt;/script&gt; </code></pre> <p>This way i get 404 error</p>
0
2016-08-28T09:27:13Z
39,190,446
<p>Try this to disable a form field.</p> <pre><code>form = SaleForm() form.fields['price'].widget.attrs['disabled'] = True </code></pre> <p>This just disable it in front end only. You have to o validations in backend form validation because, in frontend anyone can do disable to enable.</p>
0
2016-08-28T10:44:21Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
show price based on product selected in form box
39,189,811
<p>I have a model of product and sale. A product contains a list of product with name, price and quantity where a sales model has product(Foreign key), quantity and price. There is a form for sale which shows list of products, quantity and price. Whenever a user selects for the product, the price field should show the price of that product and which should be uneditable. How can it be done?</p> <p>My code</p> <p><strong>Product</strong></p> <pre><code>class Product(models.Model): name = models.CharField(max_length=120, blank=True, null=True, help_text="name of the product") quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return self.name </code></pre> <p><strong>product/forms.py</strong></p> <pre><code>PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' </code></pre> <p><strong>product/views.py</strong></p> <pre><code>def add_product(request): if request.method=='POST': form = ProductForm(request.POST or None) if form.is_valid(): # product = form.save(commit=false) # product.save() name = form.cleaned_data['name'] price = form.cleaned_data['price'] quantity = form.cleaned_data['quantity'] Product.objects.create(name=name, quantity=quantity, price=price) messages.success(request, 'Product is successfully added.') return redirect('/product/') else: form = ProductForm() return render(request, 'product/product_add.html', {'form':form}) </code></pre> <p><strong>sales/models.py</strong></p> <pre><code>class Sale(models.Model): product = models.ForeignKey(Product) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return self.product.name </code></pre> <p><strong>sales/forms.py</strong></p> <pre><code>class SaleForm(forms.ModelForm): class Meta: model = Sale fields = '__all__' </code></pre> <p>In the image(sale form), i have selected the product shoe and its price is say $70, now after selecting the product shoe my price box should show $70 inside it. Likewise, if i selected the product football, the price box should show price of football. <a href="http://i.stack.imgur.com/fXBP0.png" rel="nofollow"><img src="http://i.stack.imgur.com/fXBP0.png" alt="enter image description here"></a></p> <p><strong>UPDATE</strong></p> <p><strong>sales/urls.py</strong></p> <pre><code>url(r'^price/(?P&lt;pk&gt;\d+)$', views.fetch_price, name='fetch_price'), </code></pre> <p><strong>sales/views.py for ajax</strong></p> <pre><code>def add_sale(request): if request.method=='POST': form = SaleForm(request.POST or None) form.fields['price'].widget.attrs['disabled']=True if form.is_valid(): # product = form.save(commit=false) # product.save() product = form.cleaned_data['product'] price = form.cleaned_data['price'] quantity = form.cleaned_data['quantity'] Sale.objects.create(product=product, quantity=quantity, price=price) messages.success(request, 'Product is successfully sold.') return redirect('/product/') else: form = SaleForm() return render(request, 'sale/add_sale.html', {'form':form}) def fetch_price(request, pk): product = get_object_or_404(Product, pk=pk) print('product',product) if request.method=='GET': response = HttpResponse('') price = product.price print('price',price) response['price-pk'] = product.pk response['price'] = price return response </code></pre> <p><strong>add_sale.html</strong></p> <pre><code>&lt;script&gt; $('#id_product').on('change', function() { price_value = $(this).val(); console.log(price_value); $.ajax({ type:'GET', url:'/sale/price/'+price_value+"/", success: function(data){ console.log('price will be updated based on product selected'); $('#id_price').val(data.price); } }) }); &lt;/script&gt; </code></pre> <p>This way i get 404 error</p>
0
2016-08-28T09:27:13Z
39,190,518
<p>You should write javascript code to detect the <code>onchange</code> event of the <code>product</code> field. In the <code>onchange</code> event handler, you should fire the AJAX call to the backend to fetch the information for the selected product by passing the <code>product_id</code>. Typically, this is an another view function called from <code>urls.py</code>. Once the backend responds, the callback of AJAX call should update the <code>price</code> field. You can consider using <code>jQuery</code> instead of plain <code>javascript</code> to ease the implementation.</p>
0
2016-08-28T10:53:50Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
Can't convert a Python List to timeSeries
39,189,876
<p>I tried to resolve this problem for more than a day. I have this type of list:</p> <pre><code>TempList[:5] [(datetime.datetime(2015, 11, 25, 7, 29, 28, 337000),), (datetime.datetime(2015, 9, 8, 7, 44, 55, 53000),), (datetime.datetime(2015, 9, 10, 5, 44, 51, 867000),), (datetime.datetime(2015, 9, 10, 1, 42, 15, 740000),), (datetime.datetime(2015, 9, 2, 1, 7, 09, 687000),)] </code></pre> <p>I would like to converti it as a Pandas <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-series-date-functionality" rel="nofollow">Time Series</a>. I found this useful <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#converting-to-timestamps" rel="nofollow">function: pd.to_datetime</a>. But when I try to convert it:</p> <pre><code>Dates = pd.to_datetime(TempList) </code></pre> <p>I got This Error:</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/dist-packages/pandas/util/decorators.py", line 91, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pandas/tseries/tools.py", line 291, in to_datetime unit=unit, infer_datetime_format=infer_datetime_format) File "/usr/local/lib/python2.7/dist-packages/pandas/tseries/tools.py", line 427, in _to_datetime return _convert_listlike(arg, box, format) File "/usr/local/lib/python2.7/dist-packages/pandas/tseries/tools.py", line 341, in _convert_listlike raise TypeError('arg must be a string, datetime, list, tuple, ' TypeError: arg must be a string, datetime, list, tuple, 1-d array, or Series </code></pre> <p>But TempList is a list! I can't understand how to resolve this. How can I convert my list? Thank you!</p>
4
2016-08-28T09:33:51Z
39,189,948
<p>You have a list of tuples. Try converting that into a plain list, and then using <code>pd.to_datetime</code>. Something like (I do not have python right now)</p> <pre><code>tl2 = [ ti[0] for ti in TempList ] Dates = pd.to_datetime(tl2) </code></pre> <p>PS1: What else do you have in <code>TempList</code>? (you only show the first 5 elements).</p> <p>PS2: You might need to use the <code>format</code> argument, see <a href="http://stackoverflow.com/a/26763793/2707864">http://stackoverflow.com/a/26763793/2707864</a>.</p>
3
2016-08-28T09:43:45Z
[ "python", "pandas", "time-series" ]
How to subclass list and trigger an event whenever the data change?
39,189,893
<p>I would like to subclass <code>list</code> and trigger an event (data checking) every time any change happens to the data. Here is an example subclass:</p> <pre><code>class MyList(list): def __init__(self, sequence): super().__init__(sequence) self._test() def __setitem__(self, key, value): super().__setitem__(key, value) self._test() def append(self, value): super().append(value) self._test() def _test(self): """ Some kind of check on the data. """ if not self == sorted(self): raise ValueError("List not sorted.") </code></pre> <p>Here, I am overriding methods <code>__init__</code>, <code>__setitem__</code> and <code>__append__</code> to perform the check if data changes. I think this approach is undesirable, so my question is: Is there a possibilty of triggering data checking automatically if <em>any</em> kind of mutation happens to the underlying data structure?</p>
12
2016-08-28T09:36:06Z
39,190,103
<p>As you say, this is not the best way to go about it. To correctly implement this, you'd need to know about every method that can change the list.</p> <p>The way to go is to implement your own list (or rather a mutable sequence). The best way to do this is to use the abstract base classes from Python which you find in the <a href="https://docs.python.org/library/collections.abc.html" rel="nofollow"><code>collections.abc</code></a> module. You have to implement only a minimum amount of methods and the module automatically implements the rest for you.</p> <p>For your specific example, this would be something like this:</p> <pre><code>from collections.abc import MutableSequence class MyList(MutableSequence): def __init__(self, iterable=()): self._list = list(iterable) def __getitem__(self, key): return self._list.__getitem__(key) def __setitem__(self, key, item): self._list.__setitem__(key, item) # trigger change handler def __delitem__(self, key): self._list.__delitem__(key) # trigger change handler def __len__(self): return self._list.__len__() def insert(self, index, item): self._list.insert(index, item) # trigger change handler </code></pre> <h3>Performance</h3> <p>Some methods are slow in their default implementation. For example <code>__contains__</code> is defined in the <a href="https://hg.python.org/cpython/file/tip/Lib/_collections_abc.py#l806" rel="nofollow"><code>Sequence</code> class</a> as follows:</p> <pre><code>def __contains__(self, value): for v in self: if v is value or v == value: return True return False </code></pre> <p>Depending on your class, you might be able to implement this faster. However, performance is often less important than writing code which is easy to understand. It can also make writing a class harder, because you're then responsible for implementing the methods correctly.</p>
7
2016-08-28T10:01:04Z
[ "python" ]
Python code won't run?
39,189,900
<p>Hello i was wondering why this code will not run,thanks.</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter a number(0 to finish)")) if number == 0: finished = True else: total = total + number count = count + 1 print("the average is", total/ count) count = 0 </code></pre>
-3
2016-08-28T09:37:04Z
39,189,916
<p>It does run, the only issue I can see is that your else is indented inside your if block. In Python, indentation is important in a way that curled brackets or keywords are important in other programming languages.</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter a number(0 to finish)")) if number == 0: finished = True else: total = total + number count = count + 1 print("the average is", total/ count) count = 0 </code></pre>
0
2016-08-28T09:40:05Z
[ "python", "python-3.x" ]
Python code won't run?
39,189,900
<p>Hello i was wondering why this code will not run,thanks.</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter a number(0 to finish)")) if number == 0: finished = True else: total = total + number count = count + 1 print("the average is", total/ count) count = 0 </code></pre>
-3
2016-08-28T09:37:04Z
39,189,939
<p>Your script is alright, you haven't indented properly the <code>else</code>clause, here's a working example, also, you should cast to float your average:</p> <pre><code>count = 0 finished = False total = 0 while not finished: number = int(input("Enter a number(0 to finish)")) if number == 0: finished = True else: total = total + number count = count + 1 print("the average is", float(total) / float(count)) count = 0 </code></pre> <p>Another possible way to do the same with few lines would be this:</p> <pre><code>values = [] while True: number = int(input("Enter a number(0 to finish)")) if number == 0: break values.append(number) print("the average is", float(sum(values)) / float(len(values))) </code></pre>
0
2016-08-28T09:42:54Z
[ "python", "python-3.x" ]
Unusual permutations
39,190,036
<p>I have few lists:</p> <pre><code>a = [1,2,3] b = [4,5,6] c = [7,8,9,10] </code></pre> <p>How do I generate all combinations like:</p> <pre><code>a[0], b[0] a[1], b[1] a[2], b[2] a[0], b[0], c[0] a[1], b[1], c[0] a[2], b[2], c[0] a[1], b[1], c[1] a[2], b[2], c[2] a[0], b[0], c[3] a[1], b[1], c[3] a[2], b[2], c[3] ..... </code></pre> <p>There can be only one value at a time from each list.</p> <p>Imagine two or more lists Like a=[1,2,3] and b=[4,5,6] and c=[7,8,9] and I would like all possible pairs like (a[0], b[0]),(a[1], b[1]), (a[0], b[0], c[0])... </p>
0
2016-08-28T09:54:43Z
39,190,125
<p>Not sure whether I've understood correctly your question, but do you mean this?</p> <pre><code>from itertools import permutations my_list = ['a1', 'a2', 'a3', 'b1', 'b2', 'c1'] for i in range(len(my_list)): print(list(permutations(my_list, i))) </code></pre>
0
2016-08-28T10:03:37Z
[ "python", "algorithm", "combinations", "permutation" ]
Unusual permutations
39,190,036
<p>I have few lists:</p> <pre><code>a = [1,2,3] b = [4,5,6] c = [7,8,9,10] </code></pre> <p>How do I generate all combinations like:</p> <pre><code>a[0], b[0] a[1], b[1] a[2], b[2] a[0], b[0], c[0] a[1], b[1], c[0] a[2], b[2], c[0] a[1], b[1], c[1] a[2], b[2], c[2] a[0], b[0], c[3] a[1], b[1], c[3] a[2], b[2], c[3] ..... </code></pre> <p>There can be only one value at a time from each list.</p> <p>Imagine two or more lists Like a=[1,2,3] and b=[4,5,6] and c=[7,8,9] and I would like all possible pairs like (a[0], b[0]),(a[1], b[1]), (a[0], b[0], c[0])... </p>
0
2016-08-28T09:54:43Z
39,190,403
<p>As per your example, you seem to want only <code>abc</code>-type permutations. So you either: 1) build your "permutations" explicitly, or 2) build all permutations and filter out those you do not want.</p> <p><strong>Explicit construction</strong></p> <ol> <li>Build your <code>list_of_lists</code>, i.e. <code>[['a1', 'a2', 'a3'], ['b1', 'b2'], ['c1']]</code></li> <li>Build your permutations. Use <code>itertools.product</code>, see <a href="http://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists">All combinations of a list of lists</a></li> <li>From each of your permutations, you might want to create several, within a loop. E.g., from <code>('a1','b1','c1')</code> get <code>('a1','b1','c1')</code> and <code>('a1','b1')</code>. That is easy.</li> </ol> <p>You can fill in the gaps.</p> <p><strong>Build all and filter out</strong></p> <p>... Probably only useful if you need something (slightly) different from what I understood.</p>
1
2016-08-28T10:37:06Z
[ "python", "algorithm", "combinations", "permutation" ]
How can I do 'from foo import bar as b' with imp in Python2.7?
39,190,124
<p>I need to import a module without knowing it's location in advance; The user will specify the location as an argument to my script. </p> <p>I know I can use <code>imp</code> for imports, like </p> <pre><code>import imp foo = imp.load_source('foo', '/path/to/foo.py') </code></pre> <p>which is functionally equivalent to </p> <pre><code>import foo </code></pre> <p>if foo was found in PATH. </p> <p>How can I construct something similar to </p> <pre><code>from foo import bar as b </code></pre> <p>?</p>
0
2016-08-28T10:03:31Z
39,192,327
<p>As I commented, you can use normal attribute access to get the <code>bar</code> object from the module object returned from <code>imp.load_source</code>, even within the same expression:</p> <pre><code>b = imp.load_source('foo', '/path/to/foo.py').bar </code></pre> <p>This isn't quite the same as <code>from foo import bar as b</code>, since <code>load_source</code> always reads the source file and creates a new module object with new contents. An <code>import</code> statement will only load the module once, and use the cached version of it from <code>sys.modules</code> if you import it again.</p>
0
2016-08-28T14:30:18Z
[ "python", "python-2.7", "python-import" ]
django wsgi.py cannot recognize settings file
39,190,142
<p>A strange problem occured while trying to configure <code>apache2</code> to serve a Django project via <code>wsgi</code>.</p> <p>My project is a small to-do list implemented here. <a href="https://github.com/panospet/toDoList" rel="nofollow">https://github.com/panospet/toDoList</a></p> <p>When apache tries to run <code>wsgi.py</code>, returns this error:</p> <pre><code>Traceback (most recent call last): File "/var/www/toDoList/myToDoList/wsgi.py", line 19, in &lt;module&gt; application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named myToDoList.settings </code></pre> <p>My <code>wsgi.py</code> file is like:</p> <pre><code>import os import sys sys.path.append(' /var/www/toDoList') sys.path.append(' /var/www/toDoList/myToDoList') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myToDoList.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() </code></pre> <p>and also my <code>.conf</code> file inside <code>/etc/apache2/sites-enabled</code>:</p> <pre><code>&lt;VirtualHost *:80&gt; DocumentRoot "/var/www/toDoList" ServerName blahblah WSGIDaemonProcess todolist user=test group=test threads=5 WSGIScriptAlias / /var/www/toDoList/myToDoList/wsgi.py &lt;Location /todolist&gt; WSGIProcessGroup todolist &lt;/Location&gt; &lt;Directory /var/www/toDoList/toDoList&gt; Order allow,deny Allow from all &lt;/Directory&gt; Alias /static /var/www/toDoList/myToDoList/static/ &lt;Directory /var/www/toDoList/myToDoList/static&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre>
-1
2016-08-28T10:05:10Z
39,190,363
<p>remove that space in sys.path.append</p> <pre><code>sys.path.append('/var/www/toDoList') sys.path.append('/var/www/toDoList/myToDoList') </code></pre>
1
2016-08-28T10:31:47Z
[ "python", "django", "apache", "mod-wsgi", "wsgi" ]
django wsgi.py cannot recognize settings file
39,190,142
<p>A strange problem occured while trying to configure <code>apache2</code> to serve a Django project via <code>wsgi</code>.</p> <p>My project is a small to-do list implemented here. <a href="https://github.com/panospet/toDoList" rel="nofollow">https://github.com/panospet/toDoList</a></p> <p>When apache tries to run <code>wsgi.py</code>, returns this error:</p> <pre><code>Traceback (most recent call last): File "/var/www/toDoList/myToDoList/wsgi.py", line 19, in &lt;module&gt; application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named myToDoList.settings </code></pre> <p>My <code>wsgi.py</code> file is like:</p> <pre><code>import os import sys sys.path.append(' /var/www/toDoList') sys.path.append(' /var/www/toDoList/myToDoList') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myToDoList.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() </code></pre> <p>and also my <code>.conf</code> file inside <code>/etc/apache2/sites-enabled</code>:</p> <pre><code>&lt;VirtualHost *:80&gt; DocumentRoot "/var/www/toDoList" ServerName blahblah WSGIDaemonProcess todolist user=test group=test threads=5 WSGIScriptAlias / /var/www/toDoList/myToDoList/wsgi.py &lt;Location /todolist&gt; WSGIProcessGroup todolist &lt;/Location&gt; &lt;Directory /var/www/toDoList/toDoList&gt; Order allow,deny Allow from all &lt;/Directory&gt; Alias /static /var/www/toDoList/myToDoList/static/ &lt;Directory /var/www/toDoList/myToDoList/static&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre>
-1
2016-08-28T10:05:10Z
39,190,366
<p>Based on <a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/" rel="nofollow">Django documentation</a> You missed the <code>WSGIPythonPath</code>:</p> <pre><code>WSGIPythonPath /var/www/toDoList </code></pre> <p>This line ensures that your project package is available for import on the Python path; in other words, that import mysit works.</p>
0
2016-08-28T10:31:55Z
[ "python", "django", "apache", "mod-wsgi", "wsgi" ]
Under what condition does a Python subprocess get a SIGPIPE?
39,190,250
<p>I am reading the the Python documentation on the Popen class in the subprocess module section and I came across the following code:</p> <pre><code>p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] </code></pre> <p>The <a href="https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline" rel="nofollow">documentation</a> also states that </p> <blockquote> <p>"The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.</p> </blockquote> <p>Why must the p1.stdout be closed before we can receive a SIGPIPE and how does p1 knows that p2 exits before p1 if we already closed it? </p>
0
2016-08-28T10:18:25Z
39,190,346
<p><code>SIGPIPE</code> is a signal that would be sent if <code>dmesg</code> tried to write to a closed pipe. Here, <code>dmesg</code> ends up with <em>two</em> targets to write to, your Python process and the <code>grep</code> process.</p> <p>That's because <code>subprocess</code> clones file handles (using the <a href="https://docs.python.org/2/library/os.html#os.dup2" rel="nofollow"><code>os.dup2()</code> function</a>). Configuring <code>p2</code> to use <code>p1.stdout</code> triggers a <code>os.dup2()</code> call that asks the OS to duplicate the pipe filehandle; the duplicate is used to connect <code>dmesg</code> to <code>grep</code>.</p> <p>With two open file handles for <code>dmesg</code> stdout, <code>dmesg</code> is never given a <code>SIGPIPE</code> signal if only <em>one</em> of them closes early, so <code>grep</code> closing would never be detected. <code>dmesg</code> would needlessly continue to produce output.</p> <p>So by closing <code>p1.stdout</code> immediately, you ensure that the only remaining filehandle reading from <code>dmesg</code> stdout is the <code>grep</code> process, and if that process were to exit, <code>dmesg</code> receives a <code>SIGPIPE</code>.</p>
2
2016-08-28T10:29:41Z
[ "python", "pipe", "subprocess" ]
Development vs Release Python Code
39,190,274
<p>I am currently developing a Python application which I continually performance test, simply by recording the runtime of various parts.</p> <p>A lot of the code is related only to the testing environment and would not exist in the real world application, I have these separated into functions and at the moment I comment out these calls when testing. This requires me to remember which calls refer to test only components (they are quite interleaved so I cannot group the functionality). </p> <p>I was wondering if there was a better solution to this, the only idea I have had so far is creation of a 'mode' boolean and insertion of If statements, though this feels needlessly messy. I was hoping there might be some more standardised testing method that I am naive of.</p> <p>I am new to python so I may have overlooked some simple solutions. Thank you in advance</p>
-4
2016-08-28T10:20:13Z
39,190,392
<p>There are libraries for testing like those in the <a href="https://docs.python.org/3/library/development.html" rel="nofollow">development-section</a> of the standard library. If you did not use such tools yet, you should start to do so - they help a lot with testing. (especially <code>unittest</code>).</p> <p>Normally Python runs programs in debug mode with <a href="https://docs.python.org/3/library/constants.html#__debug__" rel="nofollow"><code>__debug__</code></a> set to <code>True</code> (see <a href="https://docs.python.org/3/reference/simple_stmts.html#assert" rel="nofollow">docs on <code>assert</code></a>) - you can switch off debug mode by setting the command-line switches <code>-O</code> or <code>-OO</code> for optimization (see <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-O" rel="nofollow">docs</a>).</p> <p>There is something about using specifically assertions in the <a href="https://wiki.python.org/moin/UsingAssertionsEffectively" rel="nofollow">Python Wiki</a></p>
0
2016-08-28T10:35:09Z
[ "python", "testing" ]
Development vs Release Python Code
39,190,274
<p>I am currently developing a Python application which I continually performance test, simply by recording the runtime of various parts.</p> <p>A lot of the code is related only to the testing environment and would not exist in the real world application, I have these separated into functions and at the moment I comment out these calls when testing. This requires me to remember which calls refer to test only components (they are quite interleaved so I cannot group the functionality). </p> <p>I was wondering if there was a better solution to this, the only idea I have had so far is creation of a 'mode' boolean and insertion of If statements, though this feels needlessly messy. I was hoping there might be some more standardised testing method that I am naive of.</p> <p>I am new to python so I may have overlooked some simple solutions. Thank you in advance</p>
-4
2016-08-28T10:20:13Z
39,190,406
<p>I'd say if you're commenting out several parts of your code when switching between debug&amp;release mode I think <strong>you're doing wrong</strong>. Take a look for example to the <a href="https://docs.python.org/2/library/logging.html" rel="nofollow">logging library</a>, as you can see, with that library you can specify the logging level you want to use only by changing a single parameter.</p> <p>Try to avoid commenting specific parts of your debug code by having one or more variables which controls the mode (debug, release, ...) your script will run. You could also use some <a href="https://docs.python.org/3/library/constants.html#__debug__" rel="nofollow">builtin ones</a> python already provides</p>
0
2016-08-28T10:37:44Z
[ "python", "testing" ]
Concatenating two string columns of numpy array into single column in python
39,190,302
<p>I have a numpy array as following :</p> <pre><code>2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 17:01:34 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 16:59:52 2016-07-02 10:40:00 2016-07-02 12:01:14 </code></pre> <p>this are two columns of array. date and time. but i want both into a single column concatenated by '\t'. both the values are in string format. </p> <p>I did it by a loop as follows, but that is a bad idea and taking much time. : </p> <pre><code>for D in Data: Data2 = np.append(Data2,np.array(D[0]+"\t"+D[1])) </code></pre> <p>Please suggest an efficient solution. </p>
0
2016-08-28T10:24:02Z
39,190,375
<p>Insert the tabs <code>\t</code> into your array using <code>numpy.insert</code> and then do a <code>numpy.reshape</code> from n by 3 to n*3 by 1</p>
1
2016-08-28T10:33:02Z
[ "python", "arrays", "numpy" ]
Concatenating two string columns of numpy array into single column in python
39,190,302
<p>I have a numpy array as following :</p> <pre><code>2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 17:01:34 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 16:59:52 2016-07-02 10:40:00 2016-07-02 12:01:14 </code></pre> <p>this are two columns of array. date and time. but i want both into a single column concatenated by '\t'. both the values are in string format. </p> <p>I did it by a loop as follows, but that is a bad idea and taking much time. : </p> <pre><code>for D in Data: Data2 = np.append(Data2,np.array(D[0]+"\t"+D[1])) </code></pre> <p>Please suggest an efficient solution. </p>
0
2016-08-28T10:24:02Z
39,190,441
<p>Neat, but not more efficient than simple loop (as Praveen pointed out in comment):</p> <pre><code>import numpy as np np.apply_along_axis(lambda d: d[0] + '\t' + d[1], 1, arr) </code></pre>
2
2016-08-28T10:43:31Z
[ "python", "arrays", "numpy" ]
Concatenating two string columns of numpy array into single column in python
39,190,302
<p>I have a numpy array as following :</p> <pre><code>2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 10:55:01 2016-07-02 17:01:34 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 17:01:34 2016-07-02 16:59:52 2016-07-02 16:59:52 2016-07-02 10:40:00 2016-07-02 12:01:14 </code></pre> <p>this are two columns of array. date and time. but i want both into a single column concatenated by '\t'. both the values are in string format. </p> <p>I did it by a loop as follows, but that is a bad idea and taking much time. : </p> <pre><code>for D in Data: Data2 = np.append(Data2,np.array(D[0]+"\t"+D[1])) </code></pre> <p>Please suggest an efficient solution. </p>
0
2016-08-28T10:24:02Z
39,191,110
<pre><code>import numpy as np a=[[1],[2],[3]] b=[[4],[5],[6]] np.concatenate((a,b),axis=1) </code></pre>
1
2016-08-28T12:08:38Z
[ "python", "arrays", "numpy" ]
Python json key error
39,190,351
<p>So I'm using the following simple snippet code to import a JSON object and then pull out specific fields into a list. Here it is:</p> <pre><code>#Set Observations URL request for all observations within the Osa Pennisula, Costa Rica query = urllib2.urlopen("http://api.inaturalist.org/v1/observations?nelat=8.60586&amp;nelng=-83.44410&amp;swlat=8.43066&amp;swlng=-83.74073&amp;per_page=1000&amp;order=desc&amp;order_by=created_at") obSet = json.load(query) #Find all common names for observations for item in obSet['results']: print item['taxon']['preferred_common_name'] </code></pre> <p>The URL is a call to the iNaturalist <code>node.js</code> service. When I make the call I get the following result:</p> <pre><code>Red Brocket Gumbo Limbo Northern Tamandua Colubrids Bats Skippers True Toads Crested Owl Tropical Screech-Owl White-nosed Coati Central American Squirrel Monkey Thread-legged Bugs Roadside Hawk Barn Owl Red Land Crab Crested Caracar --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-255-6e709d365b1b&gt; in &lt;module&gt;() 3 4 for item in obSet['results']: ----&gt; 5 print item['taxon']['preferred_common_name'] 6 7 KeyError: 'preferred_common_name' </code></pre> <p>So it's odd - I know that the response has 304 results, but the code seems to print a few out and then blow up. Why is this?! </p>
-1
2016-08-28T10:30:21Z
39,190,376
<p>Because not every item in <code>obSet['results']</code> has key <code>item['taxon']['preferred_common_name']</code>.</p> <p>You can counteract that by catching these <code>KeyError</code>s and printing the offensive keys. It also seems like some items have <code>None</code> as value for <code>'taxon'</code> key, so you may want to catch these as well:</p> <pre><code>for item in obSet['results']: try: print item['taxon']['preferred_common_name'] except (KeyError, TypeError): print item </code></pre>
2
2016-08-28T10:33:11Z
[ "python", "json" ]
How can I use Bokeh in an Azure ML notebook
39,190,415
<p>I can run the following code in a Jupyter notebook (Python 3.5) on my PC using Anaconda, and it works fine. But when I run the same code in an Azure ML notebook, I get the plot, but also the error message described below. Does anyone know how to use Bokeh in Azure ML notebooks ? Is there perhaps a way to import the seemingly missing module 'ipykernel'</p> <pre><code>from bokeh.plotting import figure, show, output_notebook from bokeh.sampledata.iris import flowers colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] p = figure(title = "Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.2, size=10) output_notebook() show(p) </code></pre> <p>produces the plot, but also the following errors</p> <pre><code>--------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-17-c50d1a94007e&gt; in &lt;module&gt;() 13 14 output_notebook() ---&gt; 15 show(p) /home/nbuser/env3/lib/python3.4/site-packages/bokeh/io.py in show(obj, browser, new) 299 300 ''' --&gt; 301 return _show_with_state(obj, _state, browser, new) 302 303 def _show_with_state(obj, state, browser, new): /home/nbuser/env3/lib/python3.4/site-packages/bokeh/io.py in _show_with_state(obj, state, browser, new) 307 308 if state.notebook: --&gt; 309 comms_handle = _show_notebook_with_state(obj, state) 310 311 elif state.server_enabled: /home/nbuser/env3/lib/python3.4/site-packages/bokeh/io.py in _show_notebook_with_state(obj, state) 329 comms_target = make_id() 330 publish_display_data({'text/html': notebook_div(obj, comms_target)}) --&gt; 331 handle = _CommsHandle(get_comms(comms_target), state.document, state.document.to_json()) 332 state.last_comms_handle = handle 333 return handle /home/nbuser/env3/lib/python3.4/site-packages/bokeh/util/notebook.py in get_comms(target_name) 109 110 ''' --&gt; 111 from ipykernel.comm import Comm 112 return Comm(target_name=target_name, data={}) 113 ImportError: No module named 'ipykernel' In [16]: </code></pre> <p>​</p>
0
2016-08-28T10:39:24Z
39,195,345
<p>There are two options I think. In a notebook, I think you can use <code>conda</code> to install new packages in your AzureML environment, by executing a cell with the following:</p> <pre><code>!conda install ipykernel --yes </code></pre> <p>Note the <code>!</code> at the beginning. In Jupyter notebooks that means to execute the command as a shell command. </p> <p>Althernatively, in the upcoming <code>0.12.2</code> release later this week <em>(today's date: 2016-08-28)</em> the "notebook comms" feature that uses <code>ipykernel</code> to be imported will no longer be "turned on" all the time, and will only be used when explicitly asked for. That should also resolve this problem.</p> <p>Until <code>0.12.2</code> is released, you can use these new features by installing a "dev build" or release candidate. The main docs site has simple instructions for <a href="http://bokeh.pydata.org/en/dev/docs/installation.html#developer-builds" rel="nofollow">installing developer builds</a>. (You can install similarly using <code>!conda</code> in a notebook, as above.)</p>
2
2016-08-28T20:10:45Z
[ "python", "azure", "jupyter-notebook", "bokeh", "azure-ml" ]
How can I use Bokeh in an Azure ML notebook
39,190,415
<p>I can run the following code in a Jupyter notebook (Python 3.5) on my PC using Anaconda, and it works fine. But when I run the same code in an Azure ML notebook, I get the plot, but also the error message described below. Does anyone know how to use Bokeh in Azure ML notebooks ? Is there perhaps a way to import the seemingly missing module 'ipykernel'</p> <pre><code>from bokeh.plotting import figure, show, output_notebook from bokeh.sampledata.iris import flowers colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] p = figure(title = "Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.2, size=10) output_notebook() show(p) </code></pre> <p>produces the plot, but also the following errors</p> <pre><code>--------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-17-c50d1a94007e&gt; in &lt;module&gt;() 13 14 output_notebook() ---&gt; 15 show(p) /home/nbuser/env3/lib/python3.4/site-packages/bokeh/io.py in show(obj, browser, new) 299 300 ''' --&gt; 301 return _show_with_state(obj, _state, browser, new) 302 303 def _show_with_state(obj, state, browser, new): /home/nbuser/env3/lib/python3.4/site-packages/bokeh/io.py in _show_with_state(obj, state, browser, new) 307 308 if state.notebook: --&gt; 309 comms_handle = _show_notebook_with_state(obj, state) 310 311 elif state.server_enabled: /home/nbuser/env3/lib/python3.4/site-packages/bokeh/io.py in _show_notebook_with_state(obj, state) 329 comms_target = make_id() 330 publish_display_data({'text/html': notebook_div(obj, comms_target)}) --&gt; 331 handle = _CommsHandle(get_comms(comms_target), state.document, state.document.to_json()) 332 state.last_comms_handle = handle 333 return handle /home/nbuser/env3/lib/python3.4/site-packages/bokeh/util/notebook.py in get_comms(target_name) 109 110 ''' --&gt; 111 from ipykernel.comm import Comm 112 return Comm(target_name=target_name, data={}) 113 ImportError: No module named 'ipykernel' In [16]: </code></pre> <p>​</p>
0
2016-08-28T10:39:24Z
39,328,659
<p>@MortenBunesGustavsen, As I known, there are two different versions of python for Azure ML notebook which include <code>python3.4</code> on the <code>env3</code> host and <code>python3.5</code> on the <code>anaconda3_410</code> host. You can directly access the url <code>http://notebooks.azure.com</code> to use the <code>Bokeh</code> without any errors on the <code>python3.5</code> environment with <code>ipykernel</code>, not access the jupyter (python3.4 without ipykernel) from Azure ML studio.</p> <p>Please check the runtime version via the code below first.</p> <pre><code>In [1]: import sys In [2]: sys.version Out[2]: '3.5.1 |Anaconda custom (64-bit)| (default, Jun 15 2016, 15:32:45) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]' </code></pre> <p>Hope it helps.</p>
1
2016-09-05T10:29:59Z
[ "python", "azure", "jupyter-notebook", "bokeh", "azure-ml" ]
how to add change language dropdown to Django(1.10) admin?
39,190,430
<p>I'm planning to add change language dropdown in my admin page. according to <a href="https://djangosnippets.org/snippets/751/" rel="nofollow">this code</a> and <a href="http://stackoverflow.com/questions/17978260/how-do-i-correctly-extend-the-django-admin-base-html-template">How to extend admin page</a>. <br/> I copy <code>base_site.html</code> and copy it to <code>myapp/templates/admin</code>, the i create a html file named <code>change_language.html</code> and write this code in it:</p> <pre><code>{% load i18n %} / {% trans 'Change language' %} &lt;form action="/i18n/setlang/" method="post" style="display: inline;"&gt; &lt;div style="display: inline;"&gt; &lt;select name="language" onchange="javascript:form.submit()"&gt; {% for lang in LANGUAGES %} &lt;option value="{{ lang.0 }}"{% ifequal LANGUAGE_CODE lang.0 %} selected="selected"{% endifequal %}&gt;{{ lang.1 }}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>I add <code>{% extends 'admin/base_site.html' %}</code> at the top of this file, noting happens.<br/> I add <code>{% extends 'admin/base.html' %}</code> , again noting happens.<br/> All hints and answers says that we should change something name <code>&lt;div id="user-tools"&gt;</code> at line 25 of <code>base.html</code>, But in Django 1.10 it goes to line 31 with a different staff. im kinnda lost because i read many different staff every where and non of them works for me. Dose any know where im doing wrong ? <br/> here is my middlewares :</p> <pre><code>MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] </code></pre> <p>And template settings :</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] </code></pre>
0
2016-08-28T10:40:43Z
39,191,836
<p>I guess you are mixing both answers that you've found on the internet. One of them copies and changes a couple of files from the admin template, effectively overriding them in your program's references. The second one extends admin's templates. You should completely implement just one of them.</p>
1
2016-08-28T13:36:31Z
[ "python", "django", "django-admin", "multilingual", "django-multilingual" ]
Show Django Model @property as a bool in model admin
39,190,445
<p>I have a model with a <code>property</code>, It returns boolean, I want to show it as icon in django model admin.</p> <h2>models.py</h2> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) @property def is_new_bar(self): return bar == 'NEW' </code></pre> <h2>admin.py</h2> <pre><code>class FooAdmin(admin.ModelAdmin): list_display = ('bar', 'is_new_bar') # is_new_bar is shown as True/False text, I want this as bool icon of django. </code></pre> <p><a href="http://i.stack.imgur.com/eoK8x.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/eoK8x.jpg" alt="Boolean Icons"></a></p>
0
2016-08-28T10:43:53Z
39,190,516
<p>Just add <code>is_new_bar.boolean = True</code> to your model. Also, remove the <code>property</code> decorator. Like this:</p> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) def is_new_bar(self): return bar == 'NEW' is_new_bar.boolean = True </code></pre>
0
2016-08-28T10:53:05Z
[ "python", "django", "admin" ]
Show Django Model @property as a bool in model admin
39,190,445
<p>I have a model with a <code>property</code>, It returns boolean, I want to show it as icon in django model admin.</p> <h2>models.py</h2> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) @property def is_new_bar(self): return bar == 'NEW' </code></pre> <h2>admin.py</h2> <pre><code>class FooAdmin(admin.ModelAdmin): list_display = ('bar', 'is_new_bar') # is_new_bar is shown as True/False text, I want this as bool icon of django. </code></pre> <p><a href="http://i.stack.imgur.com/eoK8x.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/eoK8x.jpg" alt="Boolean Icons"></a></p>
0
2016-08-28T10:43:53Z
39,190,652
<p>Try this <code>property</code> use.</p> <pre><code>def is_new_bar(self): return bar == 'NEW' is_new_bar.boolean = True is_new_bar = property(is_new_bar) </code></pre>
1
2016-08-28T11:10:40Z
[ "python", "django", "admin" ]
Show Django Model @property as a bool in model admin
39,190,445
<p>I have a model with a <code>property</code>, It returns boolean, I want to show it as icon in django model admin.</p> <h2>models.py</h2> <pre><code>class Foo(models.Model): bar = models.TextField("Title", null=True, blank=True) @property def is_new_bar(self): return bar == 'NEW' </code></pre> <h2>admin.py</h2> <pre><code>class FooAdmin(admin.ModelAdmin): list_display = ('bar', 'is_new_bar') # is_new_bar is shown as True/False text, I want this as bool icon of django. </code></pre> <p><a href="http://i.stack.imgur.com/eoK8x.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/eoK8x.jpg" alt="Boolean Icons"></a></p>
0
2016-08-28T10:43:53Z
39,190,681
<p>You can add method to your modeladmin that will return property value and set that it will return boolean:</p> <pre><code>class FooAdmin(admin.ModelAdmin): list_display = ('bar', 'get_is_new_bar') def get_is_new_bar(self, obj): return self.is_new_bar get_is_new_bar.boolean = True </code></pre>
2
2016-08-28T11:13:56Z
[ "python", "django", "admin" ]
Python Pandas subsetting based on Dates
39,190,520
<p>I got a dataframe (using pandas) which contains the following fields:</p> <ol> <li>Datesf-----------Price</li> <li>02/08/16 17:28--10</li> <li>02/08/16 17:29--20</li> <li>02/08/16 17:30--30</li> <li>03/08/16 09:00--40</li> <li>04/08/16 09:00--50</li> </ol> <p>I am trying to subset the data frame into new dataframes using "Datesf" as a filter. The subsetting should only use the Datesf.Date() part of variable "Datesf" and name the new dataframe "df" as df_date. for example> new subsetted Dataframe name> df_02_08_16<br> 1. Datesf------------Price<br> 2. 02/08/16 17:28--10 3. 02/08/16 17:29--20 4. 02/08/16 17:30--30</p> <p>I tried using the following code but obviously, I am missing out quite a few bits:</p> <pre><code>datelist= df["Datesf"].map(pd.Timestamp.date).unique() for d in datelist: print d df.loc[df['Datesf'] == '%s' % d] </code></pre> <p>My python skills are relatively basic at this stage. so forgive me if my query is not so challenging. Many thanks. regards, S</p>
0
2016-08-28T10:54:01Z
39,190,856
<p>This should do the work.</p> <pre><code>import pandas as pd df = pd.DataFrame([['02/08/16 17:28',1], ['02/08/16 17:28',10],['02/08/16 17:28',100],['03/08/16 17:28',101],['04/08/16 17:28',103]], columns=['Datesf', 'Price']) df.Datesf = pd.to_datetime(df.Datesf) unique_dates = df.Datesf.unique() data_frame_dict = {elem : pd.DataFrame for elem in unique_dates} for n, key in enumerate(data_frame_dict.keys()): print ' ==== dataframe %d ======' % n data_frame_dict[key] = df[:][df.Datesf == key] print data_frame_dict[key] data_frame_dict[key].to_csv('%s.csv'%str(key)) </code></pre>
1
2016-08-28T11:38:50Z
[ "python", "pandas", "subset" ]
Python, A class within a class, how to access variables from the upper class
39,190,547
<p>I have Qt <code>Gui</code> class that handles all the variables (<code>p1</code>, <code>p2</code>) adjustment with sliders and stuff. Inside this class, I have a OSC listener class that was supposed to listen to trigger signals and a variable <code>p3</code> from another device and use the parameters to trigger sound and graphic. But I have trouble accessing <code>p1</code>, <code>p2</code> in the listener class. Here is an example:</p> <pre><code>class Ptsgui(QtGui.QMainWindow): def __init__(self): super(Ptsgui, self).__init__() self.p1, self.p2, self.data = 0, 0, np.zeros(10) self.initUI() class OscListener(object): def __init__(self, data): self.listenerData = data self.receive_address = '127.0.0.1', 7000 def do_stuff_listener(self, addr, tags, stuff, source): print self.p1 print self.p2 self.p3 = stuff[0] trigger_sound_and_graphic(self.p1, self.p2, self.p3) def spawn(self): self.receiveServer = OSC.OSCServer(self.receive_address) self.receiveServer.addDefaultHandlers() self.receiveServer.addMsgHandler("/trigger", self.do_stuff_listener() self.emorating_oscServer = threading.Thread(target=self.receiveServer.serve_forever) self.emorating_oscServer.start() def initUI(): """ Some sliders setup for change the p1 &amp; p2 """ self.setGeometry(50, 50, 1050, 650) mainlayout = QtGui.QVBoxLayout() self.widget = QtGui.QWidget() self.widget.setLayout(mainlayout) self.listener = OscListener(data = self.data) self.show() </code></pre> <p>So here I want the <code>oscListener()</code> to be available to directly access <code>self.p1</code> and <code>self.p2</code>. And obviously I can't with this because the <code>self.p1</code>'s 'self' refers to <code>OscListener</code> but not <code>Ptsgui</code>. Also the <code>do_stuff_listener</code> is in a separate thread, is it still possible to access <code>self.p1</code> and <code>self.p2</code>? </p> <p>Ultimately, I am hoping to the GUI for user to control the parameters values. And each time a trigger signal is received via <code>OSC</code>, it will generated a new graph and sound. Please advice if there is a better way to do this. </p>
0
2016-08-28T10:57:51Z
39,190,588
<p>You could pass the<code>Ptsgui</code> to <code>OscListener</code> like this:</p> <pre><code>class Ptsgui(QtGui.QMainWindow): def __init__(self): super(Ptsgui, self).__init__() self.p1, self.p2, self.data = 0, 0, np.zeros(10) self.initUI() class OscListener(object): def __init__(self, cls, data): self.parent = cls self.listenerData = data self.receive_address = '127.0.0.1', 7000 def do_stuff_listener(self, addr, tags, stuff, source): print self.parent.p1 # Access it. print self.parent.p2 self.p3 = stuff[0] trigger_sound_and_graphic(self.p1, self.p2, self.p3) def spawn(self): self.receiveServer = OSC.OSCServer(self.receive_address) self.receiveServer.addDefaultHandlers() self.receiveServer.addMsgHandler("/trigger", self.do_stuff_listener() self.emorating_oscServer = threading.Thread(target=self.receiveServer.serve_forever) self.emorating_oscServer.start() def initUI(): """ Some sliders setup for change the p1 &amp; p2 """ self.setGeometry(50, 50, 1050, 650) mainlayout = QtGui.QVBoxLayout() self.widget = QtGui.QWidget() self.widget.setLayout(mainlayout) self.listener = OscListener(cls=self, data = self.data) # Pass it here self.show() </code></pre>
0
2016-08-28T11:02:39Z
[ "python", "class", "pyqt", "subclass", "osc" ]
Python, A class within a class, how to access variables from the upper class
39,190,547
<p>I have Qt <code>Gui</code> class that handles all the variables (<code>p1</code>, <code>p2</code>) adjustment with sliders and stuff. Inside this class, I have a OSC listener class that was supposed to listen to trigger signals and a variable <code>p3</code> from another device and use the parameters to trigger sound and graphic. But I have trouble accessing <code>p1</code>, <code>p2</code> in the listener class. Here is an example:</p> <pre><code>class Ptsgui(QtGui.QMainWindow): def __init__(self): super(Ptsgui, self).__init__() self.p1, self.p2, self.data = 0, 0, np.zeros(10) self.initUI() class OscListener(object): def __init__(self, data): self.listenerData = data self.receive_address = '127.0.0.1', 7000 def do_stuff_listener(self, addr, tags, stuff, source): print self.p1 print self.p2 self.p3 = stuff[0] trigger_sound_and_graphic(self.p1, self.p2, self.p3) def spawn(self): self.receiveServer = OSC.OSCServer(self.receive_address) self.receiveServer.addDefaultHandlers() self.receiveServer.addMsgHandler("/trigger", self.do_stuff_listener() self.emorating_oscServer = threading.Thread(target=self.receiveServer.serve_forever) self.emorating_oscServer.start() def initUI(): """ Some sliders setup for change the p1 &amp; p2 """ self.setGeometry(50, 50, 1050, 650) mainlayout = QtGui.QVBoxLayout() self.widget = QtGui.QWidget() self.widget.setLayout(mainlayout) self.listener = OscListener(data = self.data) self.show() </code></pre> <p>So here I want the <code>oscListener()</code> to be available to directly access <code>self.p1</code> and <code>self.p2</code>. And obviously I can't with this because the <code>self.p1</code>'s 'self' refers to <code>OscListener</code> but not <code>Ptsgui</code>. Also the <code>do_stuff_listener</code> is in a separate thread, is it still possible to access <code>self.p1</code> and <code>self.p2</code>? </p> <p>Ultimately, I am hoping to the GUI for user to control the parameters values. And each time a trigger signal is received via <code>OSC</code>, it will generated a new graph and sound. Please advice if there is a better way to do this. </p>
0
2016-08-28T10:57:51Z
39,190,683
<p>What you trying to achieve can be done like that:</p> <pre><code>class Ptsgui(QtGui.QMainWindow): def __init__(self): super(Ptsgui, self).__init__() self.p1, self.p2, self.data = 0, 0, np.zeros(10) self.initUI() def initUI(): """ Some sliders setup for change the p1 &amp; p2 """ self.setGeometry(50, 50, 1050, 650) mainlayout = QtGui.QVBoxLayout() self.widget = QtGui.QWidget() self.widget.setLayout(mainlayout) self.listener = OscListener(gui=self, data=self.data) self.show() class OscListener(object): def __init__(self, gui, data): self.gui = gui self.listenerData = data self.receive_address = '127.0.0.1', 7000 def do_stuff_listener(self, addr, tags, stuff, source): print self.gui.p1 print self.gui.p2 self.p3 = stuff[0] trigger_sound_and_graphic(self.gui.p1, self.gui.p2, self.gui.p3) def spawn(self): self.receiveServer = OSC.OSCServer(self.receive_address) self.receiveServer.addDefaultHandlers() self.receiveServer.addMsgHandler("/trigger", self.do_stuff_listener() self.emorating_oscServer = threading.Thread(target=self.receiveServer.serve_forever) self.emorating_oscServer.start() </code></pre> <p>See that the class nesting from your code sample is not needed.</p> <p>Also, it seems to me that what you are trying to achieve is not right. The code is extremely coupled. Consider decoupling <code>Ptsgui</code> and <code>OscListener</code>. Check <a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Observer.html" rel="nofollow">Observer pattern</a> for some inspiration.</p>
0
2016-08-28T11:14:35Z
[ "python", "class", "pyqt", "subclass", "osc" ]
Generate a two dimensional array of complex numbers
39,190,567
<p>I want to generate a two dimensional array of a given size containing complex numbers like in this example:</p> <pre><code>&gt;&gt;&gt; generate_array((2, 3)) array([[ 0.+0.j, 1.+0.j, 2.+0.j], [ 0.+1.j, 1.+1.j, 2.+1.j]]) </code></pre>
-3
2016-08-28T11:00:13Z
39,190,625
<p>Here is a way to achieve this<br> using <code>np.indices()</code> engaged with <code>np.vectorize()</code>:</p> <pre><code>def generate_array(dim): X, Y = np.indices(dim) return np.array(np.vectorize(complex)(X, Y)) ar = generate_array((2, 3)) print(ar) </code></pre> <p>Output:</p> <pre><code>[[ 0.+0.j 0.+1.j 0.+2.j] [ 1.+0.j 1.+1.j 1.+2.j]] </code></pre>
2
2016-08-28T11:07:53Z
[ "python", "numpy" ]
Generate a two dimensional array of complex numbers
39,190,567
<p>I want to generate a two dimensional array of a given size containing complex numbers like in this example:</p> <pre><code>&gt;&gt;&gt; generate_array((2, 3)) array([[ 0.+0.j, 1.+0.j, 2.+0.j], [ 0.+1.j, 1.+1.j, 2.+1.j]]) </code></pre>
-3
2016-08-28T11:00:13Z
39,190,682
<pre><code>def generate_array(m, n): return (np.arange(m) * 1j)[:, None] + np.arange(n) generate_array(2, 3) Out: array([[ 0.+0.j, 1.+0.j, 2.+0.j], [ 0.+1.j, 1.+1.j, 2.+1.j]]) </code></pre>
2
2016-08-28T11:14:18Z
[ "python", "numpy" ]
django request.session throws Atrribute error
39,190,599
<p>I get this error <em>'WSGIRequest' object has no attribute 'session'</em> on the manage.py runserver. When I try to retrieve the session dict from request.session.</p> <p>Searches on this item say I need to put 'django.contrib.sessions.middleware.SessionMiddleware' on top of the MIDDLEWARE settings. However this does not seem to work.</p> <p>My settings.py:</p> <pre><code>import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '@ta=3ful!*bzj^o@3+avt#qrm9@uz%6ur_d@ihs#j--5us*r_(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'FEM', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'laizen.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', #'django.core.context_processors.csrf', ], }, }, ] WSGI_APPLICATION = 'laizen.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), os.path.join(BASE_DIR, 'FEM', 'static') ) #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' </code></pre> <p>my views.py function:</p> <pre><code>def new_framework(request): print(request.session) return render(request, 'FEM/new_framework.html', {'bool_view_el': 'false'}) </code></pre> <p>Django error:</p> <pre><code>AttributeError at /new_framework/ 'WSGIRequest' object has no attribute 'session' Request Method: GET Request URL: http://127.0.0.1:8000/new_framework/ Django Version: 1.9.6 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'session' Exception Location: C:\Users\vik\Dropbox\Code\Web_Development\FEM_web_test\FEM\views.py in new_framework, line 23 Python Executable: C:\Anaconda3\python.exe Python Version: 3.5.2 Python Path: ['C:\\Users\\vik\\Dropbox\\Code\\Web_Development\\FEM_web_test', 'C:\\Anaconda3\\python35.zip', 'C:\\Anaconda3\\DLLs', 'C:\\Anaconda3\\lib', 'C:\\Anaconda3', 'C:\\Anaconda3\\lib\\site-packages', 'C:\\Anaconda3\\lib\\site-packages\\Sphinx-1.3.5-py3.5.egg', 'C:\\Anaconda3\\lib\\site-packages\\cryptography-1.0.2-py3.5-win-amd64.egg', 'C:\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda3\\lib\\site-packages\\Pythonwin', 'C:\\Anaconda3\\lib\\site-packages\\setuptools-20.7.0-py3.5.egg'] Server time: Sun, 28 Aug 2016 12:53:18 +0200 </code></pre>
0
2016-08-28T11:04:14Z
39,190,674
<p>You are using Django version 1.9; the MIDDLEWARE setting was only introduced in version 1.10. For earlier versions like yours you should be using MIDDLEWARE_CLASSES - or upgrade to 1.10.</p>
0
2016-08-28T11:13:02Z
[ "python", "django", "session" ]
Pass username and password to Flask Oauth2 Server (password grant type)
39,190,622
<p>I'm implementing Flask REST API with Flask-Oauthlib and wondering is it ok to pass username and password in URL parameters? For example:</p> <pre><code>GET http://127.0.0.1:5000/api/token?client_id=CLIENT_ID&amp;grant_type=password&amp;username=myusername&amp;password=hopeudontseemypass </code></pre> <p>In my development environment all the requests are showing in logs as plain text like this:</p> <pre><code>127.0.0.1 - "GET /api/token?client_id=CLIENT_ID&amp;grant_type=password&amp;username=myusername&amp;password=hopeudontseemypass HTTP/1.1" 200 - </code></pre> <p>Is there any way to pass base64 encoded username/pass in request headers? All the password grant type examples are using username and password in URL parameters, so don't know is this a really problem if server will use SSL.</p>
0
2016-08-28T11:06:49Z
39,190,696
<p>The OAuth protocol spec says that the parameters must be POST-ed to the token endpoint. By accepting them as query parameters the Authorization Server violates the spec. Better use POST to avoid the credentials ending up in log files.</p>
2
2016-08-28T11:15:45Z
[ "python", "authentication", "flask", "oauth-2.0", "flask-oauthlib" ]
Dates fill in for date range and fillna
39,190,701
<p>I am querying my database to show records from the past week. I am then aggregating the data and transposing it in python and pandas into a DataFrame. In this table I am attempting to show what occurred on each day in the past 7 week, however, on some days no events occur. In these cases, the date is missing altogether. I am looking for an approach to append the dates that are not present (but are part of the date range specified in the query) so that I can then fillna with any value I wish for the other missing columns.</p> <p>In some trials I have the data set into a pandas Dataframe where the dates are the index and in others the dates are a column. I am preferably looking to have the dates as the top index - so group by name, stack purchase and send_back and dates are the 'columns'.</p> <p>Here is an example of how the dataframe looks now and what I am looking for:</p> <p>Dates set in query for - 01.08.2016 - 08.08.2016. The dataframe looks liks so:</p> <pre><code> | dates | name | purchase | send_back 0 01.08.2016 Michael 120 0 1 02.08.2016 Sarah 100 40 2 04.08.2016 Sarah 55 0 3 05.08.2016 Michael 80 20 4 07.08.2016 Sarah 130 0 </code></pre> <p>After:</p> <pre><code> | dates | name | purchase | send_back 0 01.08.2016 Michael 120 0 1 02.08.2016 Sarah 100 40 2 03.08.2016 - 0 0 3 04.08.2016 Sarah 55 0 4 05.08.2016 Michael 80 20 5 06.08.2016 - 0 0 6 07.08.2016 Sarah 130 0 7 08.08.2016 Sarah 0 35 8 08.08.2016 Michael 20 0 </code></pre> <p>Printing the following:</p> <pre><code> df.index </code></pre> <p>gives:</p> <pre><code> 'Index([ u'dates',u'name',u'purchase',u'send_back'], dtype='object') RangeIndex(start=0, stop=1, step=1)' </code></pre> <p>I appreciate any guidance.</p>
0
2016-08-28T11:16:04Z
39,190,940
<p>assuming you have the following DF:</p> <pre><code>In [93]: df Out[93]: name purchase send_back dates 2016-08-01 Michael 120 0 2016-08-02 Sarah 100 40 2016-08-04 Sarah 55 0 2016-08-05 Michael 80 20 2016-08-07 Sarah 130 0 </code></pre> <p>you can resample and replace:</p> <pre><code>In [94]: df.resample('D').first().replace({'name':{np.nan:'-'}}).fillna(0) Out[94]: name purchase send_back dates 2016-08-01 Michael 120.0 0.0 2016-08-02 Sarah 100.0 40.0 2016-08-03 - 0.0 0.0 2016-08-04 Sarah 55.0 0.0 2016-08-05 Michael 80.0 20.0 2016-08-06 - 0.0 0.0 2016-08-07 Sarah 130.0 0.0 </code></pre>
1
2016-08-28T11:48:31Z
[ "python", "pandas" ]
Dates fill in for date range and fillna
39,190,701
<p>I am querying my database to show records from the past week. I am then aggregating the data and transposing it in python and pandas into a DataFrame. In this table I am attempting to show what occurred on each day in the past 7 week, however, on some days no events occur. In these cases, the date is missing altogether. I am looking for an approach to append the dates that are not present (but are part of the date range specified in the query) so that I can then fillna with any value I wish for the other missing columns.</p> <p>In some trials I have the data set into a pandas Dataframe where the dates are the index and in others the dates are a column. I am preferably looking to have the dates as the top index - so group by name, stack purchase and send_back and dates are the 'columns'.</p> <p>Here is an example of how the dataframe looks now and what I am looking for:</p> <p>Dates set in query for - 01.08.2016 - 08.08.2016. The dataframe looks liks so:</p> <pre><code> | dates | name | purchase | send_back 0 01.08.2016 Michael 120 0 1 02.08.2016 Sarah 100 40 2 04.08.2016 Sarah 55 0 3 05.08.2016 Michael 80 20 4 07.08.2016 Sarah 130 0 </code></pre> <p>After:</p> <pre><code> | dates | name | purchase | send_back 0 01.08.2016 Michael 120 0 1 02.08.2016 Sarah 100 40 2 03.08.2016 - 0 0 3 04.08.2016 Sarah 55 0 4 05.08.2016 Michael 80 20 5 06.08.2016 - 0 0 6 07.08.2016 Sarah 130 0 7 08.08.2016 Sarah 0 35 8 08.08.2016 Michael 20 0 </code></pre> <p>Printing the following:</p> <pre><code> df.index </code></pre> <p>gives:</p> <pre><code> 'Index([ u'dates',u'name',u'purchase',u'send_back'], dtype='object') RangeIndex(start=0, stop=1, step=1)' </code></pre> <p>I appreciate any guidance.</p>
0
2016-08-28T11:16:04Z
39,192,735
<p>Your index is of <code>object</code> type and you must convert it to <code>datetime</code> format.</p> <pre><code># Converting the object date to datetime.date df['dates'] = df['dates'].apply(lambda x: datetime.strptime(x, "%d.%m.%Y")) # Setting the index column df.set_index(['dates'], inplace=True) # Choosing a date range extending from first date to the last date with a set frequency new_index = pd.date_range(start=df.index[0], end=df.index[-1], freq='D') new_index.name = df.index.name # Setting the new index df = df.reindex(new_index) # Making the required modifications df.ix[:,0], df.ix[:,1:] = df.ix[:,0].fillna('-'), df.ix[:,1:].fillna(0) print (df) name purchase send_back dates 2016-08-01 Michael 120.0 0.0 2016-08-02 Sarah 100.0 40.0 2016-08-03 - 0.0 0.0 2016-08-04 Sarah 55.0 0.0 2016-08-05 Michael 80.0 20.0 2016-08-06 - 0.0 0.0 2016-08-07 Sarah 130.0 0.0 </code></pre> <hr> <p>Let's suppose you have data for a single day (<em>as mentioned in the comments section</em>) and you would like to fill the other days of the week with null values:</p> <p><strong>Data Setup:</strong></p> <pre><code>df = pd.DataFrame({'dates':['01.08.2016'], 'name':['Michael'], 'purchase':[120], 'send_back':[0]}) print (df) dates name purchase send_back 0 01.08.2016 Michael 120 0 </code></pre> <p><strong>Operations:</strong></p> <pre><code>df['dates'] = df['dates'].apply(lambda x: datetime.strptime(x, "%d.%m.%Y")) df.set_index(['dates'], inplace=True) # Setting periods as 7 to account for the end of the week new_index = pd.date_range(start=df.index[0], periods=7, freq='D') new_index.name = df.index.name # Setting the new index df = df.reindex(new_index) print (df) name purchase send_back dates 2016-08-01 Michael 120.0 0.0 2016-08-02 NaN NaN NaN 2016-08-03 NaN NaN NaN 2016-08-04 NaN NaN NaN 2016-08-05 NaN NaN NaN 2016-08-06 NaN NaN NaN 2016-08-07 NaN NaN NaN </code></pre> <p>Incase you want to fill the null values with 0's, you could do:</p> <pre><code>df.fillna(0, inplace=True) print (df) name purchase send_back dates 2016-08-01 Michael 120.0 0.0 2016-08-02 0 0.0 0.0 2016-08-03 0 0.0 0.0 2016-08-04 0 0.0 0.0 2016-08-05 0 0.0 0.0 2016-08-06 0 0.0 0.0 2016-08-07 0 0.0 0.0 </code></pre>
1
2016-08-28T15:15:24Z
[ "python", "pandas" ]
Python - Intra-package importing when package modules are sometimes used as standalone?
39,190,714
<p>Sorry if this has already been answered using terminology I don't know to search for.</p> <p>I have one project:</p> <pre><code>project1/ class1.py class2.py </code></pre> <p>Where <code>class2</code> imports some things from <code>class1</code>, but each has its own <code>if __name__ == '__main__'</code> that uses their respective classes I run frequently. But then, I have a second project which creates a subclass of each of the classes from <code>project1</code>. So I would like <code>project1</code> to be a package, so that I can import it into <code>project2</code> nicely:</p> <pre><code>project2/ project1/ __init__.py class1.py class2.py subclass1.py subclass2.py </code></pre> <p>However, I'm having trouble with the importing with this. If I make <code>project1</code> a package then inside <code>class2.py</code> I would want to import <code>class1.py</code> code using <code>from project1.class1 import class1</code>. This makes <code>project2</code> code run correctly. But now when I'm trying to use <code>project1</code> not as a package, but just running code from directly within that directory, the <code>project1</code> code fails (since it doesn't know what <code>project1</code> is). If I set it up for <code>project1</code> to work directly within that directory (i.e. the import in <code>class2</code> is <code>from class1 import Class1</code>), then this import fails when trying to use <code>project1</code> as a package from <code>project2</code>.</p> <p>Is there a way to have it both ways (use <code>project1</code> both as a package and not as a package)? If there is a way, is it a discouraged way and I should be restructuring my code anyway? Other suggestions on how I should be handling this? Thanks!</p> <p><strong>EDIT</strong></p> <p>Just to clarify, the problem arrises because <code>subclass2</code> imports <code>class2</code> which in turn imports <code>class1</code>. Depending on which way <code>class2</code> imports <code>class1</code> the import will fail from <code>project2</code> or from <code>project1</code> because one sees <code>project1</code> as a package while the other sees it as the working directory.</p> <p><strong>EDIT 2</strong></p> <p>I'm using Python 3.5. Apparently this works in Python 2, but not in my current version of python.</p>
0
2016-08-28T11:18:03Z
39,190,943
<p>You could run <code>class2.py</code> from inside the <code>project2</code> folder, i.e. with the current working directory set to the <code>project2</code> folder:</p> <pre><code>user@host:.../project2$ python project1/class2.py </code></pre> <p>On windows that would look like this:</p> <pre><code>C:\...project2&gt; python project1/class2.py </code></pre> <p>Alternatively you could modify the python path inside of <code>class2.py</code>:</p> <pre><code>import sys sys.path.append(".../project2") from project1.class1 import class1 </code></pre> <p>Or modify the <code>PYTHONPATH</code> environment variable similarly.</p> <p>To be able to extend your project and import for example something in <code>subclass1.py</code> from <code>subclass2.py</code> you should consider starting the import paths always with <code>project2</code>, for example in <code>class2.py</code>:</p> <pre><code>from project2.project1.class1 import class1 </code></pre> <p>Ofcourse you would need to adjust the methods I just showed to match the new path.</p>
0
2016-08-28T11:48:48Z
[ "python", "python-3.x", "package", "python-import" ]
Python - Intra-package importing when package modules are sometimes used as standalone?
39,190,714
<p>Sorry if this has already been answered using terminology I don't know to search for.</p> <p>I have one project:</p> <pre><code>project1/ class1.py class2.py </code></pre> <p>Where <code>class2</code> imports some things from <code>class1</code>, but each has its own <code>if __name__ == '__main__'</code> that uses their respective classes I run frequently. But then, I have a second project which creates a subclass of each of the classes from <code>project1</code>. So I would like <code>project1</code> to be a package, so that I can import it into <code>project2</code> nicely:</p> <pre><code>project2/ project1/ __init__.py class1.py class2.py subclass1.py subclass2.py </code></pre> <p>However, I'm having trouble with the importing with this. If I make <code>project1</code> a package then inside <code>class2.py</code> I would want to import <code>class1.py</code> code using <code>from project1.class1 import class1</code>. This makes <code>project2</code> code run correctly. But now when I'm trying to use <code>project1</code> not as a package, but just running code from directly within that directory, the <code>project1</code> code fails (since it doesn't know what <code>project1</code> is). If I set it up for <code>project1</code> to work directly within that directory (i.e. the import in <code>class2</code> is <code>from class1 import Class1</code>), then this import fails when trying to use <code>project1</code> as a package from <code>project2</code>.</p> <p>Is there a way to have it both ways (use <code>project1</code> both as a package and not as a package)? If there is a way, is it a discouraged way and I should be restructuring my code anyway? Other suggestions on how I should be handling this? Thanks!</p> <p><strong>EDIT</strong></p> <p>Just to clarify, the problem arrises because <code>subclass2</code> imports <code>class2</code> which in turn imports <code>class1</code>. Depending on which way <code>class2</code> imports <code>class1</code> the import will fail from <code>project2</code> or from <code>project1</code> because one sees <code>project1</code> as a package while the other sees it as the working directory.</p> <p><strong>EDIT 2</strong></p> <p>I'm using Python 3.5. Apparently this works in Python 2, but not in my current version of python.</p>
0
2016-08-28T11:18:03Z
39,191,012
<p>EDIT 2: Added code to class2.py to attach the parent directory to the PYTHONPATH to comply with how Python3 module imports work.</p> <pre><code>import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) </code></pre> <p>Removed relative import of Class1.</p> <p>Folder structure:</p> <pre><code>project2 - class3.py - project1 - __init__.py - class1.py - class2.py </code></pre> <p><em>project2/project1/class1.py</em></p> <pre><code>class Class1(object): def __init__(self): super(Class1, self).__init__() self.name = "DAVE!" def printname(self): print(self.name) def run(): thingamy = Class1() thingamy.printname() if __name__ == "__main__": run() </code></pre> <p><em>project2/project1/class2.py</em></p> <pre><code>import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) from class1 import Class1 class Class2(Class1): def childMethod(self): print('Calling child method') def run(): thingamy = Class2() thingamy.printname() thingamy.childMethod() if __name__ == "__main__": run() </code></pre> <p><em>project2/class3.py</em></p> <pre><code>from project1.class2 import Class2 from project1.class1 import Class1 class Class3(Class2): def anotherChildMethod(self): print('Calling another child method') def run(): thingamy = Class3() thingamy.printname() thingamy.anotherChildMethod() if __name__ == "__main__": run() </code></pre> <p>With this setup each of class1, 2 and 3 can be run as standalone scripts.</p>
1
2016-08-28T11:56:01Z
[ "python", "python-3.x", "package", "python-import" ]
Python 3.5.2 Non-Ascii Character Output
39,190,727
<p>I'm running Python 3.5.2 and am trying to do some basic stuff with unicode and UTF-8. I'm currently just trying to output non-ASCII characters and am unable to do so. For example, this:</p> <pre><code>ddd = '\u0144' print(ddd) </code></pre> <p>gives me a Unicode encode error, telling me that the character maps to undefined. From what I understand of unicode in Python 3.5.2, mapping should happen automatically. I tried putting <code># -*- coding: utf-8 -*-</code> before the code and various combinations of <code>.decode</code> and <code>.encode</code> as well, but to no avail.</p>
1
2016-08-28T11:20:40Z
39,190,905
<p>PM 2Ring, typing in <code>chcp 65001</code> in command prompt did the trick. Thanks!</p>
1
2016-08-28T11:45:03Z
[ "python", "unicode", "utf-8", "character-encoding", "non-ascii-characters" ]
SQLAlchemy / MySQL Deadlocks on serialized access
39,190,752
<p>I have a big problem with a deadlock in an InnoDB table used with sqlalchemy. </p> <blockquote> <p>sqlalchemy.exc.InternalError: (mysql.connector.errors.InternalError) 1213 (40001): Deadlock found when trying to get lock; try restarting transaction.</p> </blockquote> <p>I have already serialized the access, but still get a deadlock error. </p> <p>This code is executed on the first call in every function. Every thread and process should wait here, till it gets the lock. It's simplified, as selectors are removed. </p> <pre><code> # The work with the index -1 always exists. f = s.query(WorkerInProgress).with_for_update().filter( WorkerInProgress.offset == -1).first() </code></pre> <p>I have reduced my code to a minimal state. I am currently running only concurrent calls on the method next_slice. Session handling, rollback and deadloc handling are handled outside.</p> <p>I get deadlocks even all access is serialized. I did tried to increment a retry counter in the offset == -1 entity as well.</p> <pre><code>def next_slice(self, s, processgroup_id, itemcount): f = s.query(WorkerInProgress).with_for_update().filter( WorkerInProgress.offset == -1).first() #Take first matching object if available / Maybe some workers failed item = s.query(WorkerInProgress).with_for_update().filter( WorkerInProgress.processgroup_id != processgroup_id, WorkerInProgress.processgroup_id != 'finished', WorkerInProgress.processgroup_id != 'finished!locked', WorkerInProgress.offset != -1 ).order_by(WorkerInProgress.offset.asc()).limit(1).first() # ***** # Some code is missing here. as it's not executed in my testcase # Fetch the latest item and add a new one item = s.query(WorkerInProgress).with_for_update().order_by( WorkerInProgress.offset.desc()).limit(1).first() new = WorkerInProgress() new.offset = item.offset + item.count new.count = itemcount new.maxtries = 3 new.processgroup_id = processgroup_id s.add(new) s.commit() return new.offset, new.count </code></pre> <p>I don't understand why the deadlocks are occurring. </p> <p>I have reduced deadlock by fetching all items in one query, but still get deadlocks. Perhaps someone can help me.</p>
0
2016-08-28T11:24:33Z
39,231,620
<p>Finally I solved my problem. It's all in the documentation, but I have to understand it first. </p> <blockquote> <p>Always be prepared to re-issue a transaction if it fails due to deadlock. Deadlocks are not dangerous. Just try again.</p> <p>Source: <a href="http://dev.mysql.com/doc/refman/5.7/en/innodb-deadlocks-handling.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/innodb-deadlocks-handling.html</a></p> </blockquote> <p>I have solved my problem by changing the architecture of this part. I still get a lot of deadlocks, but they appear almost in the short running methods. I have splitted my worker table to a locking and an non locking part. The actions on the locking part are now very short and no data is handling during the get_slice, finish_slice and fail_slice operations.</p> <p>The transaction part with data handling are now in a non locking part and without concurrent access to table rows. The results are stored in finish_slice and fail_slice to the locking table. </p> <p>Finally I have found a good description on stackoverflow too. After identifying the right search terms. <a href="http://stackoverflow.com/a/2596101/5532934">http://stackoverflow.com/a/2596101/5532934</a></p>
0
2016-08-30T15:30:37Z
[ "python", "mysql", "sqlalchemy", "deadlock" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1: return None else: return list(y[0]) </code></pre> <p>Which works perfectly up until ~2000, since I'm storing far too much in memory. What can I do to make it work efficiently for large numbers (say, 50000 or 100000). I tried to make it end after finding one case, but my algorithm is still far too inefficient if the number is large.</p> <p>Any tips?</p>
0
2016-08-28T11:32:02Z
39,190,836
<p>IIRC, it's far easier to iteratively check "Does it have a square root? Does it have a cube root? Does it have a fourth root? ..." You will very quickly get to the point where putative roots have to be between <code>1</code> and <code>2</code>, at which point you can stop.</p>
5
2016-08-28T11:35:44Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1: return None else: return list(y[0]) </code></pre> <p>Which works perfectly up until ~2000, since I'm storing far too much in memory. What can I do to make it work efficiently for large numbers (say, 50000 or 100000). I tried to make it end after finding one case, but my algorithm is still far too inefficient if the number is large.</p> <p>Any tips?</p>
0
2016-08-28T11:32:02Z
39,191,055
<p>Try this Newton's method:</p> <pre><code>def NthRoot(k, num): i, j = num, num+1 while i &lt; j: j = i t = (k-1) * j + num // pow(j, k-1) i = t // k return j print(NthRoot(3,125)) </code></pre> <p><a href="https://en.wikipedia.org/wiki/Newton&#39;s_method" rel="nofollow">https://en.wikipedia.org/wiki/Newton's_method</a></p>
0
2016-08-28T12:01:09Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1: return None else: return list(y[0]) </code></pre> <p>Which works perfectly up until ~2000, since I'm storing far too much in memory. What can I do to make it work efficiently for large numbers (say, 50000 or 100000). I tried to make it end after finding one case, but my algorithm is still far too inefficient if the number is large.</p> <p>Any tips?</p>
0
2016-08-28T11:32:02Z
39,191,074
<p>a relevant improvement would be:</p> <pre><code>import math def isPP(n): # first have a look at the length of n in binary representation ln = int(math.log(n)/math.log(2)) + 1 y = [] for i in range(n+1): if (i &lt;= 1): continue # calculate max power li = int(math.log(i)/math.log(2)) mxi = ln / li + 1 for it in range(mxi): if (it &lt;= 1): continue if i ** it == n: y.append((i,it)) # break if you only need 1 if len(y) &lt;1: return None else: return list(y[0]) </code></pre>
0
2016-08-28T12:03:46Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1: return None else: return list(y[0]) </code></pre> <p>Which works perfectly up until ~2000, since I'm storing far too much in memory. What can I do to make it work efficiently for large numbers (say, 50000 or 100000). I tried to make it end after finding one case, but my algorithm is still far too inefficient if the number is large.</p> <p>Any tips?</p>
0
2016-08-28T11:32:02Z
39,191,163
<p>A number <em>n</em> is a perfect power if there exists a <em>b</em> and <em>e</em> for which <em>b</em>^<em>e</em> = <em>n</em>. For instance 216 = 6^3 = 2^3 * 3^3 is a perfect power, but 72 = 2^3 * 3^2 is not.</p> <p>The trick to determining if a number is a perfect power is to know that, if the number is a perfect power, then the exponent <em>e</em> must be less than log2 <em>n</em>, because if <em>e</em> is greater then 2^<em>e</em> will be greater than <em>n</em>. Further, it is only necessary to test prime <em>e</em>s, because if a number is a perfect power to a composite exponent it will also be a perfect power to the prime factors of the composite component; for instance, 2^15 = 32768 = 32^3 = 8^5 is a perfect cube root and also a perfect fifth root.</p> <p>The function <code>isPerfectPower</code> shown below tests each prime less than log2 <em>n</em> by first computing the integer root using Newton's method, then powering the result to check if it is equal to <em>n</em>. Auxiliary function <code>primes</code> compute a list of prime numbers by the Sieve of Eratosthenes, <code>iroot</code> computes the integer <em>k</em>th-root by Newton's method, and <code>ilog</code> computes the integer logarithm to base <em>b</em> by binary search.</p> <pre><code>def primes(n): # sieve of eratosthenes i, p, ps, m = 0, 3, [2], n // 2 sieve = [True] * m while p &lt;= n: if sieve[i]: ps.append(p) for j in range((p*p-3)/2, m, p): sieve[j] = False i, p = i+1, p+2 return ps def iroot(k, n): # assume n &gt; 0 u, s, k1 = n, n+1, k-1 while u &lt; s: s = u u = (k1 * u + n // u ** k1) // k return s def ilog(b, n): # max e where b**e &lt;= n lo, blo, hi, bhi = 0, 1, 1, b while bhi &lt; n: lo, blo, hi, bhi = hi, bhi, hi+hi, bhi*bhi while 1 &lt; (hi - lo): mid = (lo + hi) // 2 bmid = blo * pow(b, (mid - lo)) if n &lt; bmid: hi, bhi = mid, bmid elif bmid &lt; n: lo, blo = mid, bmid else: return mid if bhi == n: return hi return lo def isPerfectPower(n): # x if n == x ** y, or False for p in primes(ilog(2,n)): x = iroot(p, n) if pow(x, p) == n: return x return False </code></pre> <p>There is further discussion of the perfect power predicate at <a href="https://programmingpraxis.com/2012/03/13/perfect-power-predicate/" rel="nofollow">my blog</a>.</p>
0
2016-08-28T12:14:49Z
[ "python", "algorithm", "python-3.x" ]
How to make perfect power algorithm more efficient?
39,190,815
<p>I have the following code:</p> <pre><code>def isPP(n): pos = [int(i) for i in range(n+1)] pos = pos[2:] ##to ignore the trivial n** 1 == n case y = [] for i in pos: for it in pos: if i** it == n: y.append((i,it)) #return list((i,it)) #break if len(y) &lt;1: return None else: return list(y[0]) </code></pre> <p>Which works perfectly up until ~2000, since I'm storing far too much in memory. What can I do to make it work efficiently for large numbers (say, 50000 or 100000). I tried to make it end after finding one case, but my algorithm is still far too inefficient if the number is large.</p> <p>Any tips?</p>
0
2016-08-28T11:32:02Z
39,197,064
<p>I think a better way would be implementing this "hack":</p> <pre><code>import math def isPP(n): range = math.log(n)/math.log(2) range = (int)(range) result = [] for i in xrange(n): if(i&lt;=1): continue exponent = (int)(math.log(n)/math.log(i)) for j in [exponent-1, exponent, exponent+1]: if i ** j == n: result.append([i,j]) return result print isPP(10000) </code></pre> <p>Result:</p> <pre><code>[[10,4],[100,2]] </code></pre> <p>The hack uses the fact that:</p> <pre><code>if log(a)/log(b) = c, then power(b,c) = a </code></pre> <p>Since this calculation can be a bit off in floating points giving really approximate results, exponent is checked to the accuracy of <code>+/- 1</code>.</p> <p>You can make necessary adjustments for handling corner cases like <code>n=1, etc.</code></p>
0
2016-08-29T00:32:53Z
[ "python", "algorithm", "python-3.x" ]
Use __init__ constructor as factory method
39,191,017
<p>I have a function which takes a factory method as an argument. Invoking the factory method will create an object. Now I thought that I could directly specify the constructor of the desired object/class <code>Fruit.__init__</code> as the factory method. But that does not work, since the <code>self</code> argument does "not exist" then. So I have to introduce an additional method <code>fruit_factory</code> which builds the object:</p> <pre><code>def fruit_factory(owner): return Fruit(owner) class Fruit: def __init__(self, owner): print('Making a fruit for ' + owner) def make_snack_for_jim(snack_factory): snack_factory('Jim') make_snack_for_jim(fruit_factory) # Works, but needs additional function make_snack_for_jim(Fruit.__init__) # Does not work (no 'self' argument) </code></pre> <p>Is there a way to directly specify the constructor instead of needing to create an additional method?</p>
1
2016-08-28T11:56:29Z
39,191,060
<p>Just pass in the class itself:</p> <pre><code>&gt;&gt;&gt; make_snack_for_jim(Fruit) Making a fruit for Jim </code></pre> <p>This sets your <code>snack_factory</code> to <code>Fruit</code> inside of the <code>make_snack_for_jim</code>, which you then call with <code>snack_factory('Jim')</code></p>
4
2016-08-28T12:01:52Z
[ "python", "factory-pattern" ]
How to speed up a recursive algorithm
39,191,056
<p>I'm trying to solve the Hackerrank challenge <a href="https://www.hackerrank.com/challenges/game-of-stones-1">Game of Stones</a>, a (shortened) problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/Vqgl1.png"><img src="http://i.stack.imgur.com/Vqgl1.png" alt="enter image description here"></a></p> <p>I came up with the following solution:</p> <pre><code># The lines below are for the Hackerrank submission # T = int(raw_input().strip()) # ns = [int(raw_input().strip()) for _ in range(T)] T = 8 ns = [1, 2, 3, 4, 5, 6, 7, 10] legal_moves = [2, 3, 5] def which_player_wins(n): if n &lt;= 1: return "Second" # First player loses elif n in legal_moves: return "First" # First player wins immediately else: next_ns = map(lambda x: n - x, legal_moves) next_ns = filter(lambda x: x &gt;= 0, next_ns) next_n_rewards = map(which_player_wins, next_ns) # Reward for opponent if any(map(lambda x: x=="Second", next_n_rewards)): # Opponent enters a losing position return "First" else: return "Second" for n in ns: print which_player_wins(n) </code></pre> <p>The algorithm is essentially the minimax algorithm as it looks one move ahead and then recursively calls the same function. The problem is that in Hackerrank, it is terminating due to timeout:</p> <p><a href="http://i.stack.imgur.com/7fynV.png"><img src="http://i.stack.imgur.com/7fynV.png" alt="enter image description here"></a></p> <p>Indeed, I've noticed that evaluating <code>which_player_wins(40)</code> already takes ~2 seconds. Any ideas for a faster solution which would not time out?</p>
6
2016-08-28T12:01:10Z
39,191,123
<p>It seems from the problem description that you are able to keep the intermediate and final results from each calculation to use in later calculations. If that is so, a recursive algorithm is not optimal. Instead, use a dynamic programming style.</p> <p>In other words, keep a global array that stores the results from previous determinations of wins and losses. When you determine for a new value of <code>n</code>, rather than recursing all the way to the end, use the previous determinations.</p> <p>For example, when you get to <code>n=10</code>, you see that the first player removing 3 stones leaves 7 stones, which you have already seen as a win for the second player. Therefore, 10 stones is a win for the first player.</p> <p>I believe that your recursive algorithm would calculate all over again the result for <code>n=7</code> rather than using the previous work.</p>
6
2016-08-28T12:10:16Z
[ "python", "algorithm" ]
How to speed up a recursive algorithm
39,191,056
<p>I'm trying to solve the Hackerrank challenge <a href="https://www.hackerrank.com/challenges/game-of-stones-1">Game of Stones</a>, a (shortened) problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/Vqgl1.png"><img src="http://i.stack.imgur.com/Vqgl1.png" alt="enter image description here"></a></p> <p>I came up with the following solution:</p> <pre><code># The lines below are for the Hackerrank submission # T = int(raw_input().strip()) # ns = [int(raw_input().strip()) for _ in range(T)] T = 8 ns = [1, 2, 3, 4, 5, 6, 7, 10] legal_moves = [2, 3, 5] def which_player_wins(n): if n &lt;= 1: return "Second" # First player loses elif n in legal_moves: return "First" # First player wins immediately else: next_ns = map(lambda x: n - x, legal_moves) next_ns = filter(lambda x: x &gt;= 0, next_ns) next_n_rewards = map(which_player_wins, next_ns) # Reward for opponent if any(map(lambda x: x=="Second", next_n_rewards)): # Opponent enters a losing position return "First" else: return "Second" for n in ns: print which_player_wins(n) </code></pre> <p>The algorithm is essentially the minimax algorithm as it looks one move ahead and then recursively calls the same function. The problem is that in Hackerrank, it is terminating due to timeout:</p> <p><a href="http://i.stack.imgur.com/7fynV.png"><img src="http://i.stack.imgur.com/7fynV.png" alt="enter image description here"></a></p> <p>Indeed, I've noticed that evaluating <code>which_player_wins(40)</code> already takes ~2 seconds. Any ideas for a faster solution which would not time out?</p>
6
2016-08-28T12:01:10Z
39,191,528
<p>Following <a href="http://stackoverflow.com/users/6246044/rory-daulton">Rory Daulton</a>'s advice to use dynamic programming, I rewrote the <code>which_player_wins</code> method as follows:</p> <pre><code># The lines below are for the Hackerrank submission # T = int(raw_input().strip()) # ns = [int(raw_input().strip()) for _ in range(T)] T = 8 ns = [1, 2, 3, 4, 5, 6, 7, 10] def which_player_wins(n): moves = [2, 3, 5] table = {j:"" for j in range(n+1)} table[0] = "Second" # If it is the first player's turn an no stones are on the table, the second player wins table[1] = "Second" # No legal moves are available with only one stone left on the board for i in range(2,n+1): next_n = [i - move for move in moves if i - move &gt;= 0] next_n_results = [table[k] for k in next_n] if any([result == "Second" for result in next_n_results]): table[i] = "First" else: table[i] = "Second" return table[n] for n in ns: print which_player_wins(n) </code></pre> <p>This led to successfully solving the challenge (see below).</p> <p><a href="http://i.stack.imgur.com/2Jwo2.png" rel="nofollow"><img src="http://i.stack.imgur.com/2Jwo2.png" alt="enter image description here"></a></p>
0
2016-08-28T12:59:10Z
[ "python", "algorithm" ]
How to speed up a recursive algorithm
39,191,056
<p>I'm trying to solve the Hackerrank challenge <a href="https://www.hackerrank.com/challenges/game-of-stones-1">Game of Stones</a>, a (shortened) problem statement of which is copied below.</p> <p><a href="http://i.stack.imgur.com/Vqgl1.png"><img src="http://i.stack.imgur.com/Vqgl1.png" alt="enter image description here"></a></p> <p>I came up with the following solution:</p> <pre><code># The lines below are for the Hackerrank submission # T = int(raw_input().strip()) # ns = [int(raw_input().strip()) for _ in range(T)] T = 8 ns = [1, 2, 3, 4, 5, 6, 7, 10] legal_moves = [2, 3, 5] def which_player_wins(n): if n &lt;= 1: return "Second" # First player loses elif n in legal_moves: return "First" # First player wins immediately else: next_ns = map(lambda x: n - x, legal_moves) next_ns = filter(lambda x: x &gt;= 0, next_ns) next_n_rewards = map(which_player_wins, next_ns) # Reward for opponent if any(map(lambda x: x=="Second", next_n_rewards)): # Opponent enters a losing position return "First" else: return "Second" for n in ns: print which_player_wins(n) </code></pre> <p>The algorithm is essentially the minimax algorithm as it looks one move ahead and then recursively calls the same function. The problem is that in Hackerrank, it is terminating due to timeout:</p> <p><a href="http://i.stack.imgur.com/7fynV.png"><img src="http://i.stack.imgur.com/7fynV.png" alt="enter image description here"></a></p> <p>Indeed, I've noticed that evaluating <code>which_player_wins(40)</code> already takes ~2 seconds. Any ideas for a faster solution which would not time out?</p>
6
2016-08-28T12:01:10Z
39,193,031
<p>Your solution would work (though very slowly) if you had infinite recursion levels available. But since you're not re-using already calculated results you are very quickly hitting Python's recursion limit. One good solution, as suggested above, is to re-write the code using a non-recursive algorithm. </p> <p>Alternatively, you could keep the code you have, but get it to re-use any result that you've already seen before. This is called memoization, and an easy way to implement that is to add a memoization decorator to the part of the code that computes the next move. Here's a way to use memoization to speed up your recursive algorithm, which I think is what you've specifically asked for:</p> <ol> <li><p>Convert all of the code after the first <code>else</code> into a function, <code>next_move(n)</code> that returns either 'First' or 'Second'.</p></li> <li><p>Add a <code>memoize(f)</code> function which will take <code>next_move(n)</code> and avoid the recursion call if the result for n has already been calculated. </p></li> <li><p>Add the decorator line <code>@memoize</code> immediately before the <code>next_move</code> definition.</p></li> </ol> <p>Resulting code:</p> <pre><code>T = 8 ns = [1, 2, 3, 4, 5, 6, 7, 10] legal_moves = [2, 3, 5] def memoize(f): memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper @memoize def next_move(n): next_ns = map(lambda x: n - x, legal_moves) next_ns = filter(lambda x: x &gt;= 0, next_ns) next_n_rewards = map(which_player_wins, next_ns) # Reward for opponent if any(map(lambda x: x == "Second", next_n_rewards)): # Opponent enters a losing position return "First" else: return "Second" def which_player_wins(n): if n &lt;= 1: return "Second" # First player loses elif n in legal_moves: return "First" # First player wins immediately else: return next_move(n) for n in ns: print which_player_wins(n) </code></pre> <p>This hugely speeds up the calculation as well as reducing the levels of recursion required. On my computer n=100 is solved in 0.8 ms.</p>
2
2016-08-28T15:47:54Z
[ "python", "algorithm" ]
pandas merge columns in same dataframe
39,191,066
<p>I have dataframe with 4 columns. </p> <pre><code> Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5 Item11 Value11 Item12 Value12 6 Item13 Value13 Item14 Value14 </code></pre> <p>Is there a way for me to combine <code>Column1</code> and <code>Column3</code> together? and with <code>Column2</code> and <code>Column4</code>? To get the below</p> <pre><code> Column1 Column2 0 Item1 Value1 1 Item2 Value2 2 Item3 Value3 3 Item4 Value4 4 Item5 Value5 5 Item6 Value6 6 Item7 Value7 7 ... </code></pre> <p>I've tried playing with <code>append</code>, <code>concat</code> and <code>split</code> but cant seem to work it out.. </p>
0
2016-08-28T12:02:33Z
39,191,125
<p>Okay, maybe this might help:</p> <pre><code>In [571]: df Out[571]: Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5 Item11 Value11 Item12 Value12 6 Item13 Value13 Item14 Value14 In [572]: pd.DataFrame({'Column1': pd.concat([df.Column1, df.Column3]), 'Column2': pd.concat([df.Column2, df.Column4])}).sort_index() Out[572]: Column1 Column2 0 Item1 Value1 0 Item2 Value2 1 Item3 Value3 1 Item4 Value4 2 Item5 Value5 2 Item6 Value6 3 Item7 Value7 3 Item8 Value8 4 Item9 Value9 4 Item10 Value10 5 Item11 Value11 5 Item12 Value12 6 Item13 Value13 6 Item14 Value14 </code></pre> <p>You can also reset the index:</p> <pre><code>In [574]: pd.DataFrame({'Column1': pd.concat([df.Column1, df.Column3]), 'Column2': pd.concat([df.Column2, df.Column4])}).sort_index().reset_index(drop=True) Out[574]: Column1 Column2 0 Item1 Value1 1 Item2 Value2 2 Item3 Value3 3 Item4 Value4 4 Item5 Value5 5 Item6 Value6 6 Item7 Value7 7 Item8 Value8 8 Item9 Value9 9 Item10 Value10 10 Item11 Value11 11 Item12 Value12 12 Item13 Value13 13 Item14 Value14 </code></pre>
2
2016-08-28T12:10:26Z
[ "python", "pandas" ]
pandas merge columns in same dataframe
39,191,066
<p>I have dataframe with 4 columns. </p> <pre><code> Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5 Item11 Value11 Item12 Value12 6 Item13 Value13 Item14 Value14 </code></pre> <p>Is there a way for me to combine <code>Column1</code> and <code>Column3</code> together? and with <code>Column2</code> and <code>Column4</code>? To get the below</p> <pre><code> Column1 Column2 0 Item1 Value1 1 Item2 Value2 2 Item3 Value3 3 Item4 Value4 4 Item5 Value5 5 Item6 Value6 6 Item7 Value7 7 ... </code></pre> <p>I've tried playing with <code>append</code>, <code>concat</code> and <code>split</code> but cant seem to work it out.. </p>
0
2016-08-28T12:02:33Z
39,192,670
<pre><code>df.columns = pd.MultiIndex.from_product( [['One', 'Two'], ['Column1', 'Column2']]) df.stack(0).reset_index(drop=True) </code></pre> <p><a href="http://i.stack.imgur.com/Eb8GR.png" rel="nofollow"><img src="http://i.stack.imgur.com/Eb8GR.png" alt="enter image description here"></a></p>
1
2016-08-28T15:09:35Z
[ "python", "pandas" ]
pandas merge columns in same dataframe
39,191,066
<p>I have dataframe with 4 columns. </p> <pre><code> Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5 Item11 Value11 Item12 Value12 6 Item13 Value13 Item14 Value14 </code></pre> <p>Is there a way for me to combine <code>Column1</code> and <code>Column3</code> together? and with <code>Column2</code> and <code>Column4</code>? To get the below</p> <pre><code> Column1 Column2 0 Item1 Value1 1 Item2 Value2 2 Item3 Value3 3 Item4 Value4 4 Item5 Value5 5 Item6 Value6 6 Item7 Value7 7 ... </code></pre> <p>I've tried playing with <code>append</code>, <code>concat</code> and <code>split</code> but cant seem to work it out.. </p>
0
2016-08-28T12:02:33Z
39,194,119
<p>You can also treat the two distinct groupings as separate DataFrames by using the subcolumns and renaming the Column3 and Column4 on the fly:</p> <pre><code>&gt;&gt;&gt; df Column1 Column2 Column3 Column4 0 Item1 Value1 Item2 Value2 1 Item3 Value3 Item4 Value4 2 Item5 Value5 Item6 Value6 3 Item7 Value7 Item8 Value8 4 Item9 Value9 Item10 Value10 5 Item11 Value11 Item12 Value12 6 Item13 Value13 Item14 Value14 df[['Column1','Column2']].append(df[['Column3','Column4']].rename(columns={'Column3':'Column1','Column4':'Column2'})).sort_index().reset_index(drop=True) Column1 Column2 0 Item1 Value1 1 Item2 Value2 2 Item3 Value3 3 Item4 Value4 4 Item5 Value5 5 Item6 Value6 6 Item7 Value7 7 Item8 Value8 8 Item9 Value9 9 Item10 Value10 10 Item11 Value11 11 Item12 Value12 12 Item13 Value13 13 Item14 Value14 </code></pre>
1
2016-08-28T17:44:26Z
[ "python", "pandas" ]
Complicated refer to another table
39,191,088
<p>I have dataframe shown in below: column name 'Types'shows each types dified </p> <p>I would like to add another column named 'number' defined as below.</p> <pre><code>df=pd.DataFrame({'Sex':['M','F','F','M'],'Age':[30,31,33,32],'Types':['A','C','B','D']}) Out[8]: Age Sex Types 0 30 M A 1 31 F C 2 33 F B 3 32 M D </code></pre> <p>and I have another male table below; each column represents Types!</p> <p>(It was difficult to create table for me, Are there another easy way to create?)</p> <pre><code>table_M = pd.DataFrame(np.arange(20).reshape(4,5),index=[30,31,32,33],columns=["A","B","C","D","E"]) table_M.index.name="Age(male)" A B C D E Age(male) 30 0 1 2 3 4 31 5 6 7 8 9 32 10 11 12 13 14 33 15 16 17 18 19 </code></pre> <p>and I have female table below; </p> <pre><code>table_F = pd.DataFrame(np.arange(20,40).reshape(4,5),index=[30,31,32,33],columns=["A","B","C","D","E"]) table_F.index.name="Age(female)" A B C D E Age(female) 30 20 21 22 23 24 31 25 26 27 28 29 32 30 31 32 33 34 33 35 36 37 38 39 </code></pre> <p>so I would like to add 'number' column as shown below;</p> <pre><code> Age Sex Types number 0 30 M A 0 1 31 F C 27 2 33 F B 36 3 32 M D 13 </code></pre> <p>this number column refer to female and male table. for each age , Type, and Sex. It was too complicated for me. Can I ask how to add 'number' column?</p>
2
2016-08-28T12:05:43Z
39,191,227
<p>I suggest reshaping your male and female tables:</p> <pre><code>males = (table_M.stack().to_frame('number').assign(Sex='M').reset_index() .rename(columns={'Age(male)': 'Age', 'level_1': 'Types'})) females = (table_F.stack().to_frame('number').assign(Sex='F').reset_index() .rename(columns={'Age(female)': 'Age', 'level_1': 'Types'})) reshaped = pd.concat([males, females], ignore_index=True) </code></pre> <p>Then merge:</p> <pre><code>df.merge(reshaped) Out: Age Sex Types number 0 30 M A 0 1 31 F C 27 2 33 F B 36 3 32 M D 13 </code></pre> <hr> <p>What this does is it stacks the columns of Male and Female tables, and assigns an indicator column showing Sex ('M' and 'F'). <code>females.head()</code> looks like this:</p> <pre><code>females.head() Out: Age Types number Sex 0 30 A 20 F 1 30 B 21 F 2 30 C 22 F 3 30 D 23 F 4 30 E 24 F </code></pre> <p>and <code>males.head()</code>:</p> <pre><code>males.head() Out: Age Types number Sex 0 30 A 0 M 1 30 B 1 M 2 30 C 2 M 3 30 D 3 M 4 30 E 4 M </code></pre> <p>With pd.concat these two are combined into a single DataFrame and merge by default works on the common columns so it looks for the matches in 'Age', 'Sex', 'Types' columns and merge two DataFrames based on that.</p> <hr> <p>One other possibility is to use df.lookup:</p> <pre><code>df.loc[df['Sex']=='M', 'number'] = table_M.lookup(*df.loc[df['Sex']=='M', ['Age', 'Types']].values.T) df.loc[df['Sex']=='F', 'number'] = table_F.lookup(*df.loc[df['Sex']=='F', ['Age', 'Types']].values.T) df Out: Age Sex Types number 0 30 M A 0.0 1 31 F C 27.0 2 33 F B 36.0 3 32 M D 13.0 </code></pre> <p>This looks up the males in <code>table_M</code>, and females in <code>table_F</code>.</p>
5
2016-08-28T12:22:44Z
[ "python", "pandas", "dataframe" ]
Complicated refer to another table
39,191,088
<p>I have dataframe shown in below: column name 'Types'shows each types dified </p> <p>I would like to add another column named 'number' defined as below.</p> <pre><code>df=pd.DataFrame({'Sex':['M','F','F','M'],'Age':[30,31,33,32],'Types':['A','C','B','D']}) Out[8]: Age Sex Types 0 30 M A 1 31 F C 2 33 F B 3 32 M D </code></pre> <p>and I have another male table below; each column represents Types!</p> <p>(It was difficult to create table for me, Are there another easy way to create?)</p> <pre><code>table_M = pd.DataFrame(np.arange(20).reshape(4,5),index=[30,31,32,33],columns=["A","B","C","D","E"]) table_M.index.name="Age(male)" A B C D E Age(male) 30 0 1 2 3 4 31 5 6 7 8 9 32 10 11 12 13 14 33 15 16 17 18 19 </code></pre> <p>and I have female table below; </p> <pre><code>table_F = pd.DataFrame(np.arange(20,40).reshape(4,5),index=[30,31,32,33],columns=["A","B","C","D","E"]) table_F.index.name="Age(female)" A B C D E Age(female) 30 20 21 22 23 24 31 25 26 27 28 29 32 30 31 32 33 34 33 35 36 37 38 39 </code></pre> <p>so I would like to add 'number' column as shown below;</p> <pre><code> Age Sex Types number 0 30 M A 0 1 31 F C 27 2 33 F B 36 3 32 M D 13 </code></pre> <p>this number column refer to female and male table. for each age , Type, and Sex. It was too complicated for me. Can I ask how to add 'number' column?</p>
2
2016-08-28T12:05:43Z
39,191,401
<p>Another way to do this:</p> <pre><code>In [60]: df['numbers'] = df.apply(lambda x: table_F.loc[[x.Age]][x.Types].iloc[0] if x.Sex == 'F' else table_M.loc[[x.Age]][x.Types].iloc[0], axis = 1) In [60]: df Out[60]: Age Sex Types numbers 0 30 M A 0 1 31 F C 27 2 33 F B 36 3 32 M D 13 </code></pre>
1
2016-08-28T12:44:09Z
[ "python", "pandas", "dataframe" ]
Complicated refer to another table
39,191,088
<p>I have dataframe shown in below: column name 'Types'shows each types dified </p> <p>I would like to add another column named 'number' defined as below.</p> <pre><code>df=pd.DataFrame({'Sex':['M','F','F','M'],'Age':[30,31,33,32],'Types':['A','C','B','D']}) Out[8]: Age Sex Types 0 30 M A 1 31 F C 2 33 F B 3 32 M D </code></pre> <p>and I have another male table below; each column represents Types!</p> <p>(It was difficult to create table for me, Are there another easy way to create?)</p> <pre><code>table_M = pd.DataFrame(np.arange(20).reshape(4,5),index=[30,31,32,33],columns=["A","B","C","D","E"]) table_M.index.name="Age(male)" A B C D E Age(male) 30 0 1 2 3 4 31 5 6 7 8 9 32 10 11 12 13 14 33 15 16 17 18 19 </code></pre> <p>and I have female table below; </p> <pre><code>table_F = pd.DataFrame(np.arange(20,40).reshape(4,5),index=[30,31,32,33],columns=["A","B","C","D","E"]) table_F.index.name="Age(female)" A B C D E Age(female) 30 20 21 22 23 24 31 25 26 27 28 29 32 30 31 32 33 34 33 35 36 37 38 39 </code></pre> <p>so I would like to add 'number' column as shown below;</p> <pre><code> Age Sex Types number 0 30 M A 0 1 31 F C 27 2 33 F B 36 3 32 M D 13 </code></pre> <p>this number column refer to female and male table. for each age , Type, and Sex. It was too complicated for me. Can I ask how to add 'number' column?</p>
2
2016-08-28T12:05:43Z
39,192,535
<p>It's easier if you two tables are combined such that you can access the <code>'Sex'</code> via an <code>apply</code>.</p> <pre><code>table = pd.concat([table_F, table_M], axis=1, keys=['F', 'M']) accessor = lambda row: table.loc[row.Age, (row.Sex, row.Types)] df['number'] = df.apply(accessor, axis=1) df </code></pre> <p><a href="http://i.stack.imgur.com/I6Ku9.png" rel="nofollow"><img src="http://i.stack.imgur.com/I6Ku9.png" alt="enter image description here"></a></p>
4
2016-08-28T14:54:41Z
[ "python", "pandas", "dataframe" ]
How to create Panda Dataframe from csv that is compressed in tar.gz?
39,191,111
<p>How can I create the pandas DataFrame from csv file that's compressed in tar.gz? I found this code which does that but with zip file. What should I change in the following code to make it work with tar.gz without downloading the tar.gz and csv file. </p> <pre><code>import pandas, requests, zipfile, StringIO r =requests.get('http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip') z = zipfile.ZipFile(StringIO.StringIO(r.content)) df=pandas.read_csv(z.open('sample_CSV.csv')) </code></pre> <p>My file is <a href="https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz" rel="nofollow">https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz</a> </p>
0
2016-08-28T12:08:47Z
39,191,292
<p>Try simply supply your <code>.tar.gz</code> file as the file name<br> to <code>read_csv</code> and it will automatically decompress and open it, <br> since this is the default behavior for <code>gz</code> files.</p> <p>Make sure the extension is in lower case.</p>
0
2016-08-28T12:30:29Z
[ "python", "csv", "pandas", "gzip", "tar" ]
How to create Panda Dataframe from csv that is compressed in tar.gz?
39,191,111
<p>How can I create the pandas DataFrame from csv file that's compressed in tar.gz? I found this code which does that but with zip file. What should I change in the following code to make it work with tar.gz without downloading the tar.gz and csv file. </p> <pre><code>import pandas, requests, zipfile, StringIO r =requests.get('http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip') z = zipfile.ZipFile(StringIO.StringIO(r.content)) df=pandas.read_csv(z.open('sample_CSV.csv')) </code></pre> <p>My file is <a href="https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz" rel="nofollow">https://ghtstorage.blob.core.windows.net/downloads/mysql-2016-06-16.tar.gz</a> </p>
0
2016-08-28T12:08:47Z
39,191,488
<p>Can you try below for extracting tar.gz as below :</p> <pre><code>import tarfile tar = tarfile.open(fname, "r:gz") tar.extractall() tar.close() </code></pre>
1
2016-08-28T12:55:11Z
[ "python", "csv", "pandas", "gzip", "tar" ]
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "story" does not exist
39,191,127
<p>So this is my code below. I'm trying to create a database, with one story table. The input comes from the html input part</p> <pre><code>from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy from flask import request, redirect, url_for app = Flask(__name__) password = input("Your database password: ") app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://adambodnar:{}@localhost/user_stories'.format(password) db = SQLAlchemy(app) class Story(db.Model): id = db.Column(db.Integer, primary_key=True) story_title = db.Column(db.String(80), unique=True) user_story = db.Column(db.Text) acceptance_criteria = db.Column(db.Text) business_value = db.Column(db.Integer) estimation = db.Column(db.Integer) status = db.Column(db.String(30)) def __init__(self, story_title, user_story, acceptance_criteria, business_value, estimation, status): self.story_title = story_title self.user_story = user_story self.acceptance_criteria = acceptance_criteria self.business_value = business_value self.estimation = estimation self.status = status @app.route('/') def index(): return render_template('form.html') @app.route('/story', methods=['POST']) def story_post(): new_story = Story(request.form['story_title'],request.form['user_story'], request.form['acceptance_criteria'], request.form['business_value'], request.form['estimation'], request.form['status']) db.session.add(new_story) db.session.commit() return redirect(url_for('index')) if __name__ == '__main__': app.run(host='0.0.0.0', port=8000) </code></pre> <p>when I try to run this, I get the following error:</p> <pre><code>sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "story" does not exist LINE 1: INSERT INTO story (story_title, user_story, acceptance_crite... ^ [SQL: 'INSERT INTO story (story_title, user_story, acceptance_criteria, business_value, estimation, status) VALUES (%(story_title)s, %(user_story)s, %(acceptance_criteria)s, %(business_value)s, %(estimation)s, %(status)s) RETURNING story.id'] [parameters: {'acceptance_criteria': 'asdasd', 'estimation': '1', 'user_story': 'asd', 'status': 'Planning', 'story_title': 'asd', 'business_value': '100'}] </code></pre> <p>The story table is not even created, I checked it through pgAdmin. I've tried a lot of things, some questions suggested to drop the table, but it's not created</p>
-1
2016-08-28T12:10:44Z
39,191,197
<p>Have you followed the <a href="http://flask-sqlalchemy.pocoo.org/2.1/quickstart/" rel="nofollow">quickstart guide</a> for Flask and sqlalchemy? Anyway, on the guide you will notice that it says to do this:</p> <blockquote> <p>To create the initial database, just import the db object from an interactive Python shell and run the SQLAlchemy.create_all() method to create the tables and database:</p> <pre><code>&gt;&gt;&gt; from yourapplication import db &gt;&gt;&gt; db.create_all() </code></pre> </blockquote> <p>In the code you included with your question the table creation code seems to be missing, which explains the table not being created.</p> <p>You can consider including <code>db.create_all()</code> with your application (put it right after <code>db = SqlAlchemy(app)</code>) - if this wrapper functions like the standard sqlalchemy version it should only create new tables and not blow up if tables already exist.</p>
0
2016-08-28T12:19:07Z
[ "python", "flask", "flask-sqlalchemy" ]
Django Query - How to use the objects.filter results
39,191,168
<p>If I use the following code it works perfectly:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] for x in campaignnoquery: test2 = x.campaignno </code></pre> <p>However, when I try:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] test1 = campaignnoquery.campaignno </code></pre> <p>I get the following error:</p> <pre><code> test1 = campaignnoquery.campaignno AttributeError: 'QuerySet' object has no attribute 'campaignno' </code></pre> <p>I am sure it is something basic and I could just crack on with the one that worked but I am just intrigued on whats happening.</p> <p>Many thanks in advance, Alan.</p>
-1
2016-08-28T12:15:38Z
39,191,222
<p><code>campaignnoquery</code> is, as the error says, a <code>QuerySet</code> object (in this case it holds <code>UserSelection</code> instances). </p> <p>Your error is treating it as an instance of a single <code>UserSelection</code> object.</p> <p>Are you sure this <code>filter</code> will always return a single object? if so, you can use <code>get</code> instead.</p> <p>If not, what are you expecting <code>campaignnoquery.campaignno</code> to return? (considering <code>campaignnoquery</code> is a <strong>group</strong> of <code>UserSelection</code> objects).</p>
1
2016-08-28T12:21:47Z
[ "python", "mysql", "django" ]
Django Query - How to use the objects.filter results
39,191,168
<p>If I use the following code it works perfectly:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] for x in campaignnoquery: test2 = x.campaignno </code></pre> <p>However, when I try:</p> <pre><code>campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] test1 = campaignnoquery.campaignno </code></pre> <p>I get the following error:</p> <pre><code> test1 = campaignnoquery.campaignno AttributeError: 'QuerySet' object has no attribute 'campaignno' </code></pre> <p>I am sure it is something basic and I could just crack on with the one that worked but I am just intrigued on whats happening.</p> <p>Many thanks in advance, Alan.</p>
-1
2016-08-28T12:15:38Z
39,191,224
<p>You are referencing the wrong object! </p> <p>When looping through campaignnoquery, <strong><em>x</em></strong> becomes campaignnoquery[0], campaignnoquery[1], etc... </p> <p>Try referencing it like this:</p> <pre><code>test1 = campaignnoquery[0].campaignno </code></pre>
1
2016-08-28T12:21:55Z
[ "python", "mysql", "django" ]
Sending nested json data with Python requests and in x-www-form-urlencoded
39,191,187
<p>I cannot figure out how to do this. Basically one particular API is asking for </p> <p><code>'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'</code></p> <p>yet they want the form data to be like this:</p> <pre><code>stockLevels=[ { "SKU": "sample string 1", "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a", "Level": 3 }, { "SKU": "sample string 1", "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a", "Level": 3 } ] </code></pre> <p>What I'm doing is this:</p> <pre><code>def change_stock_quantity(self, SKU, qty): # Note that this will change quantity of just one item # instead of two like in the example above payload = { 'stockLevels':[{ 'SKU': SKU, 'LocationId': self.ebay1_location_id, 'Level': qty, }] } r = self.session.post(self.session_server + '//api/Stock/SetStockLevel', data=payload) print r.request.body # stockLevels=SKU&amp;stockLevels=LocationId&amp;stockLevels=Level # this is not correct, it should be something like: # stockLevels:[{"SKU":"P01", "LocationId":"00000000", "Level":4}] print r # &lt;Response [400]&gt; (obivously) </code></pre> <p>Any ides on what do I do wrong?</p>
0
2016-08-28T12:18:12Z
39,191,337
<p>After mining this <a href="https://github.com/LinnSystems/LinnworksNetSDK" rel="nofollow">GitHub repo's examples</a>, their approach seems to be the following:</p> <ol> <li>The body is, indeed, <code>x-www-form-urlencoded</code></li> <li>Complex parameters are JSON strings encoded for <code>x-www-form-urlencoded</code></li> </ol> <p>So looking at <a href="https://github.com/LinnSystems/LinnworksNetSDK/blob/master/Linnworks/src/php/Stock.php#L63" rel="nofollow">their PHP example</a> for the <a href="https://apps.linnworks.net/Api/Method/Stock-CreateVariationGroup" rel="nofollow">CreateVariationGroup</a> call, try this:</p> <pre><code>stockLevels=[ { "SKU": "sample string 1", "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a", "Level": 3 }, { "SKU": "sample string 1", "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a", "Level": 3 } ] payload = {'stockLevels' : json.dumps(stockLevels)} # send payload encoded with x-www-form-urlencoded </code></pre>
1
2016-08-28T12:35:31Z
[ "python", "json", "python-requests" ]
How to get random bounding boxes from image? (python)
39,191,221
<p>I have a batch of images and I open each one using the open function with mode 'rb' and then I read each one using read function. Now I want to get 50 random bounding boxes from each image and read each bounding box again with open and read functions. Is there any simple way to do it?</p>
0
2016-08-28T12:21:43Z
39,191,845
<p>Here's a possible solution:</p> <pre><code>from random import randint from PIL import Image def random_bbox(bbox): v = [randint(0, v) for v in bbox] left = min(v[0], v[2]) upper = min(v[1], v[3]) right = max(v[0], v[2]) lower = max(v[1], v[3]) return [left, upper, right, lower] filename = "your_image.png" im = Image.open(filename) bbox = im.getbbox() N = 50 for i in range(N): random_tile = im.crop(random_bbox(bbox)) #random_tile.show() </code></pre> <p>As you can see, this solution is cropping random subimages from one image, as you can see I've commented the line <code>random_tile.show()</code>, now it's up to you how processing that random_tile (saving, tweaking, ...)</p>
0
2016-08-28T13:37:06Z
[ "python", "image", "bounding-box" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call?</p> <p>EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.</p>
3
2016-08-28T12:28:43Z
39,191,350
<p>Here is one hack, but not pythonic. Actually since all you need is creating an object in global namespace you can simply update the namespace by your intended object.</p> <pre><code>&gt;&gt;&gt; zip(globals().update(a=[1, 2, 3]) or a, a[1:]) [(1, 2), (2, 3)] </code></pre> <p>Since the <code>update()</code> attribute returns None, its logical <code>or</code> with the object would be the object itself.</p>
1
2016-08-28T12:37:18Z
[ "python", "assign" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call?</p> <p>EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.</p>
3
2016-08-28T12:28:43Z
39,191,500
<p>If this is a code golf thing so it <strong>must</strong> be a single statement, then this works in Python 2:</p> <pre><code>print[zip(l,l[1:])for l in[[1,2,3,4,5]]][0] </code></pre> <p><strong>output</strong></p> <pre><code>[(1, 2), (2, 3), (3, 4), (4, 5)] </code></pre> <p>Otherwise, </p> <pre><code>l=[1,2,3,4,5];print zip(l,l[1:]) </code></pre> <p>is shorter, and <strong>far</strong> more sensible than the list comprehension abuse shown above.</p> <p>Many languages in the C family permit assignment to variables inside expressions. This can be convenient but it has also led to numerous bugs, and most modern compilers will generate warnings if an assignment is detected inside an <code>if</code> condition (for example).</p> <p>It was an intentional design decision to not allow that sort of thing in Python. Thus a Python assignment statement is <em>not</em> an expression, and so it doesn't have a value.</p> <p>BTW, the Python data model is quite different to that of many other languages. <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables" rel="nofollow">Python doesn't really have variables</a> that are containers for values, it has objects that may be bound to names.</p> <hr> <p>Note that in Python 3 <code>zip</code> returns an iterator, not a list, so if you want to produce a list you'd need to wrap the <code>zip</code> call with <code>list()</code>.</p>
2
2016-08-28T12:56:03Z
[ "python", "assign" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call?</p> <p>EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.</p>
3
2016-08-28T12:28:43Z
39,191,611
<p>You can use lambdas and default arguments to code golf this. Stressing that this shouldn't be used in production code, but just demonstrating what is possible in python.</p> <pre><code>(lambda l=[1, 2, 3]: zip(l, l[1:]))() </code></pre>
2
2016-08-28T13:10:24Z
[ "python", "assign" ]
Python assign value and use on same line
39,191,276
<p>I was trying to create a shortest-possible code for a puzzle, and the question came to mind trying to do something like this: </p> <p><code>zip(l=[1,2,3,4,5],l[1:])</code> </p> <p>So I was wondering, is there a way to produce a value, assign it to a variable and use that variable on the very same line/function call?</p> <p>EDIT:To clarify things, I am aware that this thing is not recommended nor good nor does it yield faster results. Also, the essence of the question is assignment and reusing of the same variable in the same function call. The list is produced using input, the static list here is for the example only. In a situation like this, I would like to avoid repeating the same task twice while I have already produced the result somewhere.</p>
3
2016-08-28T12:28:43Z
39,191,691
<p>Of course, you can always do this:</p> <pre><code>l = range(1, 6); zip(l, l[1:]) </code></pre> <p>but I guess that's not what you wanted. :-)</p> <p>There is a relatively clean way</p> <pre><code>(lambda l: zip(l, l[1:]))(range(1, 6)) </code></pre> <p>BTW that function is defined in <a href="https://docs.python.org/3.6/library/itertools.html#itertools-recipes" rel="nofollow">itertools recipes</a> as pairwise, so <code>pairwise(range(1, 6))</code> is probably the most direct way. You only need to write an import hook that imports Python functions from web pages. :-D</p> <p>And there is a nice convoluted way</p> <pre><code>next(zip(l, l[1:]) for l in [range(1, 6)]) </code></pre> <p>If you want more ideas, just say so. :-)</p>
1
2016-08-28T13:19:27Z
[ "python", "assign" ]
Python graph from txt(csv) file and there are 5 columns, How Can I pick 3rd or 4th columns for y axis?
39,191,448
<p><a href="http://i.stack.imgur.com/BCfNp.png" rel="nofollow">enter image description here</a>I am studying Python matplotlib. I have txt file which is including 4 columns.</p> <p>But I would like to select column 3rd or 4th one from txt.</p> <p>I tried and studied but there are so many errors in my coding. I am a beginner of python programming so it is too hard to handle by myself. Could you help me, please?</p> <pre><code>Date | Time | distance | speed 2016/08/25 02:19:39 0.0006 0.6406 2016/08/25 02:19:40 0.0013 2.7856 2016/08/25 02:19:40 0.0019 2.4938 2016/08/25 02:19:42 0.0025 2.1624 2016/08/25 02:19:43 0.0031 1.7867 2016/08/25 02:19:45 0.0038 1.2161 2016/08/25 02:19:50 0.0044 0.4524 2016/08/25 02:19:51 0.0050 1.7881 2016/08/25 02:19:54 0.0057 0.7540 2016/08/25 02:19:55 0.0063 2.7822 </code></pre> <p>And I want to make a graph that x axis is Date and time, and y axis is for distance or speed.</p> <p>I found this source from internet. And This bottom of source is working for with test.txt.</p> <pre><code>Date | Time | distance 2016/08/26 23:45:30 0.0088 2016/08/26 23:45:35 0.0094 2016/08/26 23:45:36 0.0101 2016/08/26 23:45:38 0.0107 2016/08/26 23:45:39 0.0113 2016/08/26 23:45:42 0.0119 2016/08/26 23:45:47 0.0126 2016/08/26 23:45:48 0.0132 2016/08/26 23:45:50 0.0138 2016/08/26 23:45:51 0.0145 2016/08/26 23:45:52 0.0151 2016/08/26 23:45:54 0.0157 </code></pre> <p>code:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime import numpy as np # Converter function datefunc = lambda x: mdates.date2num(datetime.strptime(x, '%Y/%m/%d %H:%M:%S')) # Read data from 'file.dat' dates, levels = np.genfromtxt('sss.txt', # Data to be read delimiter=19, # First column is 19 characters wide converters={0: datefunc}, # Formatting of column 0 dtype=float, # All values are floats unpack=True) # Unpack to several variables fig = plt.figure() ax = fig.add_subplot(111) # Configure x-ticks ax.set_xticks(dates) # Tickmark + label at every plotted point ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d %H:%M')) ax.set_ylabel('y') ax.plot_date(dates, levels, ls='-', marker='o') ax.set_title('How many km does my hamster runs?') ax.set_ylabel('Distance (km)') ax.grid(True) # Format the x-axis for dates (label formatting, rotation) fig.autofmt_xdate(rotation=45) fig.tight_layout() fig.show() </code></pre>
0
2016-08-28T12:50:22Z
39,193,884
<p>Here is a working example of how you can do it. The data in <code>data.txt</code> is as in your first example. I use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">np.loadtxt</a> to load the text file. The optional arguments I raise are: 1) <code>unpack=True</code>, so that you get the data into different variables as shown in my example; 2) <code>skiprows=2</code> to not read the file header; 3) <code>dtype='string'</code> to parse the data as string. Loading the data as strings forces you to convert the data into either floats or date-time objects. When the load is done it is a simple manner of just plotting the data with matplotlib. For clarity I used <code>twinx</code> to share the x-axis since the x-values are the same. Does this solve your question?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from datetime import datetime plt.close('all') filepath = 'data.txt' date, ttime, dist, vel = np.loadtxt(filepath, unpack=True, skiprows=2, dtype='string') timestamps = [datetime.strptime(ddate+'-'+tt, '%Y/%m/%d-%H:%M:%S') for ddate, tt in zip(date, ttime)] dist = map(float, dist) vel = map(float, vel) fig, ax_dist = plt.subplots() ax_vel = ax_dist.twinx() ax_dist.plot(timestamps, dist, 'r') ax_vel.plot(timestamps, vel, 'g') ax_dist.set_ylabel('Distance') ax_vel.set_ylabel('Velocity') ax_dist.set_xlabel('Time') fig.show() </code></pre>
0
2016-08-28T17:18:33Z
[ "python", "mysql", "date", "matplotlib", "graph" ]
How to group a data frame while containing information about two rows?
39,191,508
<p>I'm new to Python and I hope someone can help me with this performance issue. My data looks like:</p> <pre><code> TIMESTAMP A 34 2050-09-08 03:00:00 EST 3.0 40 2050-09-08 07:00:00 EST 3.0 67 2050-09-08 17:00:00 EST 6.0 84 2050-09-08 23:00:00 EST 6.0 89 2050-09-09 01:00:00 EST 11.0 103 2050-09-09 07:00:00 EST 10.0 110 2050-09-09 11:00:00 EST 10.0 118 2050-09-09 15:00:00 EST 10.0 </code></pre> <p>I want get the time intervals in which the values in column A are Steady (S), Increasing (I) or Decreasing (D).</p> <p>At this moment, I use a for-loop to compare the rows and calculate the slope between these values. As long as the sign of the slope does not change for every iteration, the end timestamp of the interval gets updated. This results in intervals like Interval(begin, end, state). The result for the example above would be:</p> <pre><code>Interval(2050-09-08 03:00:00 EST, 2050-09-08 07:00:00 EST, S) Interval(2050-09-08 07:00:00 EST, 2050-09-08 17:00:00 EST, I) Interval(2050-09-08 17:00:00 EST, 2050-09-08 23:00:00 EST, S) etc. </code></pre> <p>Since the dataset contains many rows and columns, I'm trying to find a way to code this more efficiently (without a for-loop). </p> <pre><code>data['slope'] = compute_slopes(data) data['state'].apply(lambda x: get_state(x)) data["shift"] = data["state"].shift(1) data["check"] = data["state"] != data["shift"] data["group"] = data["check"].cumsum() begin_group = data.groupby("group").first() end_group = data.groupby("group").last() result = pd.concat([begin_group, end_group]) result = result.sort_values('TIMESTAMP') def compute_slopes(data): next_df = data.shift(-1) return getSlope(pd.to_datetime(df['TIMESTAMP'], format = '%Y-%m-%d %H:%M:%S EST'), df['A'], pd.to_datetime(next_df['TIMESTAMP'], format = '%Y-%m-%d %H:%M:%S EST'), next_df['A']) def get_slope(x1, y1, x2, y2): return (y2 - y1) / ((x2 - x1).dt.total_seconds()/60) def get_state(slope): if(slope &lt; 0): state = 'D' #DECREASING elif(slope == 0): state = 'S' #STEADY else: state = 'I' #INCREASING return state </code></pre> <p>The code above results in something like below, but grouping this data frame does not work since there is one state which belongs to two timestamps (state S belongs to 03:00:00 and 07:00:00).</p> <pre><code> TIMESTAMP A slope state 34 2050-09-08 03:00:00 EST 3.0 0.000000 S 40 2050-09-08 07:00:00 EST 3.0 0.005000 I 67 2050-09-08 17:00:00 EST 6.0 0.000000 S 84 2050-09-08 23:00:00 EST 6.0 0.041667 I 89 2050-09-09 01:00:00 EST 11.0 -0.002778 D 103 2050-09-09 07:00:00 EST 10.0 0.000000 S 110 2050-09-09 11:00:00 EST 10.0 0.000000 S 118 2050-09-09 15:00:00 EST 10.0 0.000000 S </code></pre> <p>In some way, I want to group these states and get the begin- and end timestamp for each state and save it in an interval. Does anyone know a quicker way than just looping through the data frame?</p> <p>Many thanks in advance!</p>
1
2016-08-28T12:56:58Z
39,192,395
<p>This should be helpful. Use lots of <code>shift</code> and then use <code>groupby</code> + <code>agg</code>.</p> <pre><code>df.loc[df.A &lt; df.A.shift(-1), 'State'] = 'I' df.loc[df.A &gt; df.A.shift(-1), 'State'] = 'D' df.loc[df.A == df.A.shift(-1).ffill(), 'State'] = 'S' df['StateGroup'] = (df.State != df.State.shift()).cumsum() df['NextTIMESTAMP'] = df.TIMESTAMP.shift(-1).ffill() df </code></pre> <p><a href="http://i.stack.imgur.com/W7iIs.png" rel="nofollow"><img src="http://i.stack.imgur.com/W7iIs.png" alt="enter image description here"></a></p> <pre><code>aggs = dict(A=['mean', 'count', 'first', 'last'], State=['first'], TIMESTAMP={'Start': 'first'}, NextTIMESTAMP={'End': 'last'}) df.groupby('StateGroup').agg(aggs) </code></pre> <p><a href="http://i.stack.imgur.com/CBk1r.png" rel="nofollow"><img src="http://i.stack.imgur.com/CBk1r.png" alt="enter image description here"></a></p>
0
2016-08-28T14:38:12Z
[ "python", "pandas", "dataframe", "timestamp", "group" ]
Page not found (404) error on django
39,191,613
<p>I am trying to get price value as soon as product is selected in sale form. There is a sale form which has field of price, quantity and product. When user selects for product, the price of that product should be shown to the input box of price. For that i have used ajax. </p> <blockquote> <p>But i am getting an error of 404 page not found in sales/price/2. When i enter that url in browser i get the result as {"price-pk": 2, "price": 890.0}</p> </blockquote> <p><strong>The code</strong></p> <p><strong>sales/views.py</strong></p> <pre><code>def fetch_price(request, pk): response = {} product = get_object_or_404(Product, pk=pk) print('product',product) if request.method=='GET': price = product.price print('price',price) response['price-pk'] = product.pk response['price'] = price json_data = json.dumps(response) return HttpResponse(json_data, content_type='application/json') </code></pre> <p><strong>sales/urls.py</strong></p> <pre><code>url(r'^price/(?P&lt;pk&gt;\d+)$', views.fetch_price, name='fetch_price'), </code></pre> <p><strong>add_sale.html</strong></p> <pre><code>&lt;script&gt; $('#id_product').on('change', function() { price_id = $(this).val(); // if shoe is selected price_id value becomes 2 as pk of shoe is 2 console.log(price_id); url = "/sale/price/"+price_id+"/"; $.ajax({ type:'GET', url:url, success: function(data){ console.log('price will be updated based on product selected'); $('#id_price').val(data.price); } }) }); &lt;/script&gt; </code></pre>
0
2016-08-28T13:10:43Z
39,191,759
<p>Your URL pattern doesn't end with a slash, but your Ajax request is for a URL that does end with a slash. Fix one or the other; probably better for consistency to ensure that the pattern has a slash.</p> <pre><code>r'^price/(?P&lt;pk&gt;\d+)/$' </code></pre>
2
2016-08-28T13:27:46Z
[ "javascript", "python", "ajax", "django", "django-views" ]
python bokeh, how to make a correlation plot?
39,191,653
<p>How can I make a correlation heatmap in Bokeh?</p> <pre><code>import pandas as pd import bokeh.charts df = pd.util.testing.makeTimeDataFrame(1000) c = df.corr() p = bokeh.charts.HeatMap(c) # not right # try to make it a long form # (and it's ugly in pandas to use 'index' in melt) c['x'] = c.index c = pd.melt(c, 'x', ['A','B','C','D']) # this shows the right 4x4 matrix, but values are still wrong p = bokeh.charts.HeatMap(c, x = 'x', y = 'variable', values = 'value') </code></pre> <p>By the way, can I make a colorbar on the side, instead of legends in the plot? And also how to choose the color range/mapping eg dark blue (-1) to white (0) to dark red (+1)?</p>
0
2016-08-28T13:15:50Z
39,195,150
<p>If you want that level of control, I have to suggest using the (only slightly) lower level <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/plotting.html" rel="nofollow"><code>bokeh.plotting</code> interface</a>. You can see an example of a categorical heatmap generated using this interface in the gallery:</p> <p><a href="http://bokeh.pydata.org/en/latest/docs/gallery/categorical.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/gallery/categorical.html</a></p> <hr> <p>Regarding a legend, for a colormap like this you actually will want a discrete <code>ColorBar</code> instead of a <code>Legend</code>. This is a new feature that will be present in the upcoming <code>0.12.2</code> release later this week <em>(today's date: 2016-08-28)</em>. These new colorbar annotations can be located outside the main plot area. Currently, to see the documentation for it, you will have to refer to the "dev preview" docs site:</p> <p><a href="http://bokeh.pydata.org/en/dev/docs/user_guide/annotations.html#color-bars" rel="nofollow">http://bokeh.pydata.org/en/dev/docs/user_guide/annotations.html#color-bars</a></p> <p>There is also an example in the GitHub repo:</p> <p><a href="https://github.com/bokeh/bokeh/blob/master/examples/plotting/file/color_data_map.py" rel="nofollow">https://github.com/bokeh/bokeh/blob/master/examples/plotting/file/color_data_map.py</a></p> <p>Note that last example also uses another new feature to do the colormapping in the browser, instead of having to precompute the colors in python. Basically all together it looks like:</p> <pre><code># create a color mapper with your palette - can be any list of colors mapper = LinearColorMapper(palette=Viridis3, low=0, high=100) p = figure(toolbar_location=None, tools='', title=title) p.circle( x='x', y='y', source=source # use the mapper to colormap according to the 'z' column (in the browser) fill_color={'field': 'z', 'transform': mapper}, ) # create a ColorBar and addit to the side of the plot color_bar = ColorBar(color_mapper=mapper, location=(0, 0)) p.add_layout(color_bar, 'right') </code></pre> <p>There are more sophisticated options too, e.g. if you want to control the ticking on the colorbar more carefully you could add a custom ticker or tick formatter just like on a normal <code>Axis</code>, to achieve things like:</p> <p><a href="http://i.stack.imgur.com/XnHVB.png" rel="nofollow"><img src="http://i.stack.imgur.com/XnHVB.png" alt="enter image description here"></a></p> <p>It's not clear what your actual requirements are, so I just mention this in case it is useful to know. </p> <p>Until <code>0.12.2</code> is released, you can use these new features by installing a "dev build" or release candidate. The main docs site has simple instructions for <a href="http://bokeh.pydata.org/en/dev/docs/installation.html#developer-builds" rel="nofollow">installing developer builds</a>.</p> <hr> <p>Finally, Bokeh is a large project and finding the best way to do so often involves asking for more information and context, and in general, having a discussion. That kind of collaborative help seems to be frowned upon at SO, (they are "not real answers") so I'd encourage you to also check out the <a href="https://groups.google.com/a/continuum.io/forum/?pli=1#!forum/bokeh" rel="nofollow">public mailing list</a> for help anytime. </p>
2
2016-08-28T19:46:46Z
[ "python", "heatmap", "bokeh" ]
I want to toggle a real pushbutton and display it on tkinter GUI
39,191,725
<p>I want to toggle a pushbutton and show its changes on a label using tkinter.</p> <p>If I press the button it shows "on" on the label and when I press again it shows "off" on the label</p> <p>So I try these codes and If I'm trying the wrong code please help me write the correct using tkinter.</p> <p>I have a problem in combining this code</p> <pre class="lang-py prettyprint-override"><code>import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(22,GPIO.IN,up_down=GPIO.PUD_UP) while(1): if GPIO.input(22)==1: if bs == False : x.set("on") bs=True sleep(0.5) else: x.set("off") bs=False sleep(0.5) </code></pre> <p>This works okay but I want to connect it to a GUI label to print on it on or off.</p> <p>Here is the tkinter code</p> <pre class="lang-py prettyprint-override"><code>import tkinter.* root = tk() x = StringVar() s=Label(root,textvariable=x) s.grid(column=0,row=0) root.mainloop() </code></pre> <p>When I try to combine it I make it like this</p> <pre class="lang-py prettyprint-override"><code>from Tkinter import * import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(7,GPIO.IN) b=False def check_button1(): if GPIO.input(7)== 1: if b == False : labelText1.set("on") print"on" b=True time.sleep(0.5) else: labelText1.set("off") print"off" b=False time.sleep(0.5) mamdouh.after(10,check_button1) mamdouh = Tk() labelText1 = StringVar() x1 = Label(mamdouh,textvariable=labelText1) x1.config(font=('Helvetica',25,'bold')) x1.grid(row=0,column=0) mamdouh.title("mamdouh") mamdouh.geometry('1200x700') mamdouh.after(10,check_button1) mamdouh.mainloop() </code></pre> <p>but it didn't works it keeps blank every time I press the push button actually If it works well I will put 17 push button</p> <p>I think that the problem is in placing this if statment on the right place and placing the b variable in it's right place and I think also there is a problem between this if statment and tkinter because I tried this code wich works perfect but it is not toggling the push button so I want to change this lets add this code here also :</p> <pre class="lang-py prettyprint-override"><code>from Tkinter import * import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(7,GPIO.IN) def check_button1(): if(GPIO.input(7) == GPIO.LOW): labelText1.set("on") else: labelText1.set("off") mamdouh.after(10,check_button1) mamdouh = Tk() labelText1 = StringVar() x1 = Label(mamdouh,textvariable=labelText1) x1.config(font=('Helvetica',25,'bold')) x1.grid(row=0,column=0) mamdouh.title("mamdouh") mamdouh.geometry('1200x700') mamdouh.after(10,check_button1) mamdouh.mainloop() </code></pre> <p>So how I can make this toggle push button on an Label?</p>
0
2016-08-28T13:23:52Z
39,195,269
<p>Your problem is recognizing button down and button up events. Your OS mouse driver does this for your mouse buttons. If your GPIO module does not do this for you, you will have to detect these events by comparing the current state to the previous state. (I am ignoring here any possible need to 'de-bounce' the button.) You are sort of trying to do this with the time.sleep(.5) calls, but do not use time.sleep in gui code.</p> <p>Your driver should be self-contained and independent of any tk widgets other than the root needed for .after. For multiple buttons, you will need your own GPIOButton class. Your code that works is a starting point. Tkinter allows you to tie a command to button-up events. Your class init should similarly take up and or down event commands (callbacks).</p> <p>Here is something untested that might get you started.</p> <pre><code>class GPIOButton: def __init__(self, master, buttons, command_down=None, command_up=None): self.master = master self.buttons = buttons self.command_down = command_down self.command_up = command_up GPIO.setmode(GPIO.BOARD) for button in buttons: GPIO.setup(button, GPIO.IN) self.state = [GPIO.HIGH] * len(buttons) # best initial value? self.check_buttons() # or call this elsewhere def check_buttons(self): for i, button in enumerate(self.buttons): oldstate = self.state[i] newstate = GPIO.input(button) if oldstate != newstate: self.state[i] = newstate command = (self.command_down if newstate==GPIO.LOW else self.command_up) command(button) self.master.after(10, self.check_button) </code></pre>
0
2016-08-28T20:00:54Z
[ "python", "python-2.7", "tkinter", "raspberry-pi", "raspberry-pi2" ]
flask - sqlalchemy execute update where id=3
39,191,853
<p>How can I update <strong>column email</strong> from user table <strong>where id=3</strong>?</p> <pre><code>from sqlalchemy import update @app.route('/testupdate/') def testupdate(): db.session.execute(update(user, values={user.email: "za@bcdef"})) db.session.commit() return 'done' </code></pre>
-1
2016-08-28T13:37:28Z
39,192,400
<pre><code>stmt = user.update().where(user.c.id==3).values(email="za@bcdef") db.session.execute(stmt) </code></pre> <p>see examples in <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/dml.html#sqlalchemy.sql.expression.update" rel="nofollow">documentation</a></p>
0
2016-08-28T14:38:26Z
[ "python", "orm", "sqlalchemy", "execute" ]
How to use TextInput widget with ModelChoiceField in Django forms?
39,191,861
<p>In Django, the <code>ChoiceField</code> or <code>ModelChoiceField</code> represent the data in a <code>Select</code> widget. This is helpful when the list of objects is small. However it is extremely difficult to manage (for the end-user) if the number of objects are in thousands.</p> <p>To eliminate the said problem I'd like the end-users to manually enter the field value in an input box of type text (i.e, via <code>TextInput</code> widget).</p> <hr> <p>So far, I have created the below code. As <code>ModelChoiceField</code> has <code>Select</code> widget by default; It behaves in similar manner as before even after changing the widget to <code>TextInput</code>. It expects a <code>pk</code> or <code>id</code> value of the model object and thus raising an error : </p> <blockquote> <p><em>Select a valid choice. That choice is not one of the available choices.</em></p> </blockquote> <p>However, I'd want the end-user to enter <code>sku_number</code> field in the input box rather than the <code>pk</code> or <code>id</code> of the object. What is the correct way to solve this problem?</p> <p><strong>models.py</strong></p> <pre><code>class Product(models.Model): sku_number = models.CharField(null=False, unique=True) product_name = models.CharField(null=Flase) def __str__(self): return self.sku_number </code></pre> <p><strong>forms.py</strong></p> <pre><code>class SkuForm(forms.Form): sku_number = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.TextInput()) extra_field = forms.CharField(required=True) </code></pre> <hr> <p><strong>Note</strong> : I did try another approach to solve this problem. By displaying only last 10 objects by slicing the number of objects; this ensures that the select box is not flooded with thousands of items.</p> <pre><code>queryset=Product.objects.all().order_by('-id')[:10] </code></pre> <p>The latter methodology if correctly implemented would work with my particular use-case, however others might be interested in the former method. The above statement further raised errors because of Django's limitation with generating SQL statements.</p> <blockquote> <p>Also note that even though slicing an unevaluated <strong>QuerySet</strong> returns another unevaluated <strong>QuerySet</strong>, modifying it further (e.g., adding more filters, or modifying ordering) is not allowed, since that does not translate well into SQL and it would not have a clear meaning either.</p> <p>Source : <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated" rel="nofollow">Django Docs</a></p> </blockquote>
0
2016-08-28T13:38:32Z
39,196,428
<p>You can easily do that in the form clean() method.</p> <p>I.e.</p> <pre><code>from django.shortcuts import get_object_or_404 class SkuForm(forms.Form): sku = forms.CharField(required=True) extra_field = forms.CharField(required=True) def clean(self): # If you're on Python 2.x, change super() to super(SkuForm, self) cleaned_data = super().clean() sku = cleaned_data['sku'] obj = get_object_or_404(Product, sku_number=sku) # do sth with the Product </code></pre>
1
2016-08-28T22:38:34Z
[ "python", "django", "forms" ]
How to use TextInput widget with ModelChoiceField in Django forms?
39,191,861
<p>In Django, the <code>ChoiceField</code> or <code>ModelChoiceField</code> represent the data in a <code>Select</code> widget. This is helpful when the list of objects is small. However it is extremely difficult to manage (for the end-user) if the number of objects are in thousands.</p> <p>To eliminate the said problem I'd like the end-users to manually enter the field value in an input box of type text (i.e, via <code>TextInput</code> widget).</p> <hr> <p>So far, I have created the below code. As <code>ModelChoiceField</code> has <code>Select</code> widget by default; It behaves in similar manner as before even after changing the widget to <code>TextInput</code>. It expects a <code>pk</code> or <code>id</code> value of the model object and thus raising an error : </p> <blockquote> <p><em>Select a valid choice. That choice is not one of the available choices.</em></p> </blockquote> <p>However, I'd want the end-user to enter <code>sku_number</code> field in the input box rather than the <code>pk</code> or <code>id</code> of the object. What is the correct way to solve this problem?</p> <p><strong>models.py</strong></p> <pre><code>class Product(models.Model): sku_number = models.CharField(null=False, unique=True) product_name = models.CharField(null=Flase) def __str__(self): return self.sku_number </code></pre> <p><strong>forms.py</strong></p> <pre><code>class SkuForm(forms.Form): sku_number = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.TextInput()) extra_field = forms.CharField(required=True) </code></pre> <hr> <p><strong>Note</strong> : I did try another approach to solve this problem. By displaying only last 10 objects by slicing the number of objects; this ensures that the select box is not flooded with thousands of items.</p> <pre><code>queryset=Product.objects.all().order_by('-id')[:10] </code></pre> <p>The latter methodology if correctly implemented would work with my particular use-case, however others might be interested in the former method. The above statement further raised errors because of Django's limitation with generating SQL statements.</p> <blockquote> <p>Also note that even though slicing an unevaluated <strong>QuerySet</strong> returns another unevaluated <strong>QuerySet</strong>, modifying it further (e.g., adding more filters, or modifying ordering) is not allowed, since that does not translate well into SQL and it would not have a clear meaning either.</p> <p>Source : <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated" rel="nofollow">Django Docs</a></p> </blockquote>
0
2016-08-28T13:38:32Z
39,304,229
<p>In my case, I had to change the <code>sku_number</code> field to Product object's <code>id</code>. This had to be done before <code>clean()</code>. As seen in <a href="http://stackoverflow.com/a/11083656/433587">this answer</a>, <code>__init__()</code> should be used to modify data before it reaches <code>clean()</code>.</p> <pre><code>class SkuForm(forms.Form): sku_number = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.TextInput()) extra_field = forms.CharField(required=True) def __init__(self, data=None, *args, **kwargs): if data is not None: data = data.copy() # make it mutable if data['sku_number']: obj = get_object_or_404(Product, batch_name=data['sku_number']) data['sku_number'] = obj.id super(SkuForm, self).__init__(data=data, *args, **kwargs) </code></pre>
0
2016-09-03T07:06:06Z
[ "python", "django", "forms" ]
Class object has no attribute tk?
39,191,892
<p>I am fairly new to python and with the help of tutorials I am trying to create a calculator but got stuck due to an error which I am unable to correct which occurs when I press a number button</p> <pre><code>from tkinter import * root=Tk() root.title("Yuvi's CAl") global char class cal(): def __init__(self): self.string= StringVar() root=Tk() root.title("Yuvi's CAl") self.string=StringVar enter=Entry(root,textvariable=self.string) enter.grid(row=0,column=0,columnspan=6) values=["1","2","3","4","5","+","6","7","=","8","9","c"] row=1 col=0 i=0 for txt in values: if i==3: row=3 col=0 if i==6: row=4 col=0 if i==9: row=5 col=0 if txt=="+": but=Button(root,text=txt) but.grid(row=row,column=col) elif txt=="=": but=Button(root,text=txt,command=lambda:self.equals) but.grid(row=row,column=col) elif txt=="c": but=Button(root,text=txt,command=lambda:self.clr) but.grid(row=row,column=col) else: but=Button(root,text=txt,command=lambda txt=txt:self.add(txt)) but.grid(row=row,column=col) col+=1 i+=1 def add(self,char): meet=self.string.get(self) self.string.set((str(meet)) + (str(char))) def equals(self): result=eval(self.string.get()) self.string.set(result) def clr(self): self.string.set("") ent=cal() root.mainloop() </code></pre> <p>and this being the error when I press a number button</p> <pre><code>Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__ return self.func(*args) File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 40, in &lt;lambda&gt; but=Button(root,text=txt,command=lambda txt=txt:self.add(txt)) File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 46, in add meet=self.string.get(self) File "/usr/lib/python3.4/tkinter/__init__.py", line 339, in get value = self._tk.globalgetvar(self._name) AttributeError: 'cal' object has no attribute '_tk' </code></pre> <p>Do rectify if any mistakes Thank you in advance</p>
1
2016-08-28T13:41:57Z
39,192,290
<p>There are several issues with your code first you should remove hiding your global vars within your <code>__init__</code> as it creates two windows and only running <code>mainloop</code> for one of them. In addition you overwrite <code>self.string</code> with the <code>StringVar</code> class object after first creating an instance of it. So your <code>__init__</code> could look like so</p> <pre><code>... def __init__(self): self.string=StringVar() enter=Entry(root,textvariable=self.string) enter.grid(row=0,column=0,columnspan=6) values=["1","2","3","4","5","+","6","7","=","8","9","c"] row=1 col=0 i=0 ... </code></pre> <p>then in your <code>add</code> you don't have to pass <code>self</code> to <code>self.string.get</code>, that is it should look like </p> <pre><code>... def add(self,char): meet=self.string.get() self.string.set((str(meet)) + (str(char))) ... </code></pre> <p>Those changes fixes your exception but I guess there are still other logical mistakes in the calculator, however that's not what the question is about and fixing them wouldn't help you learning python. </p>
2
2016-08-28T14:25:31Z
[ "python", "tkinter", "python-3.4" ]
Reverse for 'detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/$']
39,191,917
<p>My traceback:</p> <pre><code>File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in post 217. return super(BaseCreateView, self).post(request, *args, **kwargs) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in post 183. return self.form_valid(form) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in form_valid 163. return super(ModelFormMixin, self).form_valid(form) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in form_valid 79. return HttpResponseRedirect(self.get_success_url()) File "D:\virtualEnv\lib\site-packages\django\views\generic\edit.py" in get_success_url 151. url = self.object.get_absolute_url() File "D:\virtualEnv\website\music\models.py" in get_absolute_url 13. return reverse('music:detail', kwargs={'pk': self.pk}) File "D:\virtualEnv\lib\site-packages\django\urls\base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "D:\virtualEnv\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix 389. (lookup_view_s, args, kwargs, len(patterns), patterns) Exception Type: NoReverseMatch at /music/album/add/ Exception Value: Reverse for 'detail' with arguments '()' and keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['music/(?P&lt;album_id&gt;[0-9]+)/$'] </code></pre> <p>my Album model is:</p> <pre><code>class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def get_absolute_url(self): return reverse('music:detail', kwargs={'pk': self.pk}) </code></pre> <p>my views.py:</p> <pre><code>class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title','genre', 'album_logo'] </code></pre> <p>urls:</p> <pre><code>app_name = 'music' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P&lt;album_id&gt;[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'), ] </code></pre> <p>Why this code not work properly in D:\virtualEnv\website\music\models.py in get_absolute_url:</p> <pre><code> return reverse('music:detail', kwargs={'pk': self.pk}) </code></pre> <p>When I tried to add album using form it gave above errors. How do I fix this issues?</p> <p><strong>Edit:</strong></p> <p>When I changed album_id with pk, it gives following errors:</p> <pre><code>Template error: In template D:\virtualEnv\website\music\templates\music\detail.html, error at line 14 Reverse for 'favorite' with arguments '(4,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 4 : 5 : &lt;img src="{{album.album_logo}}" &gt; 6 : 7 : &lt;h1&gt;{{album.album_title }}&lt;/h1&gt; 8 : &lt;h3&gt;{{album.artist}}&lt;/h3&gt; 9 : 10 : {% if error_message %} 11 : &lt;p&gt;&lt;strong&gt;{{ error_message }}&lt;/strong&gt;&lt;/p&gt; 12 : {% endif %} 13 : 14 : &lt;form action=" {% url 'music:favorite' album.id %} " method="post"&gt; 15 : {% csrf_token %} 16 : {% for song in album.song_set.all %} 17 : &lt;input type="radio" id="song{{ forloop.counter}}" name="song" value="{{song.id}}"&gt; 18 : &lt;label for= "song{{ forloop.counter}}"&gt; 19 : {{song.song_title}} 20 : {% if song.is_favorite %} 21 : &lt;img src="http://i.imgur.com/b9b13Rd.png"/&gt; 22 : {% endif %} 23 : &lt;/label&gt;&lt;br&gt; 24 : {% endfor %} Traceback: File "D:\virtualEnv\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "D:\virtualEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "D:\virtualEnv\lib\site-packages\django\template\response.py" in render 109. self.content = self.rendered_content File "D:\virtualEnv\lib\site-packages\django\template\response.py" in rendered_content 86. content = template.render(context, self._request) File "D:\virtualEnv\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 208. return self._render(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context) File "D:\virtualEnv\lib\site-packages\django\template\loader_tags.py" in render 174. return compiled_parent._render(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context) File "D:\virtualEnv\lib\site-packages\django\template\loader_tags.py" in render 70. result = block.nodelist.render(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render 994. bit = node.render_annotated(context) File "D:\virtualEnv\lib\site-packages\django\template\base.py" in render_annotated 961. return self.render(context) File "D:\virtualEnv\lib\site-packages\django\template\defaulttags.py" in render 447. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "D:\virtualEnv\lib\site-packages\django\urls\base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "D:\virtualEnv\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix 389. (lookup_view_s, args, kwargs, len(patterns), patterns) Exception Type: NoReverseMatch at /music/4/ Exception Value: Reverse for 'favorite' with arguments '(4,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre>
-1
2016-08-28T13:44:02Z
39,191,959
<p>Your <code>get_absolute_url</code> method passes a <code>kwarg</code> called <code>pk</code>, but your URL pattern expects an argument called <code>album_id</code>. </p>
0
2016-08-28T13:49:18Z
[ "python", "django" ]
Mouse X & Y positions for get_rect.collidepoint in pygame
39,192,125
<p>I am trying to create a click event in PyGame but I am facing an error:</p> <pre class="lang-none prettyprint-override"><code>AttributeError: 'NoneType' object has no attribute 'get_rect' </code></pre> <p>The code:</p> <pre><code>mouse_pos = pygame.mouse.get_pos() mouse_pressed = pygame.mouse.get_pressed() if mouse_pressed[0] and play_btn.get_rect().collidepoint(mouse_pos[0], mouse_pos[1]): print "Mouse clicked play" </code></pre> <p>The button...</p> <pre><code>play_btn = button("PLAY NOW", 210, 150, 300, 80, white, grey) </code></pre>
1
2016-08-28T14:06:47Z
39,192,933
<p>Based on the information provided, <code>button</code> doesn't return anything. It returns <code>None</code>.</p> <p>According to your previous <a href="http://stackoverflow.com/questions/39190253/pygame-button-cant-seek-in-this-data-source">question</a> your function <code>button</code> looks like this:</p> <pre><code>def button(btn_txt_img,posx,posy): btn_txt_img = pygame.image.load(("/Users/wolf/Desktop/python/img/",btn_txt_img,".png")).convert_alpha() btn_txt_img_hover = pygame.image.load(("/Users/wolf/Desktop/python/img/",btn_txt_img,"_hover.png")).convert_alpha() if((w_size[0]/3.3)+btn_txt_img.get_rect().width &gt; mouse_pos[0] &gt; (w_size[0]/3.3) and posy+btn_txt_img.get_rect().height &gt; mouse_pos[1] &gt; posy): return main_screen.blit(btn_txt_img_hover, [(w_size[0]/3.3),posy,btn_txt_img.get_rect().width,btn_txt_img.get_rect().height]) else: return main_screen.blit(btn_txt_img, [(w_size[0]/3.3),posy,btn_txt_img.get_rect().width,btn_txt_img.get_rect().height]) pygame.display.update() </code></pre> <p>Blitting works directly on the object and therefore returns <code>None</code>. Since your function returns whatever <code>main_screen.blit...</code> returns, it'll also return <code>None</code></p>
0
2016-08-28T15:37:11Z
[ "python", "pygame" ]
How to send a string with spaces from Python to Bash sub-process as a single value?
39,192,127
<p>I'm trying to send a variable from a python script to a bash script. I'm using <code>popen</code> like as shown below:</p> <pre><code>subprocess.Popen(["bash", "-c", ". mainGui_functions.sh %d %s" % (commandNum.get(), entryVal)]) </code></pre> <p>However, <code>entryVal</code> can sometimes contain one or more white space characters. In that case I divide the string into multiple arguments ($2,$3..)</p> <p>How can i get it in one argument?</p>
2
2016-08-28T14:07:02Z
39,192,204
<p>Simple solution #1: You do it the exact same way you'd do it if you were typing the input on the commandline; put it in quotes:</p> <pre><code>subprocess.Popen(["bash", "-c", ". mainGui_functions.sh {} '{}'".format(commandNum.get(), entryVal)]) </code></pre> <p>Simple solution #2: If <code>mainGui_functions.sh</code> is already executable, then you can just omit the <code>bash</code> part and pas args to it directly. In this case, <code>subprocess</code> takes care of making sure an entry with whitespace winds up as a single arg for you:</p> <pre><code>subprocess.Popen(["mainGui_functions.sh", str(commandNum.get()), entryVal]) </code></pre>
2
2016-08-28T14:17:09Z
[ "python", "bash", "subprocess" ]
How to send a string with spaces from Python to Bash sub-process as a single value?
39,192,127
<p>I'm trying to send a variable from a python script to a bash script. I'm using <code>popen</code> like as shown below:</p> <pre><code>subprocess.Popen(["bash", "-c", ". mainGui_functions.sh %d %s" % (commandNum.get(), entryVal)]) </code></pre> <p>However, <code>entryVal</code> can sometimes contain one or more white space characters. In that case I divide the string into multiple arguments ($2,$3..)</p> <p>How can i get it in one argument?</p>
2
2016-08-28T14:07:02Z
39,192,210
<p>Put quotes around it in your bash command line – e.g.,</p> <pre><code>subprocess.Popen(['bash', '-c', '. mainGui_functions.sh %d "%s"' % (commandNum.get(), entryVal)]) </code></pre>
0
2016-08-28T14:17:52Z
[ "python", "bash", "subprocess" ]
Scrape All External Links from Multiple URLs in a Text File with Scrapy
39,192,171
<p>I am new to Scrapy and Python and as such I am a beginner. I want to be able to have Scrapy read a text file with a seed list of around 100k urls, have Scrapy visit each URL, and extract all external URLs (URLs of Other Sites) found on each of those Seed URLs and export the results to a separate text file.</p> <p>Scrapy should only visit the URLs in the text file, not spider out and follow any other URL.</p> <p>I want to be able to have Scrapy work as fast as possible, I have a very powerful server with a 1GBS line. Each URL in my list is from a unique domain, so I won't be hitting any 1 site hard at all and thus won't be encountering IP blocks.</p> <p>How would I go about creating a project in Scrapy to be able to extract all external links from a list of urls stored in a textfile?</p> <p>Thanks.</p>
-1
2016-08-28T14:12:56Z
39,205,016
<p>You should use: <br> 1. start_requests function for reading list of urls. <br> 2. css or xpath selector for all "a" html elements.</p> <pre><code>from scrapy import Spider class YourSpider(Spider): name = "your_spider" def start_requests(self): with open('your_input.txt', 'r') as f: # read the list of urls for url in f.readlines() # process each of them yield Request(url, callback=self.parse) def parse(self, response): item = YourItem(parent_url=response.url) item['child_urls'] = response.css('a::attr(href)').extract() return item </code></pre> <p>More info about start_requests here: <br> <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.start_requests" rel="nofollow">http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.start_requests</a></p> <p>For extracting scraped items to another file use Item Pipeline or Feed Export. Basic pipeline example here: <br> <a href="http://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-a-json-file" rel="nofollow">http://doc.scrapy.org/en/latest/topics/item-pipeline.html#write-items-to-a-json-file</a></p>
0
2016-08-29T11:19:47Z
[ "python", "url", "web-scraping", "scrapy", "web-crawler" ]
RTSP: cannot get session identifier
39,192,256
<p>I am trying to control an ip cam using a python script (I can see the stream with VLC or mplayer).</p> <p>After received OPTIONS and DESCRIBE informations, every SETUP I try give me an error:</p> <pre><code>SETUP rtsp://192.168.0.41:554/xxxxxx RTSP/1.0 CSeq: 3 Transport: RTP/AVP/UDP;unicast;client_port=3056-3057 RTSP/1.0 400 Bad Request Allow: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER, SET_PARAMETER,USER_CMD_SET </code></pre> <p>so I never receive the session identification.</p> <p>Maybe the problem is in the Transport line, but I think it's because I do not know what to put in place of the xxxxxxx (I tried and googled a lot but with non results)</p> <p>Here are the output of OPTIONS and DESCRIBE:</p> <pre><code> OPTIONS rtsp://192.168.0.41:554 RTSP/1.0 CSeq: 1 RTSP/1.0 200 OK CSeq: 1 Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER, SET_PARAMETER,USER_CMD_SET --------------------------------- DESCRIBE rtsp://192.168.0.41:554/onvif2 RTSP/1.0 CSeq: 2 RTSP/1.0 200 OK CSeq: 2 Content-Type: application/sdp Content-Length: 360 v=0 o=- 1421069297525233 1 IN IP4 192.168.0.41 s=H.264 Video, RtspServer_0.0.0.2 t=0 0 a=tool:RtspServer_0.0.0.2 a=type:broadcast a=control:* a=range:npt=0- m=video 0 RTP/AVP 96 c=IN IP4 0.0.0.0 b=AS:500 a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=1;profile-level-id=42001F;sprop-parameter-sets=Z0IAH5WoFAFuQA==,aM48gA== a=control:track1 </code></pre> <p>What that * stands for?</p> <p>And what is "track1"? </p> <p>(note: if I check for onvif1, that is the other streaming sent by the cam, the result is the same, but with track2, that means that the server answer should be appropriate)</p>
0
2016-08-28T14:22:03Z
39,212,075
<p>Example from RTSP rfc <a href="https://www.ietf.org/rfc/rfc2326.txt" rel="nofollow">https://www.ietf.org/rfc/rfc2326.txt</a>:</p> <pre><code>S-&gt;C RTSP/1.0 200 OK CSeq: 1 Content-base: rtsp://foo.com/test.wav/ Content-type: application/sdp Content-length: 48 v=0 o=- 872653257 872653257 IN IP4 172.16.2.187 s=mu-law wave file i=audio test t=0 0 m=audio 0 RTP/AVP 0 a=control:streamid=0 C-&gt;S SETUP rtsp://foo.com/test.wav/streamid=0 RTSP/1.0 Transport: RTP/AVP/UDP;unicast; client_port=6970-6971;mode=play CSeq: 2 </code></pre> <p>You just append it to the URL for your SETUP request.</p> <p>I'm not really sure what the a=control:* means</p>
0
2016-08-29T17:40:32Z
[ "python", "streaming", "rtsp", "onvif" ]