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
Using QApplication::exec() in a function or class
38,800,568
<p>I want the following code to get the request url starting with <code>http://down.51en.com:88</code> during the web loading process , and then do other processing with the response object of the url . In my program, once <code>targetUrl</code> is assigned a value , I want the function <code>targetUrlGetter(url)</co...
0
2016-08-06T04:33:38Z
38,810,188
<p>You should always initialize <code>QApplication</code> at the beginning of the program, and always call the <code>QApplication::exec</code> function at the end of the program.</p> <p>Another thing is that <code>QWebEngineUrlRequestInterceptor.interceptRequest</code> is a callback function which is called asynchrono...
-1
2016-08-07T01:49:05Z
[ "python", "qt", "pyqt", "qt5", "pyqt5" ]
Pandas read_csv incorrectly reading headers
38,800,587
<p>I am reading a csv file using 'pd.read_csv' and writing it to another csv using 'file.to_csv'. It is incorrectly displaying the headers in the output file. For example,</p> <p><strong>input</strong>: </p> <pre><code>ABC | 20151004 | 1900 | 0000000002 | MUPPETS SP 1-10/4, THE | | | R|RS 0 0 0 0 0 2993 </cod...
-2
2016-08-06T04:37:56Z
38,806,408
<p>Try this:</p> <pre><code>data = pd.read_csv(r'filepath/input.csv',sep='|') </code></pre> <p>The rs.1 is likely indicative of duplicate 'rs' columns</p>
0
2016-08-06T16:30:23Z
[ "python", "pandas" ]
My submit button in html template is not working in django
38,800,710
<p>I prepared an attendance register template in HTML.I have a HTML table and a submit button in the given HTML page.While clicking the submit button,i want to save the data in HTML table.But i can't.</p> <p>Ist std.html</p> <pre><code> {% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title...
0
2016-08-06T05:00:30Z
38,800,761
<p>In the template the <code>form</code> is closed before any <code>input</code> elements are defined, therefore the form will not contain any of the data entered as part of the table.</p> <p>You can fix it by moving the <code>&lt;/form&gt;</code> closing tag to somewhere after the end of the table.</p> <p>Furthermor...
0
2016-08-06T05:08:31Z
[ "python", "html", "django", "django-forms" ]
My submit button in html template is not working in django
38,800,710
<p>I prepared an attendance register template in HTML.I have a HTML table and a submit button in the given HTML page.While clicking the submit button,i want to save the data in HTML table.But i can't.</p> <p>Ist std.html</p> <pre><code> {% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title...
0
2016-08-06T05:00:30Z
38,800,824
<p>You should not be manually generating your form like that in your html. I can see that you have already had a look at django forms. May I propose the following:</p> <pre><code>&lt;form name="demo_form.asp" method="post"&gt; {% csrf_token %} {{ form.as_p }} &lt;button type="submit" value="continue"&gt;Su...
1
2016-08-06T05:20:30Z
[ "python", "html", "django", "django-forms" ]
Install Python mysqlclient on Ubuntu docker container
38,800,723
<p>I want to install <a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">Python's mysqlclient</a> package on a Docker container running <a href="https://hub.docker.com/_/ubuntu/" rel="nofollow">Ubuntu</a>. The installation fails because I don't have gcc installed in the container:</p> <pre><code>x86_64-...
0
2016-08-06T05:01:58Z
38,800,828
<p>You can install the build dependencies, make the module, then remove them.</p> <p><a href="https://github.com/docker-library/redis/blob/8929846148513a1e35e4212003965758112f8b55/3.0/Dockerfile#L24" rel="nofollow">Redis is a good example</a> of how to build and cleanup in one step so you don't create a bulky image la...
0
2016-08-06T05:20:43Z
[ "python", "ubuntu", "docker" ]
Install Python mysqlclient on Ubuntu docker container
38,800,723
<p>I want to install <a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">Python's mysqlclient</a> package on a Docker container running <a href="https://hub.docker.com/_/ubuntu/" rel="nofollow">Ubuntu</a>. The installation fails because I don't have gcc installed in the container:</p> <pre><code>x86_64-...
0
2016-08-06T05:01:58Z
38,906,785
<p>I created a container and installed everything I needed to build mysqlclient. I downloaded the .tgz and used <code>python setup.py bdist_wheel</code> to generate the Wheel file. I copied over the wheel file to a directory mounted from my host machine, and installed it on the container where I wanted mysqlclient in...
0
2016-08-11T22:01:07Z
[ "python", "ubuntu", "docker" ]
How to split large txt file into small txt files by line using python
38,800,810
<p>I have a large txt file contains 1 million lines, I want to split them into small txt files each contains 10 lines, how to do it using python? I found some related questions and have code like this :</p> <pre><code>def split_file(filepath, lines=30): """Split a file based on a number of lines.""" path, fi...
-3
2016-08-06T05:17:32Z
38,806,953
<p>This should work. It's a little roundabout, but should circumvent your mystery error while being human readable.</p> <p>First let's define a couple of useful functions. The first reads a file and makes each line a list element, and the second writes lists as files.</p> <p>Note, the second function will create a ne...
0
2016-08-06T17:29:40Z
[ "python", "text", "split" ]
python 2.7 regular expression match with \r\n in string
38,800,817
<p>Wondering if any ways to match string contains <code>\r \n</code>? It seems the same regular expression match does not work if input string content contains <code>\r \n</code>. Using Python 2.7.</p> <p><strong>works pretty good</strong>,</p> <pre><code>import re content = '{(1) hello (1)}' reg = '{\(1\)(.*?)\(1\)...
0
2016-08-06T05:19:28Z
38,800,849
<p>This works:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; content = '{(1) hello \r\n (1)}' &gt;&gt;&gt; reg = '{\(1\)(.*?)\(1\)}' &gt;&gt;&gt; results = re.findall(reg, content, re.DOTALL) &gt;&gt;&gt; &gt;&gt;&gt; print results[0] hello &gt;&gt;&gt; &gt;&gt;&gt; prog = re.compile(reg, re.DO...
2
2016-08-06T05:23:56Z
[ "python", "regex", "python-2.7" ]
NameError: name 'driver' is not defined
38,800,908
<p>I use above code to scrape friend list from facebook UID and am getting an error: </p> <pre><code> File "C:\Users\Tn\PycharmProjects\untitled\test\1.py", line 15, in friend_uid_list soup = from_uid(uid) File "C:\Users\Tn\PycharmProjects\untitled\test\1.py", line 11, in from_uid driver.get('https://www.fa...
0
2016-08-06T05:34:09Z
38,801,204
<p>The reason is simple: <strong>You create some new processes, and it can't see the variables in another process(main process).</strong></p> <p>There are several solutions: </p> <ol> <li><p>Pass the variables you need as arguments. But this is not possible since <code>driver</code> is not picklable.</p></li> <li><p...
0
2016-08-06T06:21:06Z
[ "python", "python-3.x", "multiprocessing" ]
How to concat multiple functions in python
38,800,914
<p>How to do this in python?</p> <pre><code>def f(a, b): return a, b+2, b+3 def g(a, b, c): return a+b+c </code></pre> <p>How to get something like <code>k = f+g</code> hence that</p> <pre><code>k(a, b) is g(f(a,b)) </code></pre> <p>Note that this is an abstract question. I wonder whether there's a function ...
2
2016-08-06T05:35:23Z
38,800,945
<h3>Answer for original question</h3> <p>Define:</p> <pre><code>k = lambda x,y:g(*f(x,y)) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; k(2,3) 13 </code></pre> <h3>Answer for revised question</h3> <p>Define:</p> <pre><code>concat = lambda a,b:lambda *args: b(*a(*args)) </code></pre> <p>Example:</p> <pr...
4
2016-08-06T05:41:23Z
[ "python", "functools" ]
How to concat multiple functions in python
38,800,914
<p>How to do this in python?</p> <pre><code>def f(a, b): return a, b+2, b+3 def g(a, b, c): return a+b+c </code></pre> <p>How to get something like <code>k = f+g</code> hence that</p> <pre><code>k(a, b) is g(f(a,b)) </code></pre> <p>Note that this is an abstract question. I wonder whether there's a function ...
2
2016-08-06T05:35:23Z
38,801,006
<p>Why not define a third function as you did with <code>f</code> and <code>g</code>:</p> <pre><code>&gt;&gt;&gt; def f(a, b): return a, b+2, b+3 &gt;&gt;&gt; def g(a,b,c): return a+b+c &gt;&gt;&gt; def k(a,b): return g(*f(a,b)) &gt;&gt;&gt; k(2,3) 13 </code></pre>
1
2016-08-06T05:51:46Z
[ "python", "functools" ]
How to concat multiple functions in python
38,800,914
<p>How to do this in python?</p> <pre><code>def f(a, b): return a, b+2, b+3 def g(a, b, c): return a+b+c </code></pre> <p>How to get something like <code>k = f+g</code> hence that</p> <pre><code>k(a, b) is g(f(a,b)) </code></pre> <p>Note that this is an abstract question. I wonder whether there's a function ...
2
2016-08-06T05:35:23Z
38,801,609
<p>There are at least 2 approaches to do this:</p> <p>Approach A (recommended):</p> <pre><code>def compound(inner_func, outer_func): def wrapper(*args, **kwargs): return outer_func(*inner_func(*args, **kwargs)) return wrapper </code></pre> <p>Note that <code>inner_func</code> mustn't return a diction...
2
2016-08-06T07:15:48Z
[ "python", "functools" ]
Scrapy i/o block when downloading files
38,800,942
<p>I using Scrapy to scrapy a webside and download some files. Since the file_url I get will redirect to another url (302 redirect).So I use another method handle_redirect to get the redirected url. I custom the filespipeline like this.</p> <pre><code>class MyFilesPipeline(FilesPipeline): def handle_redirect(sel...
2
2016-08-06T05:41:17Z
38,810,558
<p>You use the <code>requests</code> API which is synchronous/blocking. This means that you turn your concurrency (<code>CONCURRENT_REQUESTS_PER_DOMAIN</code>) from (by default) 8, to effectively one. It seems like it dominates your delay. Nice trick the one you did on your second attempt. This doesn't use <code>reques...
0
2016-08-07T03:16:23Z
[ "python", "scrapy" ]
Python OOP Monty Hall not giving the expected results
38,800,946
<p>Trying out some OOP in python, I tried to create a Monty Hall Problem simulation that is giving odd results. I implement three different strategies that a player can choose from, either to stay with the first door selected, switch to the second closed door, or randomly choose between them.</p> <pre><code>import ra...
0
2016-08-06T05:41:30Z
38,801,574
<p>You're not playing the game correctly. After the contestant chooses a door, the host reveals a goat behind one of the other two doors, and then offers the contestant the opportunity to switch -- you're allowing a choice between three doors instead of two. Here's a revised <code>play()</code> function:</p> <pre><c...
1
2016-08-06T07:11:48Z
[ "python" ]
Jupyter Notebook does not work fully in Pycharm
38,800,953
<p>I am following <a href="https://confluence.jetbrains.com/display/PYH/Using+IPython+Notebook+with+PyCharm" rel="nofollow">these</a> steps to run IPython in the Pycharm IDE. On pressing <code>run</code> button in any cell, I do get below pop-up window</p> <p><a href="http://i.stack.imgur.com/ewupL.png" rel="nofollow"...
1
2016-08-06T05:42:54Z
38,801,082
<p>For the PyCharm Jupyter notebooks, to see results you need to open up a jupyter notebook. </p> <p>The reason why you don't just do all your code in Jupyter Notebooks is because Pycharm helps with LaTex integration and many more functions.</p>
0
2016-08-06T06:03:47Z
[ "python", "ipython", "pycharm", "jupyter", "jupyter-notebook" ]
Jupyter Notebook does not work fully in Pycharm
38,800,953
<p>I am following <a href="https://confluence.jetbrains.com/display/PYH/Using+IPython+Notebook+with+PyCharm" rel="nofollow">these</a> steps to run IPython in the Pycharm IDE. On pressing <code>run</code> button in any cell, I do get below pop-up window</p> <p><a href="http://i.stack.imgur.com/ewupL.png" rel="nofollow"...
1
2016-08-06T05:42:54Z
39,165,872
<p>I solved following:</p> <p>First I followed the reply to the <a href="https://github.com/ContinuumIO/anaconda-issues/issues/921" rel="nofollow">issue jupyter-notebook No such file or directory: 'conda'</a>, in short you should do:</p> <pre><code>conda update nb_conda nb_conda_kernels nb_anacondacloud </code></pre>...
1
2016-08-26T12:03:00Z
[ "python", "ipython", "pycharm", "jupyter", "jupyter-notebook" ]
Nginx debugging logging levels
38,800,991
<p>I followed <a href="https://www.digitalocean.com/community/tutorials/how-to-configure-logging-and-log-rotation-in-nginx-on-an-ubuntu-vps" rel="nofollow">these</a> instructions and enabled the error log within nginx.</p> <p>I was trying to test the log, I created a syntax error by removing a <code>:</code> at the en...
1
2016-08-06T05:48:48Z
38,801,069
<p>1) Disable nginx debug mode, it will eat your hdd. Nginx debug mode log purpose is to debug nginx itself, not your application errors.</p> <p>2) Don't look for errors in the wrong places, nginx error log has nothing to do with your application(flask)/middleware (uwsgi in your case) logs</p> <p>3) <a href="https://...
1
2016-08-06T06:01:54Z
[ "python", "nginx", "uwsgi", "error-log" ]
How to set focus in tkinter entry box
38,801,019
<p>have spent a while looking for an answer. I'm new to Python but not to coding in general. Finding the various versions quite challenging!</p> <p>Anyway I'm very Gui orientated and have managed to get tkinter working with Python 3.5.1</p> <p>Just playing with basics and have the following code but cannot set focus ...
-1
2016-08-06T05:53:48Z
38,801,587
<p>Every Tkinter widget has the <code>focus_set</code> method.</p> <p>The problem with your code is that the <code>.grid</code> method returns <code>None</code>. Thus </p> <pre><code>mEntry1 = Entry(textvariable=V1,width=10).grid(row=0,column=0,sticky=W) </code></pre> <p>sets <code>mEntry1</code> to <code>None</code...
1
2016-08-06T07:12:55Z
[ "python", "tkinter" ]
regex: find all asterisks without prepended backslashes
38,801,092
<p>I am building a regex that transforms <code>*asterisks*</code> into <code>&lt;b&gt;bold tags&lt;/b&gt;</code>, as a simpler version of Markdown. The regex looks like this:</p> <pre><code>markdown = '\*(?P&lt;name&gt;.+)\*' bold = '&lt;b&gt;\g&lt;name&gt;&lt;/b&gt;' text = 'abcdef *bold* ghijkl' print(re.sub(markdow...
1
2016-08-06T06:05:09Z
38,802,952
<p><strong>Problem 1a: Syntax Error</strong></p> <p>It's not working, because you have to escape the backslashes as well.</p> <pre><code>markdown = '[^\\\\]\*(?P&lt;name&gt;.+)[^\\\\]\*' </code></pre> <p>Or use <code>r''</code> to define a raw string.</p> <pre><code>markdown = r'[^\\]\*(?P&lt;name&gt;.+)[^\\]\*' </...
1
2016-08-06T09:57:20Z
[ "python", "regex" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for put...
0
2016-08-06T06:09:07Z
38,801,179
<p>As @thefourtheye noted <code>dict</code> might be better container. In case you want 2D list you could first add the values a intermediate <code>dict</code> where key is row and value is list of numbers. Then you could use list comprehension to generate the final result:</p> <pre><code>&gt;&gt;&gt; l = [[3,350],[4...
0
2016-08-06T06:17:30Z
[ "python", "list", "multidimensional-array", "indexing" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for put...
0
2016-08-06T06:09:07Z
38,801,181
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">pandas</a> module for this task:</p> <pre><code>In [186]: a = np.array([[3,350],[4,800],[0,150],[0,200],[4,750]]) In [187]: res = pd.DataFrame(a).groupby(0)[1].apply(list).to_frame('val').rename_axis('idx') In [188]: res O...
0
2016-08-06T06:17:44Z
[ "python", "list", "multidimensional-array", "indexing" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for put...
0
2016-08-06T06:09:07Z
38,801,187
<p>Try taking a look at list comprehensions, they provide a one-liner way of creating lists. If you don't know what they are this is a pretty decent guide to get you started <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">here</a>. Also, take a look at <code>tuple</code>'s, as they ...
1
2016-08-06T06:18:24Z
[ "python", "list", "multidimensional-array", "indexing" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for put...
0
2016-08-06T06:09:07Z
38,802,285
<p>There are numerious ways to do this. Here's a fairly straight-forward one:</p> <pre><code>a = [[3, 350], [4, 800], [0, 150], [0, 200], [4, 750]] rows, values = zip(*a) b = [[] for _ in range(max(rows)+1)] # initialize 2D output for i, row in enumerate(rows): b[row].append(values[i]) print(b) # -&gt; [[150, ...
0
2016-08-06T08:39:08Z
[ "python", "list", "multidimensional-array", "indexing" ]
how to convert the %3A and %2F to : and / in the url in python?
38,801,188
<p>How to convert the replace(%3A and %2F ...) in the url. <br><strong>URL</strong><br> <code>https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https%3A%2F%2Furl%2F%26TIME%3DFri%2520Aug%252005%25202016%252011%3A40%3A14%2520GMT%2B0530%28India%2520Standard%2520Time%29</code> <br><br> <strong>Required URL<...
0
2016-08-06T06:18:32Z
38,801,219
<p>Take a look at <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote" rel="nofollow">urllib.parse.unquote</a>: "Replace %xx escapes by their single-character equivalent."</p>
2
2016-08-06T06:23:01Z
[ "python", "python-3.x", "url" ]
how to convert the %3A and %2F to : and / in the url in python?
38,801,188
<p>How to convert the replace(%3A and %2F ...) in the url. <br><strong>URL</strong><br> <code>https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https%3A%2F%2Furl%2F%26TIME%3DFri%2520Aug%252005%25202016%252011%3A40%3A14%2520GMT%2B0530%28India%2520Standard%2520Time%29</code> <br><br> <strong>Required URL<...
0
2016-08-06T06:18:32Z
38,801,429
<p>In <code>python 2.7</code>, use <a href="https://docs.python.org/2/library/urllib.html#urllib.quote" rel="nofollow">urllib.unquote</a>:</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; urllib.unquote(urllib.unquote('https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https%3A%2F%2Furl%2F%26TIME%...
2
2016-08-06T06:52:25Z
[ "python", "python-3.x", "url" ]
How to run a process with timeout and still get stdout at runtime
38,801,202
<p>The need:</p> <ol> <li>Timeout after X seconds, and kill the process (and all the processes it opened) if timeout reached before the process ends gracefully.</li> <li>Read ongoing output at runtime.</li> <li>Work with processes that produce output, ones that don't, and ones that produce output, and then stop produc...
6
2016-08-06T06:20:45Z
38,868,895
<p>I would use asyncio for this kind of task.</p> <p>Read IO from the process like in this accepted anwser: <a href="http://stackoverflow.com/questions/24435987/how-to-stream-stdout-stderr-from-a-child-process-using-asyncio-and-obtain-its-e">How to stream stdout/stderr from a child process using asyncio, and obtain it...
4
2016-08-10T09:08:56Z
[ "python", "python-3.x", "timeout", "subprocess", "stdout" ]
How to run a process with timeout and still get stdout at runtime
38,801,202
<p>The need:</p> <ol> <li>Timeout after X seconds, and kill the process (and all the processes it opened) if timeout reached before the process ends gracefully.</li> <li>Read ongoing output at runtime.</li> <li>Work with processes that produce output, ones that don't, and ones that produce output, and then stop produc...
6
2016-08-06T06:20:45Z
38,880,667
<p>Use the 2 python script below.</p> <ul> <li><p>The <em>Master.py</em> will use <code>Popen</code> to start a new process and will start a watcher thread that will kill the process after <code>3.0</code> seconds.</p></li> <li><p>The slave must call the flush method if no newline in the data written to the <code>stdo...
0
2016-08-10T18:10:57Z
[ "python", "python-3.x", "timeout", "subprocess", "stdout" ]
Efficient group by and where clause in python
38,801,205
<p>I am having <strong>weekly( say 5 weeks)</strong> sales and baskets for <strong>product and store combination</strong>, i want to find the total spend and visits of product <strong>(irrespective of store)</strong> for a particular <strong>week(say 201520)</strong>" i.e. 20th week of year 2015. the moment i select a ...
1
2016-08-06T06:21:18Z
38,801,383
<p><strong>UPDATE2:</strong> adding new calculated multi-level column:</p> <pre><code>In [229]: x = res.sales / res.baskets In [230]: x Out[230]: week 201518 201519 201520 prod 122 90.9990 NaN NaN 123 5.0225 4.269048 85.933636 In [231]: x.columns = pd.MultiIndex.from_product(['spend_per_...
2
2016-08-06T06:45:09Z
[ "python", "python-3.x", "pandas" ]
Efficient group by and where clause in python
38,801,205
<p>I am having <strong>weekly( say 5 weeks)</strong> sales and baskets for <strong>product and store combination</strong>, i want to find the total spend and visits of product <strong>(irrespective of store)</strong> for a particular <strong>week(say 201520)</strong>" i.e. 20th week of year 2015. the moment i select a ...
1
2016-08-06T06:21:18Z
38,801,397
<p>I think the easiest and more "Pythonic" solution will involve at least two steps: groupby, then a merge. And you can do it as follows:</p> <pre><code># First create a container DataFrame to hold the data: columns = pd.MultiIndex.from_arrays([['a', 'b'], df[0].unique()]) output = pd.DataFrame(columns=columns) # The...
0
2016-08-06T06:47:48Z
[ "python", "python-3.x", "pandas" ]
Efficient group by and where clause in python
38,801,205
<p>I am having <strong>weekly( say 5 weeks)</strong> sales and baskets for <strong>product and store combination</strong>, i want to find the total spend and visits of product <strong>(irrespective of store)</strong> for a particular <strong>week(say 201520)</strong>" i.e. 20th week of year 2015. the moment i select a ...
1
2016-08-06T06:21:18Z
38,801,480
<p>You can also get what you need using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table</a>, although it's a little different approach, <em>but you were looking for a one line code</em>:</p> <pre><code>print(pd.pivot_table(df, index = 'week', columns =...
3
2016-08-06T06:56:52Z
[ "python", "python-3.x", "pandas" ]
Pytest: Update a global variable in test
38,801,234
<p>I am new to Python and am using pytest for testing</p> <p>I am executing the pytest from within the python script. I have a global variable in the script which I modify based on the result in the test. The updated global variable is again used after the tests are executed.</p> <pre><code>import pytest global test_...
0
2016-08-06T06:24:45Z
38,802,415
<p>pytest is designed to be called from command line, not from inside your test script. Your global variable does not work, because pytest imports your script as module, which has it's own namespace.</p> <p>To customize the report generation, use the post-process-hook: <a href="http://doc.pytest.org/en/latest/example/...
0
2016-08-06T08:56:20Z
[ "python", "python-2.7", "py.test", "pytest-django" ]
Pytest: Update a global variable in test
38,801,234
<p>I am new to Python and am using pytest for testing</p> <p>I am executing the pytest from within the python script. I have a global variable in the script which I modify based on the result in the test. The updated global variable is again used after the tests are executed.</p> <pre><code>import pytest global test_...
0
2016-08-06T06:24:45Z
38,810,233
<p>This can be solved using the exit code return when calling <strong>pytest.main()</strong> The global variable is not necessary</p> <pre><code>import pytest def test_toggle(): a = True b = True c = True if a == b else False assert c def test_switch(): one = True two = False three = Tru...
0
2016-08-07T01:59:13Z
[ "python", "python-2.7", "py.test", "pytest-django" ]
Is there a way to convert multiple date formats into datetime python
38,801,516
<p>Is there an easy way to convert multiple date formats into a datetime object in python? Eventually these will be inserted into a MySQL database with type DATE.</p> <p>Examples of what type of data I might be receiving:</p> <p>August 2, 2008</p> <p>04-02-2007</p> <p>May 2014</p> <p>Converted I would like these t...
0
2016-08-06T07:02:05Z
38,801,552
<p>Use the third party <a href="http://labix.org/python-dateutil" rel="nofollow">dateutil</a> library:</p> <pre><code>&gt;&gt;&gt; from dateutil import parser &gt;&gt;&gt; parser.parse("August 2, 2008") datetime.datetime(2008, 8, 2, 0, 0) &gt;&gt;&gt; parser.parse("04-02-2007") datetime.datetime(2007, 4, 2, 0, 0) &gt;...
3
2016-08-06T07:08:11Z
[ "python", "mysql", "datetime" ]
Is there a way to convert multiple date formats into datetime python
38,801,516
<p>Is there an easy way to convert multiple date formats into a datetime object in python? Eventually these will be inserted into a MySQL database with type DATE.</p> <p>Examples of what type of data I might be receiving:</p> <p>August 2, 2008</p> <p>04-02-2007</p> <p>May 2014</p> <p>Converted I would like these t...
0
2016-08-06T07:02:05Z
39,757,592
<p>You might also want to checkout <a href="https://pypi.python.org/pypi/dateparser" rel="nofollow">dateparser</a>:</p> <pre><code>&gt;&gt;&gt; import dateparser &gt;&gt;&gt; dates = ['August 2, 2008', '04-02-2007', 'May 2014'] &gt;&gt;&gt; [dateparser.parse(d, settings={'PREFER_DAY_OF_MONTH': 'first'}).strftime('%Y-%...
0
2016-09-28T21:01:43Z
[ "python", "mysql", "datetime" ]
Functioning of append in dictionary?
38,801,672
<p>Please explain the use of <code>append</code> function in the following example:</p> <p>Example 1:</p> <pre><code>new = {} for (key, value) in data: if key in new: new[key].append( value ) else: new[key] = [value] </code></pre> <p>and in example 2:</p> <pre><code>new = {} for (key, value)...
1
2016-08-06T07:23:34Z
38,801,719
<p><code>new</code> is a dictionary, but the dictionary’s value are lists, which have the <a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>list.append()</code></a> method.</p> <p>In the loop, the dictionary is being filled with the values from <code>data</code>. A...
1
2016-08-06T07:30:31Z
[ "python" ]
How to know when creating set or frozenset
38,801,695
<p>I am new to Python. I am reading Building Skills in Python (<em>Lott</em>) and trying out some examples. I see that the <code>set(iterable)</code> function creates both a mutable set and an immutable frozenset. How do I know if I am creating a set or a frozenset?</p>
1
2016-08-06T07:26:36Z
38,801,805
<p>That is simply incorrect. The <a href="https://docs.python.org/2/library/functions.html#func-set" rel="nofollow"><code>set()</code></a> built-in returns a set, not a frozenset. <a href="https://docs.python.org/2/library/functions.html#func-frozenset" rel="nofollow"><code>frozenset()</code></a> returns a frozenset. A...
2
2016-08-06T07:41:13Z
[ "python", "python-2.7" ]
how to make a different conditions with one input (python)
38,801,851
<p>Can anyone help me with this coding?</p> <p>I want to insert a RFID card data to a MySQL database. When i first tap the tag on RFID Reader, the program will insert the data to Masuk table When i tap the tag again, the program will insert the data to Keluar table.</p> <p>Am i doing right with this code?</p> <pre><...
0
2016-08-06T07:48:29Z
38,803,580
<p>all you need is something like this.create a global variable(count) to achieve the behavior with <code>if and elif</code> condition like </p> <pre><code> if (count==True): # insert into musak and update count to false elif(count==False): # insert into other table and update count to True </code></pre...
0
2016-08-06T11:08:15Z
[ "python", "mysql", "database", "raspberry-pi", "rfid" ]
how to make a different conditions with one input (python)
38,801,851
<p>Can anyone help me with this coding?</p> <p>I want to insert a RFID card data to a MySQL database. When i first tap the tag on RFID Reader, the program will insert the data to Masuk table When i tap the tag again, the program will insert the data to Keluar table.</p> <p>Am i doing right with this code?</p> <pre><...
0
2016-08-06T07:48:29Z
38,864,616
<p>see the code to access and modify the global variable</p> <pre><code>global count def modi(): global count # required to modify the global copy count=10 def printc(): if (count==10): # read it as a normal variable print("yes") modi() printc() </code></pre>
0
2016-08-10T05:03:44Z
[ "python", "mysql", "database", "raspberry-pi", "rfid" ]
kill python thread while it waits for read for a long time
38,802,014
<p>I need to terminate thread but can't check regularly any flags since it waits for reading/input.</p> <p>Simple example:</p> <pre><code>import threading, time class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): print(input("wainting for input: "...
0
2016-08-06T08:07:37Z
38,802,275
<p>Here's an example, how you can solve your hanging process problem with <code>select</code>:</p> <pre><code>import threading import select import subprocess import sys def watch_output(args, timeout): process = subprocess.Popen(args, stdout=subprocess.PIPE) while True: ready_to_read, _, _ = sel...
1
2016-08-06T08:36:48Z
[ "python", "multithreading" ]
kill python thread while it waits for read for a long time
38,802,014
<p>I need to terminate thread but can't check regularly any flags since it waits for reading/input.</p> <p>Simple example:</p> <pre><code>import threading, time class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): print(input("wainting for input: "...
0
2016-08-06T08:07:37Z
38,802,300
<p>You can just have the main thread kill the process. The reader thread will eventually hit EOF and then exit.</p> <p>Example:</p> <pre><code>#!/usr/bin/env python import threading import subprocess import time import sys def pipe_thread(handle): print "in pipe_thread" x = handle.readline() while x: prin...
0
2016-08-06T08:41:07Z
[ "python", "multithreading" ]
Spark UDF that takes in unknown number of columns
38,802,054
<p>I have a list of spark dataframes with different schemas. Example: </p> <pre><code>list_df = [df1, df2, df3, df4] # df1.columns = ['a', 'b'] # df2.columns = ['a', 'b', 'c'] # df3.columns = ['a', 'b', 'c', 'd'] # df4.columns = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>Now, I want to write a single udf that is able...
1
2016-08-06T08:12:36Z
38,803,457
<p>Actually this approach works just fine in Python:</p> <pre><code>from pyspark.sql.functions import array, udf df = sc.parallelize([("a", "b", "c", "d")]).toDF() f = udf(lambda xs: "+".join(xs)) df.select(f("_1")).show() ## +------------+ ## |&lt;lambda&gt;(_1)| ## +------------+ ## | a| ## +-----------...
2
2016-08-06T10:54:17Z
[ "python", "apache-spark", "dataframe", "pyspark", "udf" ]
For loop queryset from inline model
38,802,097
<p>have a model and and inline model.. I need to create a queryset which retrieves data from the inline model and returns a for loop in a template..Looks like my code is not working though..can anyone help?</p> <pre><code>class Account(models.Model): uuid = ShortUUIDField(unique=True) name = models.CharField(m...
2
2016-08-06T08:17:06Z
38,804,557
<blockquote> <p>My for loop should retrieve all rates in case account name is XXX</p> </blockquote> <p>Then this:</p> <pre><code>'rates': Account.objects.filter(name__name__icontains='xxx) </code></pre> <p>Should be like this</p> <pre><code>'rates': Rates.objects.filter(name__name='XXX') </code></pre> <p>OR if...
1
2016-08-06T13:02:19Z
[ "python", "django-models" ]
Adding BioNetGen to Anaconda environment
38,802,101
<p>I am trying to use <a href="http://docs.pysb.org/en/latest/" rel="nofollow">PySB</a> with Anaconda3 and Windows7. I have added the relevant depedencies (numpy, scipy, sympi, perl) to a working environment. However I am struggling with the BioNetGen program. I have downloaded it, and added the path to BNG, but I cann...
0
2016-08-06T08:17:39Z
38,807,164
<p>Yes, BioNetGen itself is written in Perl and thus can't be installed via pip or other Python package managers. You need to download the <a href="http://www.bionetgen.org/index.php/BioNetGen_Distributions" rel="nofollow">BioNetGen command-line interface</a> for your platform and then follow the instructions in the <a...
0
2016-08-06T17:52:04Z
[ "python", "anaconda", "pysb" ]
How to index a tensor using arrays?
38,802,258
<p>Suppose I have a 3D array (tensor)</p> <pre><code>print a.shape (100, 100, 100) </code></pre> <p>and want to index its first axis using one array:</p> <pre><code>print i.shape (20,) </code></pre> <p>and its last axis using another array</p> <pre><code>print j.shape (30,) </code></pre> <p>My intent is to get a ...
0
2016-08-06T08:35:39Z
38,802,289
<p><strong>Approach #1 :</strong> You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html" rel="nofollow"><code>np.ix_</code></a> for getting such meshes of indices and simply indexing into the input array must give you the desired output. Thus, an implementation would be like so -</p> ...
1
2016-08-06T08:40:02Z
[ "python", "python-2.7", "numpy", "slice" ]
ValueError unknown label type array sklearn- load_boston
38,802,537
<p>I am using the following code to check SGDClassifier</p> <pre><code>import numpy as np from sklearn.datasets import load_boston from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import tr...
0
2016-08-06T09:09:57Z
38,802,710
<p>In classification tasks, the dependent variable (or the <em>target</em>) is categorical. We try to predict if a claim is fraudulent or not, for example. In regression, on the other hand, the dependent variable is numerical. It can be measured. </p> <p>In the Boston Housing dataset, the dependent variable is <em>"Me...
2
2016-08-06T09:30:25Z
[ "python", "scikit-learn" ]
Removing duplicates if paired adjacently
38,802,590
<p>Deleting any pair of <strong>adjacent</strong> letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.</p> <p>Sample input = aaabccddd <br/> Sample output = abd</p> <p>Confused how to iterate the list or the string in a way to match the duplicates and removing them...
0
2016-08-06T09:16:02Z
38,802,724
<p>Removing paired letters can be reduced to reducing runs of letters to an empty sequence if there are an even number of them, 1 if there are an odd number. <code>aaaaaa</code> becomes empty, <code>aaaaa</code> is reduced to <code>a</code>.</p> <p>To do this on any sequence, use <a href="https://docs.python.org/2/lib...
1
2016-08-06T09:31:09Z
[ "python", "arrays", "string", "list" ]
Removing duplicates if paired adjacently
38,802,590
<p>Deleting any pair of <strong>adjacent</strong> letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.</p> <p>Sample input = aaabccddd <br/> Sample output = abd</p> <p>Confused how to iterate the list or the string in a way to match the duplicates and removing them...
0
2016-08-06T09:16:02Z
38,802,785
<p>You can use stack in order to achieve <strong>O(n)</strong> time complexity. Iterate over the characters in a string and for each character check if the top of stack contains the same character. In case it does pop the character from stack and move to next item. Otherwise push the character to the stack. Whatever re...
1
2016-08-06T09:37:39Z
[ "python", "arrays", "string", "list" ]
Unit test failing after moving functions into a class
38,802,595
<p>I'm trying to write a unit test for a function within a class but I'm having a little trouble. Before moving the importer function into a class, this test worked. However, now I get <code>TypeError: grab_column_locations missing 1 required positional argument: 'sheet'</code>. The importer function itself is correctl...
-1
2016-08-06T09:16:23Z
38,804,498
<p>The error message says this:</p> <pre><code>TypeError: grab_column_locations missing 1 required positional argument: 'sheet' </code></pre> <p>This sounds like the function signature is:</p> <pre><code>def grab_column_locations(self, sheet): </code></pre> <p>Are you not calling it from an <strong>instance</strong...
0
2016-08-06T12:54:04Z
[ "python", "unit-testing" ]
Using JSON with AJAX and Python database
38,802,638
<p>I am new to python and am trying to access the db though python and return some results in a JSON array using AJAX.<br> I test it by returning a JSON list and alerting it using js. it works when I don't use the db connection but as soon as I add it the js alert stops too. the db connection seems to work properly whe...
1
2016-08-06T09:22:50Z
38,803,837
<p>In <strong>webairdb.py</strong> you write to <code>sys.stdout</code> (that is what <code>print</code> does) - putting effectively breaking the json output. (You might want to have a look at the output by pressing F12 in your browser)</p> <p>So just remove it and either write to <code>sys.stderr</code> or use <a hre...
0
2016-08-06T11:36:08Z
[ "javascript", "python", "json", "ajax", "database" ]
how to get two inputs and accessing to objects and methods of a class?
38,802,726
<p>I wrote this code to access an object via user input. It works with locals (I know I can make dictionary too) </p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs redfire = Dragon(2, 4) dic1 =...
-1
2016-08-06T09:31:15Z
38,802,871
<p>You are not using class method rightly :</p> <pre><code>redfire = Dragon(2, 4) dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} </code></pre> <p>In fact, in your class function definition: <code>def sum(self):</code>, self refer to an object of the class.</p> <p>You should then use it like ...
0
2016-08-06T09:47:43Z
[ "python", "class", "python-3.x", "methods", "input" ]
how to get two inputs and accessing to objects and methods of a class?
38,802,726
<p>I wrote this code to access an object via user input. It works with locals (I know I can make dictionary too) </p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs redfire = Dragon(2, 4) dic1 =...
-1
2016-08-06T09:31:15Z
38,803,423
<p>There's no point storing the methods in the dictionary: they're already stored in the Dragon class itself. As jonrsharpe mentions in the comments, you can use the built-in <code>getattr</code> function to retrieve an attribute of a class instance; that applies to methods like your <code>sum</code> and <code>mul</cod...
0
2016-08-06T10:49:18Z
[ "python", "class", "python-3.x", "methods", "input" ]
how to get two inputs and accessing to objects and methods of a class?
38,802,726
<p>I wrote this code to access an object via user input. It works with locals (I know I can make dictionary too) </p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs redfire = Dragon(2, 4) dic1 =...
-1
2016-08-06T09:31:15Z
38,804,242
<p>Thanks so much everbody especially jonrsharp and PM 2Ring for mentioning getattr() function . code below is what i was seeking for </p> <pre><code>class Dragon: def __init__(self,head,tail): self.head=head self.tail=tail def sum(self): return (self.head + self.tail) class Snake: ...
0
2016-08-06T12:20:18Z
[ "python", "class", "python-3.x", "methods", "input" ]
Importing module with "current-directory" imports
38,802,908
<p>I have the following code to load a module dynamically:</p> <pre><code>def load_module(absolute_path): import importlib.util module_name, _ = os.path.splitext(os.path.split(absolute_path)[-1]) try: py_mod = imp.load_source(module_name, absolute_path) except ImportError: module_root =...
0
2016-08-06T09:52:09Z
38,804,371
<p>It doesn't really matter that this you are using dynamic importing here; the same problem applies to any code making assumptions about the current directory being on the path. It is the responsibility of those scripts to ensure that the current directory is on the path themselves.</p> <p>Rather than use <code>'.'</...
1
2016-08-06T12:36:01Z
[ "python", "import", "python-3.5", "python-importlib" ]
Translate/Rotate 2D points to change perspective
38,802,990
<p>I am recording a video of a users eye, and then using computer vision to track their eyes in an attempt to estimate their gaze, however the angle I am able to record the user at is not straight on and the representation of the data needs to be displayed, as if the user is looking straight on.</p> <p>To explain myse...
5
2016-08-06T10:00:23Z
38,831,587
<p>My matrix math is worse than "fairly rusty," but I've got a few ideas that could be helpful.</p> <p>Overall, there's a lot more information on transforming images than transforming discrete points. You may want to look into transforming the eye portion of your image rather than transforming the pupil points.</p> <...
4
2016-08-08T14:15:25Z
[ "python", "numpy", "2d", "matrix-multiplication", "perspectivecamera" ]
Reading spcific columns out of file
38,802,991
<p>I am having a problem reading big (300008 lines) output file of simulation code. I am using this function to read two columns of the file </p> <pre><code>def read2(filename,i1,i2): "Read 2 ARRAYS from the i1-th and i2-th columns of a text file" from numpy import * # import numpy package f...
0
2016-08-06T10:00:35Z
38,804,041
<p>When you <code>len(f.readlines())</code>, the it comes to the end of the file, so <code>f.readline()</code> starts from the end of file every time. You get empty string all the time.</p>
0
2016-08-06T11:57:28Z
[ "python", "string", "list", "python-2.7", "numpy" ]
How to sum Threads in python
38,803,050
<p>I need help on how i can sum all the threads.to get sum of thread one to three all together..The parallel program should use all processors in host computer</p> <pre><code>import threading import time from datetime import datetime start_time = datetime.now() def sum_number(): summ = 100 for num in range (1,...
0
2016-08-06T10:06:15Z
38,803,360
<p>You can do</p> <pre><code>import time import multiprocessing.dummy as mp # uses threads instead of full processes def sum_range(start_stop): start,stop=start_stop return sum(range(start,stop)) if __name__=="__main__": start_time=time.perf_counter() with mp.Pool() as p: my_sums=p.map(sum_ra...
0
2016-08-06T10:40:53Z
[ "python", "multithreading", "python-3.x", "parallel-processing", "multiprocessing" ]
indentation error on If Statement
38,803,093
<pre><code>if mssge &lt;= answr: print("Too High, Try Again") elif mssge &gt;= answr: print("Too Low, Try Again") else: print("Nice Job! R to play again; Q to quit") if event.type == pygame.Q: sys.exit() else event.type == pygame.R: break gotoline(7) </code></pr...
-1
2016-08-06T10:10:49Z
38,803,112
<p>You cannot have conditions in the <code>else</code>-statement. <code>Else</code> is supposed to catch every case which is <strong>not</strong> caught by the preceding <code>if/elifs</code>.</p> <p>Your first code-block should be</p> <pre><code>if message_1 &lt;= rand_numb: print("Too High, Try Again") elif me...
0
2016-08-06T10:12:59Z
[ "python", "if-statement", "indentation" ]
indentation error on If Statement
38,803,093
<pre><code>if mssge &lt;= answr: print("Too High, Try Again") elif mssge &gt;= answr: print("Too Low, Try Again") else: print("Nice Job! R to play again; Q to quit") if event.type == pygame.Q: sys.exit() else event.type == pygame.R: break gotoline(7) </code></pr...
-1
2016-08-06T10:10:49Z
38,803,126
<p>An <code>else</code> clause doesn't take a condition. You could either write it as an <code>elif</code> clause, or as a straight-forward <code>else.</code> Note, BTW, that you should remove the <code>=</code> from the first two conditions to make the code correct:</p> <pre><code>if message_1 &lt; rand_numb: # &...
2
2016-08-06T10:15:01Z
[ "python", "if-statement", "indentation" ]
Python, have a process run in the background and get status from the main thread
38,803,153
<p>this is a noob question, I have never done much in Python. I need to have a main process run and do stuff, while a background process does other calculations and saves the result to a variable. When the main thread wants, it should be able to read the last value stored in the variable: every value stored before is f...
1
2016-08-06T10:18:33Z
38,803,231
<p>Use <a href="https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">multiprocessing.Value</a>, which is implemented with shared memory between the processes:</p> <pre><code>from multiprocessing import Process, Value import time def f(n): while True: n.val...
2
2016-08-06T10:26:38Z
[ "python", "multiprocessing" ]
Uploading multiple files with Flask App Builder
38,803,257
<p>Creating a simple front end with Flask where I can select multiple files and runs some calculations on them. </p> <p>Currently I am using the code below, but it is only good for 1 file, <code>#do something</code> is where the conversion happens;</p> <pre><code>class Sources(SimpleFormView): form = MyForm f...
0
2016-08-06T10:29:18Z
38,804,331
<p>You can use this HTML form which will allow the user to select multiple files:</p> <pre><code>&lt;form method="POST" enctype="multipart/form-data" action="/upload"&gt; &lt;input type="file" name="file[]" multiple=""&gt; &lt;input type="submit" value="Upload Files"&gt; &lt;/form&gt; </code></pre> <p>Then in you...
0
2016-08-06T12:32:04Z
[ "python", "html", "flask", "flask-wtforms", "flask-appbuilder" ]
Sign extending from a variable bit width
38,803,320
<p>Here is a code in C++:</p> <pre><code>#include &lt;iostream&gt; #include&lt;limits.h&gt; using namespace std; void sign_extending(int x,unsigned b) { int r; // resulting sign-extended number int const m = CHAR_BIT * sizeof(x) - b; r = (x &lt;&lt; m) &gt;&gt; m; cout &lt;&lt; r; } void Run() { unsig...
2
2016-08-06T10:35:53Z
38,803,993
<p>you can use</p> <pre><code>def sign_extending(x, b): if x&amp;(1&lt;&lt;(b-1)): # is the highest bit (sign) set? (x&gt;&gt;(b-1)) would be faster return x-(1&lt;&lt;b) # 2s complement return x </code></pre>
2
2016-08-06T11:52:04Z
[ "python", "c++", "ctypes", "sign-extension" ]
Decorator not working correctly
38,803,385
<p>I'm trying to get my decorator working but I keep getting returned with</p> <pre><code>TypeError: command() takes 1 positional argument but 2 were given </code></pre> <p>I'm not sure what is happening, is someone able to explain to me what I'm doing wrong?</p> <p><strong>Decorator Code</strong></p> <pre><code>de...
0
2016-08-06T10:43:51Z
38,803,412
<p>You are decorating with <code>bot.command</code>.</p> <p>If <code>bot</code> is an object, then <code>bot.command</code> is a method and is called with a <code>self</code> parameter before the <code>command</code> argument, hence the “2 were given”.</p>
0
2016-08-06T10:47:37Z
[ "python", "python-3.x" ]
python multiprocessing.Process's join can not end
38,803,425
<p>I'm going to write a program which has multiple process(CPU-crowded) and multiple threading(IO-crowded).(the code below just a sample, not the program)</p> <p>But when the code meet the <code>join()</code> ,it make the program become a deadlock.</p> <p>My code is post below</p> <pre><code>import requests import t...
2
2016-08-06T10:49:24Z
38,928,677
<p>I finally find the reason. As you can see, I import the <code>Queue</code> from the <code>multiprocessing</code>, so the <code>Queue</code> should only used for <strong>Process</strong>, but I make the <strong>Thread</strong> access the <code>Queue</code> on my code, so it must something unknown occur behind the pro...
0
2016-08-13T02:41:09Z
[ "python", "multiprocessing" ]
Py2app: A main script could not be located in the Resources folder
38,803,437
<p>I am building a GUI tkinter python3 application and attempting to compile it with py2app. For some reason when I try to launch the .app bundle in the dist folder it gives me this error:<br> <i>A main script could not be located in the Resources folder</i><br> I was wondering why it is doing this, as it is rather fru...
0
2016-08-06T10:51:22Z
39,367,323
<p>In your "setup.py" file that you used to create the application, did you remember to list all the modules used in your code. For example, if you used the OS and Glob modules, then you would add this to your setup.py next to "OPTIONS":</p> <pre><code>OPTIONS = {'argv_emulation': True, 'includes':['glob', 'os']} </co...
0
2016-09-07T10:24:16Z
[ "python", "user-interface", "tkinter", "py2app" ]
Py2app: A main script could not be located in the Resources folder
38,803,437
<p>I am building a GUI tkinter python3 application and attempting to compile it with py2app. For some reason when I try to launch the .app bundle in the dist folder it gives me this error:<br> <i>A main script could not be located in the Resources folder</i><br> I was wondering why it is doing this, as it is rather fru...
0
2016-08-06T10:51:22Z
39,405,027
<p>I actually figured out: a bit of a stupid mistake, but since I'm using python 3.x I have to type in <code>python3</code> before doing it.</p>
0
2016-09-09T06:21:21Z
[ "python", "user-interface", "tkinter", "py2app" ]
how to interrogate ontology with sparql, rdflib in python
38,803,464
<p>I have developed my own ontology (I defined my classes, properties, etc.) and I want to interrogate my ontology with sparql. </p> <p>in protégé 2000 (open-source ontology editor) everything works fine, but when I want to implement my request sparql in python I encountered some problems.</p> <p>I did it in Java ...
0
2016-08-06T10:54:56Z
38,817,186
<p>Look at this if you want to use Jena Fuseki. <a href="http://stackoverflow.com/questions/7634618/jena-tdb-in-python">Jena TDB in Python?</a></p> <p>I can suggest a way to use rdflib. My work with rdflib has been limited to simple queries and serialization. The simplest way would be to load your graph ( in any of th...
0
2016-08-07T18:22:59Z
[ "python", "sparql", "jena", "rdflib", "pyjnius" ]
Expire index in mongoDB based on condition
38,803,658
<p>I have <code>boolean</code> field named <code>pending</code> in <code>Mongoengine</code> model in Python. I want the document to be removed after 1 hour only if <code>pending=True</code>. If I needed to remove the document after 1 hour unconditionally I would just set expire index. Is there some smart and easy way t...
1
2016-08-06T11:15:19Z
38,803,774
<p>I am afraid it is not directly possible to add some custom logic to the periodic cleaning of expired documents but as described in the <a href="https://docs.mongodb.com/manual/core/index-ttl/#expiration-of-data" rel="nofollow">docs</a> you could use a expire index and only set the indexed field from your application...
1
2016-08-06T11:29:27Z
[ "python", "mongodb", "mongoengine", "ttl" ]
Cannot import hachoir_core in python
38,803,753
<p>I can't import <code>hachoir_core</code> (or <code>hachoir_parser</code>, or <code>hachoir_metadata</code>) in python anymore (I used to be able to just a day ago):</p> <pre><code>ImportError: No module named hachoir_core </code></pre> <p>I've tried uninstalling all three (core, parser and metadata) with <code>pip...
1
2016-08-06T11:27:05Z
38,803,850
<p>Press Command+Space and type Terminal and press enter/return key. Run in Terminal app:</p> <pre><code>ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" &lt; /dev/null 2&gt; /dev/null </code></pre> <p>and press enter/return key. Wait for the command to finish. Run:</p> <pre>...
1
2016-08-06T11:36:55Z
[ "python", "pip", "anaconda" ]
Google Challenge Dilemma, Insights into possible errors?
38,803,824
<p>I am currently passing 4 of the 5 hidden test cases for this challenge and would like some input</p> <p>Quick problem description:</p> <blockquote> <p>You are given two input strings, String chunk and String word</p> <p>The string "word" has been inserted into "chunk" some number of times</p> <p>The ta...
0
2016-08-06T11:34:49Z
38,963,429
<p>I am not sure. But i will avoid matching first and last character of chunk. Should replace all other.</p>
0
2016-08-15T21:35:22Z
[ "java", "python", "string", "challenge-response" ]
How to optimize searching multiple strings ("needles") in one string ("haystack"), in python
38,803,945
<p>I need to know if either/all needle are found in a haystack. I assume there's a way to optimize the time for searching. For example:</p> <pre><code>haystack = "xxxxxefgyyy" needles = [ 'ezz', 'efg', 'eee', 'b', ... ] </code></pre> <p>In this example an optimized method would probably sort the needles by first let...
0
2016-08-06T11:45:45Z
38,804,175
<p>Maybe there is a more efficient implementation for that but you can simply use <a href="https://docs.python.org/3/library/re.html" rel="nofollow">re</a>. For a really big <code>needles</code> this might not be ideal - don't know where "really big" starts.</p> <pre><code>import re haystack = "xxxxxefgyyy" needles ...
-1
2016-08-06T12:12:13Z
[ "python", "search", "optimization" ]
Why does this for loop only work if it iterates at the zeroth index?
38,803,987
<p>I have a list:</p> <pre><code>oldlist = ['do gs\n','ca ts\n','monk eys\n','fro gs\n','\n','lio ns\n','tige rs\n','she ep\n'] </code></pre> <p>I'm trying to extract only the <strong>first</strong> portion of the list <strong>['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n']</strong> before the newline <stron...
0
2016-08-06T11:51:40Z
38,804,059
<p>The <code>in</code> operator when used on strings checks if a given character exists at all in the string. So <code>\n in "do gs\n"</code> evaluates to true, because there is a newline character in this string. However, if you check for <code>\n in "do gs\n"[0]</code> it only checks if the first character is the new...
2
2016-08-06T11:59:30Z
[ "python", "loops", "python-3.x", "for-loop", "iteration" ]
Why does this for loop only work if it iterates at the zeroth index?
38,803,987
<p>I have a list:</p> <pre><code>oldlist = ['do gs\n','ca ts\n','monk eys\n','fro gs\n','\n','lio ns\n','tige rs\n','she ep\n'] </code></pre> <p>I'm trying to extract only the <strong>first</strong> portion of the list <strong>['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n']</strong> before the newline <stron...
0
2016-08-06T11:51:40Z
38,804,075
<p>Your <code>iter[0]</code> means the first character in each string while <code>iter</code> means each full string. eg <code>'do gs\n'[0]</code> means <code>'d'</code> and of course in <code>'do gs\n'</code> there is a <code>'\n'</code>.</p> <p>You can also use the shorter <code>newlist=oldlist[:oldlist.index("\n")]...
0
2016-08-06T12:01:18Z
[ "python", "loops", "python-3.x", "for-loop", "iteration" ]
Kivy SQLalchemy and Android, No module named MySQLdb
38,803,988
<p>I'm building an app for android and i need to interact with Mysql database. I have some problem at configuring access from android but not with my linux installation. </p> <p>I have succesfully imported the recipe of SQLAlchemy on my android apk but when i run the app trough logcat i see the error:</p> <pre><code>...
0
2016-08-06T11:51:43Z
38,813,571
<p>I answer to my own question hoping someone will find it usefull.</p> <p>I find out how to solve it, use as a dialer mysql+mysqlconnector like:</p> <pre><code>engine = create_engine('mysql+mysqlconnector://user00:psw@localhost:3306/database') </code></pre> <p>and adds the recipe requirements in the buildozer.spec:...
0
2016-08-07T11:17:49Z
[ "android", "python", "mysql", "buildozer" ]
Kivy SQLalchemy and Android, No module named MySQLdb
38,803,988
<p>I'm building an app for android and i need to interact with Mysql database. I have some problem at configuring access from android but not with my linux installation. </p> <p>I have succesfully imported the recipe of SQLAlchemy on my android apk but when i run the app trough logcat i see the error:</p> <pre><code>...
0
2016-08-06T11:51:43Z
39,254,396
<blockquote> <p>kivy -m pip install mysql-connector </p> </blockquote> <p>than: </p> <blockquote> <p>import mysql.connector</p> </blockquote> <p>working for me :)</p>
0
2016-08-31T16:11:37Z
[ "android", "python", "mysql", "buildozer" ]
How to have several handlers using Logbook?
38,804,018
<p>I'm using <a href="https://logbook.readthedocs.io/" rel="nofollow">logbook</a> to log message in a Python app but</p> <pre><code>import logbook from logbook import Logger, StreamHandler, NullHandler log = Logger('LogbookExample') import sys StreamHandler(sys.stdout).push_application() NullHandler().push_applica...
3
2016-08-06T11:55:12Z
38,818,189
<p>The problem here is choosing <code>NullHandler</code>. It acts as a "black hole", swallowing all logs and not propagating them up the stack.</p> <p>Stacking non-<code>NullHandler</code>s is easy:</p> <pre><code>StreamHandler(sys.stdout).push_application() StreamHandler(sys.stderr, bubble=True).push_application() <...
1
2016-08-07T20:21:56Z
[ "python", "logging", "logbook" ]
Issue in django proejct with two version of python installed on centos server
38,804,103
<p>Working on django1.9 project, the issue is that default python installed on my server is 2.6 and i have to use python 2.7 for django 1.9. I have installed python2.6 on server. And while creating django projected i hve created it using virtual environment with python2.7 but whenever i am trying to access project it g...
0
2016-08-06T12:04:01Z
38,813,220
<p>Your mod_wsgi is compiled for Python 2.6. You cannot make it use a virtual environment for Python 2.7 and wouldn't be able to use it with application code which requires Python 2.7. You need to reinstall mod_wsgi with it recompiled for Python 2.7.</p>
0
2016-08-07T10:30:57Z
[ "python", "django" ]
mapping over 2 numpy.ndarray simultaneously
38,804,186
<p>Here's the problem. Let's say I have a matrix A =</p> <pre><code>array([[ 1., 0., 2.], [ 0., 0., 2.], [ 0., -1., 3.]]) </code></pre> <p>and a vector of indices p = <code>array([0, 2, 1])</code>. I want to turn a 3x3 matrix A to an array of length 3 (call it v) where v[j] = A[j, p[j]] for j = 0, ...
0
2016-08-06T12:13:23Z
38,804,529
<p>I don't think that such a functionality exists. To achieve what you want, I can think of two easy ways. You could do:</p> <pre><code>np.diag(A[:, p]) </code></pre> <p>Here the array <code>p</code> is applied as a column index for every row such that on the diagonal you will have the elements that you are looking f...
4
2016-08-06T12:58:03Z
[ "python", "arrays", "numpy", "matrix" ]
Getting multiple values in dictionary
38,804,366
<p>I want to get the values of a key in a dictionary. After working with googlemaps and I got my result, I want to just get the values I need and move on. But it seems not to be working for me.</p> <p>The result:</p> <pre><code>&gt;&gt;&gt;the_distance= gmaps.distance_matrix(origins, destinations) &gt;&gt;&gt; print ...
0
2016-08-06T12:35:30Z
38,804,407
<p>simple access to the dictionary could be done as follows.</p> <pre><code>cool_variable = the_distance['rows'][0]['elements'][0] cool_variable['duration']['text'] cool_variable['distance']['text'] </code></pre>
3
2016-08-06T12:40:05Z
[ "python" ]
'from __future__ import unicode_literals' in Django Migrations
38,804,449
<p>I just want to know that why does every auto-generated Django migration file contains the following line. </p> <pre><code>from __future__ import unicode_literals </code></pre> <p>The applications is running fine even if I remove all these lines. So, what's it purpose?</p>
0
2016-08-06T12:46:48Z
38,804,896
<p><code>from __future__ import unicode_literals</code> makes <code>"abc"</code> <code>unicode</code> instead of <code>str</code> in Python 2.x, so <code>"abc"</code> then means the same as <code>u"abc"</code> while otherwise <code>"abc"</code> would mean the same as <code>b"abc"</code>.</p> <p>For more info see the <...
1
2016-08-06T13:41:30Z
[ "python", "django", "import", "migration" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as foll...
1
2016-08-06T12:49:29Z
38,804,518
<p>Start the counter to 0 right after the first for loop, and increase by 1 each time after the second for loop:</p> <pre><code>for key, data in users_list: counter = 0 print key for value in data: counter += 1 print str(counter), "-", value["first_name"].upper(), value["last_name"].upper(...
0
2016-08-06T12:56:26Z
[ "python", "dictionary" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as foll...
1
2016-08-06T12:49:29Z
38,804,523
<pre><code>for key, data in users_list: print key for count, value in enumerate(data): print (count + 1), "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre> <p>That should do it. Read more about <code>enumerate</code> <a href=...
3
2016-08-06T12:57:19Z
[ "python", "dictionary" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as foll...
1
2016-08-06T12:49:29Z
38,804,545
<p>You may want to use the <em>enumerate</em> function on the list like that:</p> <pre><code>users_list = users.items() # converts users dict to a list for key, data in users_list: print key for i, value in enumerate(data, 1): print str(i), "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(va...
0
2016-08-06T13:00:06Z
[ "python", "dictionary" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as foll...
1
2016-08-06T12:49:29Z
38,805,546
<p>as mention by other, <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> is the best way to go, so I will just add some extra tip to make the program more efficient:</p> <ol> <li><p>unless you really need the <code>user_list</code> later on, iterate over <c...
0
2016-08-06T14:51:18Z
[ "python", "dictionary" ]
URL Regular Expression mismatch
38,804,535
<p>I am trying to learn Django and I am currently stuck in an issue.</p> <p>I created an app Contact and run the server, I get the error.</p> <p>The error page displayed by server:</p> <p><a href="http://i.stack.imgur.com/Z9H90.png" rel="nofollow"><img src="http://i.stack.imgur.com/Z9H90.png" alt="enter image descri...
-3
2016-08-06T12:58:35Z
38,804,661
<p>The <em>Page not found</em> error message tells you what went wrong: For the URL (<em>/contact</em>) you requested, Django was unable to find a suitable view. Because you have debugging enabled, you get some information, including a list of registered views.</p> <p>First things first: You probably have <code>url(r'...
0
2016-08-06T13:13:15Z
[ "python", "django" ]
Cannot update pip on ubuntu
38,804,596
<p>I am trying to update pip on ubuntu because it keeps telling me "You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command." but when I use that command it tells me "bash: /home/zak/.local/bin/pip: /usr/bin/python: bad interpreter: ...
0
2016-08-06T13:06:24Z
38,804,818
<p>If you are updating it globally (and not inside a virtualbox) try using sudo.</p> <pre><code>sudo pip install --upgrade pip </code></pre>
0
2016-08-06T13:32:05Z
[ "python", "ubuntu", "pip" ]
Unable to HTTP POST using python raw socket
38,804,615
<p>I am trying to do a http post on a url using a python raw socket.But I am unable to do so, while http get requests are working fine. The problem is when I try post.</p> <p>My code</p> <pre><code>import socket HOST = 'www.example.com' PORT = 80 DATA = "POST /example/email.php HTTP/1.1\r\n" # send headers "HOST: ...
-2
2016-08-06T13:08:04Z
38,804,835
<p>try it with</p> <pre><code>DATA = ("POST /example/email.php HTTP/1.1\r\n" # send headers "HOST: example.com\r\n" "Accept: *\r\n" "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n" "Referer: http://example.com/example/\r\n" "\r\n" # blank line seperating headers from body "action=subscribeme&amp;e...
1
2016-08-06T13:35:42Z
[ "python" ]
how run kivy program?
38,804,663
<p>I wrote some program with python kivy lib but it's not working. </p> <pre><code>import kivy from kivy.app import App from kivy.uix.button import Button from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.graphics import Color class Controller(BoxLa...
1
2016-08-06T13:13:19Z
38,805,809
<p>There are two problems here. </p> <p>I will show two examples in this answer. The first without nested <code>BoxLayout</code>, and second with nested <code>BoxLayout</code>.<br> In both examples, I will use <code>__init__</code> instead of <code>welcome()</code><br> You can also use <code>welcome()</code>. Read be...
1
2016-08-06T15:22:43Z
[ "python", "kivy" ]
The if statement looks right but got wrong answer
38,804,744
<pre><code>a = 5 b = 10 if a &lt; 5 and b &gt; 5: print('Yes') else: print('No') </code></pre> <p>When running the code above, I expect the answer is Yes. But the output is 'No'. Could anyone please tell me what wrong in my code is? Thank you in advance! </p>
-5
2016-08-06T13:23:47Z
38,804,765
<p>You are expecting <code>5</code> to be lower than <code>5</code> (<code>a = 5</code> and <code>a &lt; 5</code>). That's clearly not true, so the expression <code>a &lt; 5 and b &gt; 5</code> is False and the <code>else</code> branch is picked.</p>
2
2016-08-06T13:26:11Z
[ "python", "python-3.5" ]
The if statement looks right but got wrong answer
38,804,744
<pre><code>a = 5 b = 10 if a &lt; 5 and b &gt; 5: print('Yes') else: print('No') </code></pre> <p>When running the code above, I expect the answer is Yes. But the output is 'No'. Could anyone please tell me what wrong in my code is? Thank you in advance! </p>
-5
2016-08-06T13:23:47Z
38,804,806
<p>a is assigned to 5 this means that a is equal to five (a &lt; 5 is false) try doing</p> <pre><code> if a &lt;= 5 and b &gt;= 5: print('yes' else: print('no') </code></pre>
2
2016-08-06T13:30:24Z
[ "python", "python-3.5" ]
is there any command to "terminate all other sessions" in telegram-cli?
38,804,807
<p>i need a script to terminate all other sessions each time new login in my account detected(or each second) in python. <strong>is there any command to "terminate all other sessions" in telegram-cli?</strong></p>
1
2016-08-06T13:30:47Z
38,806,055
<p>You would need the session_id of your other sessions:</p> <pre><code>destroy_session#e7512126 session_id:long = DestroySessionRes;The expected </code></pre> <p>responses is:</p> <pre><code>destroy_session_ok#e22045fc session_id:long = DestroySessionRes; </code></pre> <p>or</p> <pre><code>destroy_session_none#6...
2
2016-08-06T15:49:08Z
[ "python", "telegram" ]
[Numpy/Pandas]How can I efficiently create a panel data set from transaction records?
38,804,820
<p>I have data arranged in the following form:</p> <pre><code>ID,DATE,STATUS 1,6/20/2011,A 1,1/14/2013,B 1,8/1/2016,C 2,3/1/2005,A 2,4/30/2005,B 2,6/30/2010,C 2,8/20/2010,D </code></pre> <p>I want to convert these transactions into an unbalanced panel with an annual frequency:</p> <pre><code>ID,YEAR,STATUS 1,2011,A ...
0
2016-08-06T13:32:09Z
38,805,181
<p>Here's one way:</p> <pre><code>import pandas as pd df = pd.read_csv('file', parse_dates=['DATE']) df = df.set_index('DATE').resample('A').ffill() df['YEAR'] = df.index.year df = df.sort_values(['ID', 'YEAR']).reset_index(drop=True) df Out: ID STATUS YEAR 0 1 A 2011 1 1 A 2012 2 1 B ...
2
2016-08-06T14:11:53Z
[ "python", "pandas", "numpy" ]
Select texts between tags in Xpath in Python
38,804,848
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;td width="250"&gt; 10.03.1984 16:30 &lt;br/&gt; Lütfi Kırdar, İstanbul &lt;br/&gt; &lt;br/&gt; 47-38, 49-58, 8-10...
2
2016-08-06T13:37:04Z
38,805,274
<blockquote> <p><em>"My code is <code>mactarih=tree.xpath("//tr//td[@width='250']//text()")</code>. But it is wrong"</em>. </p> </blockquote> <p>If it was 'wrong' in the sense that it returned empty texts or newlines along with the correct texts, then you can use <code>normalize-space()</code> to filter out whitespa...
2
2016-08-06T14:22:00Z
[ "python", "xpath" ]
Why does cookielib.LWPCookieJar accept an empty argument list?
38,804,897
<p>In the cookielib documentation, the definition of <a href="https://docs.python.org/2/library/cookielib.html#file-cookie-jar-classes" rel="nofollow">cookielib.LWPCookieJar</a> is:</p> <pre><code>class cookielib.LWPCookieJar(filename, delayload=None, policy=None) </code></pre> <p>The filename is a required argument....
1
2016-08-06T13:41:34Z
38,809,931
<p>Because the documentation is lying, apparently.</p> <p><code>cookielib.py</code> imports the definition of <a href="https://hg.python.org/cpython/file/2.7/Lib/_LWPCookieJar.py#l49" rel="nofollow"><code>LWPCookieJar</code></a> from <code>_LWPCookieJar.py</code>, which defines it as:</p> <pre><code>class LWPCookieJa...
1
2016-08-07T00:48:28Z
[ "python", "cookies" ]
Exit function after if
38,804,905
<p>This maybe a stupid question, but I don't kow how to exit the function below after if statement. This code is written in python</p> <pre><code>def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print("sum(%s)=%s" % (parti...
0
2016-08-06T13:42:21Z
38,804,917
<p>You are printing the return value of the function. Your function returns <code>None</code> (the default return value), so that is what is printed.</p> <p>Drop the <code>print()</code> function call, just call the function and leave it at that:</p> <pre><code>def main(): subset_sum([10, 7, 6, 3], 13) </code></p...
2
2016-08-06T13:43:52Z
[ "python", "if-statement", "exit" ]
Exit function after if
38,804,905
<p>This maybe a stupid question, but I don't kow how to exit the function below after if statement. This code is written in python</p> <pre><code>def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print("sum(%s)=%s" % (parti...
0
2016-08-06T13:42:21Z
38,804,929
<p>Your function is just returning, which means it returns <code>None</code>. This is a problem when you're calling the function recursively, because the parent doesn't know whether it should continue recursing or not.</p> <p>You should instead return a value that tells the parent call whether or not it should return ...
0
2016-08-06T13:45:18Z
[ "python", "if-statement", "exit" ]
Replacing pairs of variables in a file
38,804,986
<p>I working on a problem and my goal is to replace variables in the file and the name of the files. The issue is that I have to change a couple of variables at the same time for all combinations (Generally 24 combinations).</p> <p>I know how to create of all combinations of strings, but I want to put lists inside a...
-2
2016-08-06T13:52:02Z
38,806,936
<p>I think I almost tackled the above problem:</p> <pre><code>#!/usr/bin/env python import itertools import copy def replace_variables(i, distance ='0', T1 ='0', T2 = '0', gamma = '0' ): k_ = copy.deepcopy(i) k_[0][0] = '-2' k_[1][0] = '2' template_new = template.replace('*distance*',...
0
2016-08-06T17:27:41Z
[ "python" ]
What does sys.exit really do with multiple threads?
38,804,988
<p>I was really confused by sys.exit() in python. In <a href="https://docs.python.org/2/library/sys.html" rel="nofollow">python documentation</a>, it says "Exit from Python"; does that mean when <code>sys.exit()</code> is called in a python program, the process will exit? If so, the code below shows a different result:...
4
2016-08-06T13:52:16Z
38,805,142
<p>It is easy. </p> <p>In your case, the end of the program is when the last thread will be terminated. Maybe kind of join() method(as in Java) in python will wait for other threads. you can change <code>while(true)</code> to have finite method in sense of time.</p> <pre><code>def threadrun(): i=1000_000_000_000 ...
1
2016-08-06T14:09:19Z
[ "python", "multithreading", "exit" ]
What does sys.exit really do with multiple threads?
38,804,988
<p>I was really confused by sys.exit() in python. In <a href="https://docs.python.org/2/library/sys.html" rel="nofollow">python documentation</a>, it says "Exit from Python"; does that mean when <code>sys.exit()</code> is called in a python program, the process will exit? If so, the code below shows a different result:...
4
2016-08-06T13:52:16Z
38,805,169
<p>As per the documentation <a href="https://docs.python.org/2/library/sys.html#sys.exit" rel="nofollow"><code>sys.exit()</code></a> raises <code>SystemExit</code>:</p> <blockquote> <p>Exit the interpreter by raising SystemExit(status).</p> </blockquote> <p>If <code>SystemExit</code> reaches the <a href="https://gi...
4
2016-08-06T14:11:08Z
[ "python", "multithreading", "exit" ]
What does sys.exit really do with multiple threads?
38,804,988
<p>I was really confused by sys.exit() in python. In <a href="https://docs.python.org/2/library/sys.html" rel="nofollow">python documentation</a>, it says "Exit from Python"; does that mean when <code>sys.exit()</code> is called in a python program, the process will exit? If so, the code below shows a different result:...
4
2016-08-06T13:52:16Z
38,805,873
<p><sub>Paraphrasing what's in the documentation for <a href="https://docs.python.org/2/library/threading.html#thread-objects" rel="nofollow">Thread Objects</a></sub></p> <p>Normally a Python program exits only when there's nothing but daemon threads (ignoring itself) are left running. The “main thread” object whi...
0
2016-08-06T15:29:44Z
[ "python", "multithreading", "exit" ]
access first message in Django template
38,804,989
<p>I am using the following code to access the first message in Django template,</p> <pre><code>{% if messages %} {% for message in messages %} {% if forloop.first %} {{ message }} {% endif %} {% endfor %} {% endif %} </code></pre> <p>How I can achieve the same without using ...
0
2016-08-06T13:52:28Z
38,805,227
<p>Following should work:</p> <pre><code>{% if messages %} {{ messages.0 }} {% endif %} </code></pre>
2
2016-08-06T14:17:27Z
[ "python", "django" ]