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
Overwrite several methods of a class with a loop
37,523,092
<p>I would like to know if there is an easy way to do some identical edits on several methods of a class. An example :</p> <pre><code>class Dog(): def __init__(self): self.name = 'abc' self.age = 1 def setName(self, newValue): self.name = newValue def setAge(self, newValue): ...
3
2016-05-30T10:13:36Z
37,523,150
<p>You could probably go with a decorator here:</p> <pre><code>def add_output(output): """Adds an output to a function whenever it's called.""" def decorator(f): def wrapper(*args, **kwargs): return_value = f(*args, **kwargs) print(output) return return_value ...
1
2016-05-30T10:16:56Z
[ "python", "class", "methods" ]
Overwrite several methods of a class with a loop
37,523,092
<p>I would like to know if there is an easy way to do some identical edits on several methods of a class. An example :</p> <pre><code>class Dog(): def __init__(self): self.name = 'abc' self.age = 1 def setName(self, newValue): self.name = newValue def setAge(self, newValue): ...
3
2016-05-30T10:13:36Z
37,523,576
<p>The Pythonic way to do this is probably to use the <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptor protocol</a>, which is also what properties use:</p> <pre><code>class VocalAttribute: def __init__(self, name, feedback): """Called when you first create the descriptor...
2
2016-05-30T10:37:02Z
[ "python", "class", "methods" ]
Overwrite several methods of a class with a loop
37,523,092
<p>I would like to know if there is an easy way to do some identical edits on several methods of a class. An example :</p> <pre><code>class Dog(): def __init__(self): self.name = 'abc' self.age = 1 def setName(self, newValue): self.name = newValue def setAge(self, newValue): ...
3
2016-05-30T10:13:36Z
37,526,461
<p>since decorator could explicit called here a way to use it:</p> <pre><code>def updater(obj, call_back, call_back_args=(), call_back_kw=None, replace=False): # ability to be called on the fly with different args and kw for the callback # now it returns the updated obj (instance or class) # but could a b...
-1
2016-05-30T13:06:31Z
[ "python", "class", "methods" ]
Why doesn't Pythons unittest.assertRaises() raise an error here?
37,523,225
<p>Using Python 3.5, why does all tests below pass when run? Since, an <code>Exception</code> is not raised when <code>div</code> is called, how come that <code>assertRaises()</code> doesn't complain? </p> <p>According to the documentation for <code>assertRaises()</code>: "or fails if no exception is raised".</p> <p>...
-2
2016-05-30T10:20:02Z
37,523,266
<p>Because you have called <code>div</code> with wrong signature and exceptions was raised prior calling <code>div</code> (actual body of <code>div</code> wasn't executed, exception was raised prior execution).</p> <p>To get <strong>more clear</strong> picture of what's going on try to raise <a href="https://docs.pyt...
5
2016-05-30T10:22:17Z
[ "python", "unit-testing" ]
Why doesn't Pythons unittest.assertRaises() raise an error here?
37,523,225
<p>Using Python 3.5, why does all tests below pass when run? Since, an <code>Exception</code> is not raised when <code>div</code> is called, how come that <code>assertRaises()</code> doesn't complain? </p> <p>According to the documentation for <code>assertRaises()</code>: "or fails if no exception is raised".</p> <p>...
-2
2016-05-30T10:20:02Z
37,523,345
<p>An exception <strong>is</strong> raised when you call <code>self.div()</code> because you've defined the <code>div</code> method outside of the <code>MyTest</code> class. </p> <p>That's why it's a good idea to also verify the exception message in your test:</p> <pre><code>with self.assertRaises(Exception) as exc...
2
2016-05-30T10:25:54Z
[ "python", "unit-testing" ]
Got Failed to decode JSON object when calling a POST request in flask python
37,523,457
<p>I have written a simple REST-ful web server in python with <code>flask</code> following steps in this <a href="http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask" rel="nofollow">tutorial</a>; but I've got a problem calling <code>POST</code> request. The code is:</p> <pre><code>@app.ro...
0
2016-05-30T10:30:59Z
37,523,701
<p>Instead of using the <code>request.json</code> property, try using <code>request.get_json(force=True)</code> I would rewrite it:</p> <pre><code>@app.route('/todo/api/v1.0/tasks', methods=['POST']) def create_task(): try: blob = request.get_json(force=True) except: abort(400) if not 'tit...
0
2016-05-30T10:42:48Z
[ "python", "json", "flask", "webserver", "flask-restful" ]
Got Failed to decode JSON object when calling a POST request in flask python
37,523,457
<p>I have written a simple REST-ful web server in python with <code>flask</code> following steps in this <a href="http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask" rel="nofollow">tutorial</a>; but I've got a problem calling <code>POST</code> request. The code is:</p> <pre><code>@app.ro...
0
2016-05-30T10:30:59Z
37,524,940
<pre><code>from flask import Flask, request, abort, jsonify app = Flask(__name__) tasks = [{'id': 0}] @app.route('/todo/api/v1.0/tasks', methods=['POST']) def create_task(): if not request.json or 'title' not in request.json: abort(400) task = { 'id': tasks[-1]['id'] + 1, 'title': requ...
0
2016-05-30T11:47:43Z
[ "python", "json", "flask", "webserver", "flask-restful" ]
Read lines in one file and find all strings starting with 4-letter strings listed in another txt file
37,523,543
<p>I have 2 txt files (a and b_).</p> <p>file_a.txt contains a long list of 4-letter combinations (one combination per line):</p> <pre><code>aaaa bcsg aacd gdee aadw hwer etc. </code></pre> <p>file_b.txt contains a list of letter combinations of various length (some with spaces):</p> <pre><code>aaaibjkes aaleoslk a...
0
2016-05-30T10:35:35Z
37,523,858
<p>What you can do is to open both files and run both files down line by line using <code>for</code> loops.</p> <p>You can have two <code>for</code> loops, the first one reading <code>file_a.txt</code> as you will be reading through it only once. The second will read through <code>file_b.txt</code> and look for the st...
0
2016-05-30T10:51:35Z
[ "python", "regex", "find", "substring", "combinations" ]
Read lines in one file and find all strings starting with 4-letter strings listed in another txt file
37,523,543
<p>I have 2 txt files (a and b_).</p> <p>file_a.txt contains a long list of 4-letter combinations (one combination per line):</p> <pre><code>aaaa bcsg aacd gdee aadw hwer etc. </code></pre> <p>file_b.txt contains a list of letter combinations of various length (some with spaces):</p> <pre><code>aaaibjkes aaleoslk a...
0
2016-05-30T10:35:35Z
37,524,106
<p>I hope this would help you;</p> <pre><code>file1 = open('file_a.txt', 'r') file2 = open('file_b.txt', 'r') #get every item in your second file into a list mylist = file2.readlines() # read each line in the first file while file1.readline(): searchStr = file1.readline() # find this line in your second fil...
1
2016-05-30T11:05:50Z
[ "python", "regex", "find", "substring", "combinations" ]
Read lines in one file and find all strings starting with 4-letter strings listed in another txt file
37,523,543
<p>I have 2 txt files (a and b_).</p> <p>file_a.txt contains a long list of 4-letter combinations (one combination per line):</p> <pre><code>aaaa bcsg aacd gdee aadw hwer etc. </code></pre> <p>file_b.txt contains a list of letter combinations of various length (some with spaces):</p> <pre><code>aaaibjkes aaleoslk a...
0
2016-05-30T10:35:35Z
37,524,577
<p>Try this:</p> <pre><code>f1 = open("a.txt","r").readlines() f2 = open("b.txt","r").readlines() file1 = [word.replace("\n","") for word in f1] file2 = [word.replace("\n","") for word in f2] data = [] data_dict ={} for short_word in file1: data += ([[short_word,w] for w in file2 if w.startswith(short_word)]) fo...
0
2016-05-30T11:29:57Z
[ "python", "regex", "find", "substring", "combinations" ]
Mysql Connector error 1064 - Update with URL
37,523,603
<p>I am working on a twitter app in python and I am trying to update a user record in my database. I can insert fine but updating presents the following error:</p> <pre><code>mysql.connector.errors.ProgrammingError: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server vers...
0
2016-05-30T10:38:45Z
37,523,993
<p><a href="http://stackoverflow.com/questions/37523603/mysql-connector-error-1064-update-with-url#comment62539200_37523603">Jens</a> is right about the prepared statements. This is not only hard to debug, it's a security risk too. Your vunerable to SQL Injections.</p> <p>Anyway, I think your problem here are the miss...
1
2016-05-30T10:59:02Z
[ "python", "mysql", "mysql-connector" ]
PhantomJS from selenium - Python
37,523,654
<p>I'm trying to use PhantomJS (in Windows) with Selenium in Python to do some web scraping.<br> I've downloaded the latest PhantomJS build from the website, then unzip it. After that I've tried</p> <pre><code>from selenium import webdriver browser = webdriver.PhantomJS() </code></pre> <p>The response was</p> <pre><...
1
2016-05-30T10:40:47Z
39,189,955
<p>try to use absolute path as below where you have installed and also set 'NO_PROXY' environment for '127.0.0.1'</p> <pre><code>os.environ['NO_PROXY'] = '127.0.0.1' driver = webdriver.PhantomJS( executable_path=r'C:\Python\Python35-32\Lib\site-packages\phantomjs-2.1.1-windows\bin\phantomjs') </code></pre>
0
2016-08-28T09:44:06Z
[ "python", "selenium", "phantomjs" ]
PhantomJS from selenium - Python
37,523,654
<p>I'm trying to use PhantomJS (in Windows) with Selenium in Python to do some web scraping.<br> I've downloaded the latest PhantomJS build from the website, then unzip it. After that I've tried</p> <pre><code>from selenium import webdriver browser = webdriver.PhantomJS() </code></pre> <p>The response was</p> <pre><...
1
2016-05-30T10:40:47Z
39,293,990
<p>I'm trying to get this working under Windows, too...</p> <p>I'm superclassing the WebDriver, and I'm passing the ABSOLUTE path the executable is in into the __init__ method for the webdriver when initializing the superclass.</p> <p>This has got me further - now I'm seeing</p> <pre><code>Exception WebDriverExcepti...
0
2016-09-02T13:47:25Z
[ "python", "selenium", "phantomjs" ]
How to more efficiently calculate a rolling ratio
37,523,730
<ol> <li>i have data length is over 3000.</li> <li>below are code for making 20days value ( Volume Ration in Stock market)</li> <li>it took more than 2 min.</li> <li><p>is there any good way to reduce running time. </p> <pre><code>import pandas as pd import numpy as np from pandas.io.data import DataReader import matp...
-1
2016-05-30T10:43:50Z
37,524,739
<p>Consider using conditional row selection and <code>rolling.sum()</code>:</p> <pre><code>data.loc[data.index[:20], 'Volume Ratio'] = 0 data.loc[data.index[20:], 'Volume Ratio'] = (data.loc[:20:, 'acend'].rolling(window=20).sum() / (data.loc[:20:, 'Volume'].rolling(window=20).sum() - data.loc[:20:, 'acend'].rolling(w...
0
2016-05-30T11:37:57Z
[ "python", "numpy", "pandas", "dataframe", "iteration" ]
What should I do when I have a blocking thing in the on_message tornado.websocket?
37,523,935
<p>I'm new to tornado.I am trying to build a chat server proxy with tornado,I got the message from the web client,normally it just need to send it back,however,i need to send those message to another server first,here comes the problem,it costs a lot of time to wait the other server response,i need to make it no-blocki...
1
2016-05-30T10:55:32Z
37,527,659
<p>I think that error message is coming from your call to <code>finish()</code>, which is not meaningful for websockets (did you mean <code>close()</code>?). (Also, there's no need to use both <code>@asynchronous</code> and <code>@coroutine</code>; <code>@coroutine</code> alone is sufficient)</p> <p>But there's a bigg...
2
2016-05-30T14:04:28Z
[ "python", "websocket", "tornado" ]
Calculating the perimeter of any triangle [python 3]
37,524,028
<p>I am following an online course on python, and am stuck on this activity:</p> <blockquote> <p>Assume distance2D(x1, y1, x2, y2) has already been defined. Using it, define a function trianglePerimeter(xA, yA, xB, yB, xC, yC) which calculates the perimeter of a triangle whose three points are (xA, yA), (xB, yB) and...
-1
2016-05-30T11:01:02Z
37,524,338
<p>The input triangle has sides of lengths 3, 4, and 5. The perimeter of a polygon is equal to the sum of the lengths of its sides. For this triangle, that would be 3+4+5, or 12. However, you are multiplying two of the side lengths, then subtracting one of those side lengths from that product, for 3*5-5, or 10. I do no...
1
2016-05-30T11:17:42Z
[ "python", "python-3.x" ]
Calculating the perimeter of any triangle [python 3]
37,524,028
<p>I am following an online course on python, and am stuck on this activity:</p> <blockquote> <p>Assume distance2D(x1, y1, x2, y2) has already been defined. Using it, define a function trianglePerimeter(xA, yA, xB, yB, xC, yC) which calculates the perimeter of a triangle whose three points are (xA, yA), (xB, yB) and...
-1
2016-05-30T11:01:02Z
37,524,386
<p>See this </p> <pre><code>import math def distance2D(xA,yA,xB,yB): return math.sqrt((xA-xB)*(xA-xB)+(yA-yB)*(yA-yB)) def trianglePerimeter(xA,yA,xB,yB,xC,yC): return distance2D(xA,yA,xB,yB)+distance2D(xA,yA,xC,yC)+distance2D(xC,yC,xB,yB) print trianglePerimeter(1,5,6,2,7,6) 16.0368200508 </code></pre>
1
2016-05-30T11:20:10Z
[ "python", "python-3.x" ]
Calculating the perimeter of any triangle [python 3]
37,524,028
<p>I am following an online course on python, and am stuck on this activity:</p> <blockquote> <p>Assume distance2D(x1, y1, x2, y2) has already been defined. Using it, define a function trianglePerimeter(xA, yA, xB, yB, xC, yC) which calculates the perimeter of a triangle whose three points are (xA, yA), (xB, yB) and...
-1
2016-05-30T11:01:02Z
37,524,395
<p>To calculate perimeter add the distance of three sides. Your equation is definitely not doing that.</p> <pre><code>def perimeter(xA,yA,xB,yB,xC,yC): len_a = distance2D(xA,yA,xB,yB) len_b = distance2D(xB,yB,xC,yC) len_c = distance2D(xC,yC,xA,yA) return len_a + len_b + len_c </code></pre> <p>You will...
0
2016-05-30T11:20:39Z
[ "python", "python-3.x" ]
Deep learning - cost function increases for my training set, Theano
37,524,045
<p>I'm trying to train an extremely simple neural network, it has 2 hidden layers (for example) with 5 neurons each. </p> <p>For some reason, my cost function (chosen to be cross entropy, but doesn't really matter) is always increasing for a certain dataset.</p> <p>This is my code - </p> <pre><code>import theano_net...
0
2016-05-30T11:02:01Z
37,525,620
<p>You have to normalize your input data to the [0, 1] or [-1, 1] range, as you see this is already done in the MNIST dataset you have. Without normalization, training a neural network is much more difficult.</p> <p>You can do this easily by either substracting the mean of your dataset, and dividing by the standard de...
1
2016-05-30T12:24:27Z
[ "python", "machine-learning", "computer-vision", "neural-network" ]
Delete a specific relationship using py2neo
37,524,055
<p>Let's say we have 2 nodes, User and Post. The relationship, say upvote, can exist as (:User)-[UPVOTED]->(:Post)</p> <p>If the following query results in a non-empty list, then I wish to delete the relationship:</p> <pre><code> rel_list = list(graph.match(start_node=user, end_node=post, rel_type="UPVOTED") ...
0
2016-05-30T11:02:33Z
37,527,136
<p>To delete relationships you should use the <code>separate</code> method: <a href="http://py2neo.org/v3/database.html#py2neo.database.Transaction.separate" rel="nofollow">http://py2neo.org/v3/database.html#py2neo.database.Transaction.separate</a>. </p> <p>You may want to take a look to this issue in GitHub for some ...
0
2016-05-30T13:39:00Z
[ "python", "neo4j", "cypher", "py2neo" ]
Delete a specific relationship using py2neo
37,524,055
<p>Let's say we have 2 nodes, User and Post. The relationship, say upvote, can exist as (:User)-[UPVOTED]->(:Post)</p> <p>If the following query results in a non-empty list, then I wish to delete the relationship:</p> <pre><code> rel_list = list(graph.match(start_node=user, end_node=post, rel_type="UPVOTED") ...
0
2016-05-30T11:02:33Z
37,547,760
<p>Answering my own question, hope this helps others as well.</p> <pre><code> rel_list = list(graph.match(start_node=user, end_node=post, rel_type="UPVOTED") if len(rel_list) &gt; 0: # delete the relationship from the graph # fetch the ID of the relationship -&gt; rel_id query = ''' ...
0
2016-05-31T13:55:46Z
[ "python", "neo4j", "cypher", "py2neo" ]
How to efficiently convert the entries of a dictionary into a dataframe
37,524,056
<p>I have a dictionary like this:</p> <pre><code>mydict = {'A': 'some thing', 'B': 'couple of words'} </code></pre> <p>All the values are strings that are separated by white spaces. My goal is to convert this into a dataframe which looks like this:</p> <pre><code> key_val splitted_words 0 A ...
3
2016-05-30T11:02:38Z
37,524,317
<p>Here is my on-line approach:</p> <pre><code>df = pd.DataFrame([(k, s) for k, v in mydict.items() for s in v.split()], columns=['key_val','splitted_words']) </code></pre> <p>If I split it, it will be:</p> <pre><code>d=[(k, s) for k, v in mydict.items() for s in v.split()] df = pd.DataFrame(d, columns=['key_val','s...
4
2016-05-30T11:16:09Z
[ "python", "performance", "dictionary", "pandas" ]
How to efficiently convert the entries of a dictionary into a dataframe
37,524,056
<p>I have a dictionary like this:</p> <pre><code>mydict = {'A': 'some thing', 'B': 'couple of words'} </code></pre> <p>All the values are strings that are separated by white spaces. My goal is to convert this into a dataframe which looks like this:</p> <pre><code> key_val splitted_words 0 A ...
3
2016-05-30T11:02:38Z
37,524,658
<p>Based on @qu-dong's idea and using a generator function for readability a working example:</p> <pre><code>#! /usr/bin/env python from __future__ import print_function import pandas as pd mydict = {'A': 'some thing', 'B': 'couple of words'} def splitting_gen(in_dict): """Generator function to split ...
4
2016-05-30T11:33:41Z
[ "python", "performance", "dictionary", "pandas" ]
Newrelic error in Django : Configuration has already been done
37,524,100
<p>I am getting this error when i am trying to run <code>python manage.py runserver</code> for my Django Project,</p> <p><code>newrelic.api.exceptions.ConfigurationError: Configuration has already been done against differing configuration file or environment. Prior configuration file used was "/home/project/newrelic.i...
0
2016-05-30T11:05:06Z
37,524,437
<p>Have you just setup New Relic?</p> <p>I believe this is a problem with your <strong>procfile</strong>. Which you most likely just have edited. <br> <br> Your procfile should look something like this, depending on your wsgi.</p> <pre><code>web: newrelic-admin run-program gunicorn hello.wsgi --log-file - </code></pr...
1
2016-05-30T11:22:20Z
[ "python", "django", "newrelic" ]
Write strings with mixed encoding to console [Python]
37,524,103
<p>Suppose I have a list of 4 songs (basically, in real life I don't know how many songs I have and how are they encoded):</p> <ol> <li>OST Ходячий замок Хаула – Вальс "Карусель жизни"</li> <li>Fäaschtbänkler – 22 Genres</li> <li>Röyksopp – Running to the Sea (feat. Susanne ...
-1
2016-05-30T11:05:38Z
37,524,177
<p>Use <code>utf8</code> encoding. to write to stdout using utf8, use:</p> <pre><code>utf8stdout = open(1, mode='w', encoding='utf8',errors='replace', closefd=False) print("something", file=utf8stdout) </code></pre>
0
2016-05-30T11:08:58Z
[ "python", "encoding", "output" ]
Convert a deafultdict to numpy matrix or a CSV of 2D Matrix
37,524,151
<p>I have a <code>defaultdict</code> which stores data co-occurence of every 2 words in a dataset. I have done this os as to get a sparse representation as not every pair is present in the dataset and hence to save some memory space.</p> <p>Now are there some standard function which can convert this <code>defaultdict<...
0
2016-05-30T11:07:48Z
37,527,952
<p>Assuming your data looks something like this:</p> <pre><code>data = defaultdict(int) data[0,0] = 10 data[1,1] = 100 </code></pre> <p>You want to use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html#scipy.sparse.coo_matrix" rel="nofollow"><code>scipy.sparse.coo_matrix</code...
1
2016-05-30T14:19:34Z
[ "python", "numpy", "matrix" ]
How to use memcached in django project?
37,524,184
<p>I am working on django-project ,I want to reduce database request overhead. So I am trying with django-cache (Requires Memcached) </p> <pre><code>vi /etc/sysconfig/memcached PORT="11211" USER="memcached" MAXCONN="1024" CACHESIZE="64" We increased memory size up to 256 OPTIONS="" added IP address "-l 127.0.0.1" </...
0
2016-05-30T11:09:16Z
37,530,622
<p>You are using it correctly but keep in mind that if you restart memcached, you will loose all your existing sessions. That's to be expected.</p>
0
2016-05-30T17:00:08Z
[ "python", "memcached" ]
Python Assignment of a Variable By Looping through a Range
37,524,251
<p>The first two if statements should be identical... The first one works, the second does not work. What is wrong with the second if statement? </p> <pre><code> row=0 tsig=0 InTrade=[] for data_buy in stock_data['Buy']: if data_buy == 1: tsig=1 print(0) if sto...
0
2016-05-30T03:22:58Z
37,524,252
<p><code>row=row+1</code> is outside the loop. It stays <code>0</code> in each iteration of the loop, and only becomes <code>1</code> after the loop is finished.</p> <p>BTW - if you want to add an iteration index to a loop, you can(and should!) use <code>enumerate</code>:</p> <pre><code>for row, data_buy in enumerate...
4
2016-05-30T07:53:07Z
[ "python" ]
Python Lists Append True Boolean
37,524,346
<p>The following [incomplete] code is designed to take in an <em>n</em> to <em>x</em> number, of length <em>x-n</em>, and return the value of the next pandigital number. The code identifies which number between <em>n</em> and <em>x</em> is missing from the number passed in as an argument to the function, and returns (f...
0
2016-05-30T11:18:23Z
37,524,934
<p>You are checking the same list that you are updating and that is <strong>always</strong> dangerous. </p> <p>At the second iteration your variables are:</p> <pre><code>number=1 requiredDigits = [True, 1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>So when you are doing <code>requiredDigits.index(1)</code> there is a ...
0
2016-05-30T11:47:28Z
[ "python", "list", "boolean", "append" ]
Python Lists Append True Boolean
37,524,346
<p>The following [incomplete] code is designed to take in an <em>n</em> to <em>x</em> number, of length <em>x-n</em>, and return the value of the next pandigital number. The code identifies which number between <em>n</em> and <em>x</em> is missing from the number passed in as an argument to the function, and returns (f...
0
2016-05-30T11:18:23Z
37,524,936
<p>The issue is with using <code>index</code> to find where to assign to. Since <code>True</code> is equal to 1, you're mistakenly thinking that the <code>True</code> you entered for <code>0</code> is the <code>1</code> you want to replace next.</p> <p>A solution would be to use <code>enumerate</code> to get indexes a...
0
2016-05-30T11:47:37Z
[ "python", "list", "boolean", "append" ]
Create a distinct list of a part of column names
37,524,448
<p>I have a <code>DataFrame</code> called 'stockData'. Below is the head of a very small example that contains all of the different types of column name.</p> <pre><code> BBG.XLON.BTA.S_RAWLAST BBG.XLON.BTA.S_RAWVOLUME \ date 2008-02-04 ...
0
2016-05-30T11:23:03Z
37,524,549
<p>You can do a <code>list</code> comprehension over the <code>column</code> names using <code>df.columns</code>, use <code>.split('_')</code> and keep only the first part to get the stock name, then use <code>np.unique()</code> to remove duplicates and convert to <code>pd.Series</code>:</p> <pre><code>import numpy as...
0
2016-05-30T11:28:13Z
[ "python", "pandas" ]
Plot not offsetting off the screen
37,524,466
<p>Does anyone know what part of the code is making the plot not centered? It seems to be cutting it off at the side. I've researched and a temporary solutions was adjusting the <code>figsize</code> but this isn't a long terms solution. I've also tried adding space above without success.</p> <pre><code>import matplotl...
0
2016-05-30T11:24:14Z
37,524,872
<p>To save uncut figure use:</p> <p><code>plt.savefig('radar-chart.png', facecolor='white', bbox_inches='tight')</code></p> <p>Your problem occurs in <code>__init__</code> when axises are created.</p> <p>Add to plot section of main this code and try:</p> <pre><code># plotting width, height = matplotlib.rcParams['fi...
0
2016-05-30T11:45:06Z
[ "python", "matplotlib" ]
How to return the last primary key after INSERT in pymysql (python3.5)?
37,524,512
<pre><code>CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(255) COLLATE utf8_bin NOT NULL, `password` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ; </code></pre> <p>for example, how to get...
0
2016-05-30T11:26:29Z
37,524,602
<p>after inserting,You can get it as: <code>cursor.execute('select LAST_INSERT_ID()')</code> or use <code>cursor.lastrowid</code></p>
0
2016-05-30T11:30:35Z
[ "python", "mysql", "pymysql" ]
Python: Create empty pandas dataframe and add elements to its columns dynamically
37,524,586
<p>I am running a for loop for each of 12 months. For each month I get bunch of dates in random order over various years in history. I also have corresponding temperature data on those dates. e.g. if I am in month January, of loop all dates and temperature I get from history are for January only.</p> <p>I want to star...
1
2016-05-30T11:30:08Z
37,524,923
<p>@Zanam Pls refer this syntax. I think your question is similar to this answer </p> <pre><code> df = DataFrame(columns=('lib', 'qty1', 'qty2')) for i in range(5): df.loc[i] = [randint(-1,1) for n in range(3)] print(df) lib qty1 qty2 0 0 0 -1 1 -1 -1 1 2 1 -1 1 3 ...
0
2016-05-30T11:46:59Z
[ "python", "pandas", "dataframe" ]
Get an iteratable JSON from view in template without unicode values
37,524,648
<p>I have created a python (2.7) dictionary with the following structure:</p> <pre><code>cntr_rgns = {'country_1':[region1, region2, region3], 'country_2':[region1, region2] ..} </code></pre> <p>I pass it to my contextdioctionary as:</p> <pre><code>ctx['regions'] = cntr_rgns </code></pre> <p>What I want is to displ...
0
2016-05-30T11:33:08Z
37,525,216
<p>If you want JSON, you need to actually create some JSON.</p> <pre><code> ctx['regions'] = json.dumps(cntr_rgns) </code></pre>
1
2016-05-30T12:03:36Z
[ "python", "json", "django" ]
Python: Replace dataframe values row by row
37,524,704
<p>I'd like to conditionally replace values, row-by-row in a pandas dataframe so that max(row) will remain, while all other values in the row will be set to <code>None</code>. My intuition goes towards <code>apply()</code> but I am not sure if that's the right choice, or how to do it. </p> <p>Example (but there may be...
2
2016-05-30T11:36:02Z
37,524,757
<p>You can compared <code>DataFrame</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow"><code>eq</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow"><code>max</code></a>:</p> <pre><...
2
2016-05-30T11:39:13Z
[ "python", "pandas", "dataframe", "max", "apply" ]
Python: Replace dataframe values row by row
37,524,704
<p>I'd like to conditionally replace values, row-by-row in a pandas dataframe so that max(row) will remain, while all other values in the row will be set to <code>None</code>. My intuition goes towards <code>apply()</code> but I am not sure if that's the right choice, or how to do it. </p> <p>Example (but there may be...
2
2016-05-30T11:36:02Z
37,525,014
<p>I would suggest you to use <code>apply()</code>. You can use it as below:</p> <pre><code>In [1]: import pandas as pd In [2]: tmp= pd.DataFrame({ ...: 'A': pd.Series([1,2,3,4,5,6,7,8,9,10], index=range(0,10)), ...: 'B': pd.Series([3,4,1,33,10,9,7,3,10,10], index=range(0,10)) ...: } ) In [3]: tmp Out[3]: ...
2
2016-05-30T11:51:36Z
[ "python", "pandas", "dataframe", "max", "apply" ]
What is the best way to do Natural Language Processing in Rails app?
37,524,799
<p>I have a Rails app. I need to implement automatic text categorization algorithms and possibly more NLP capabilities in app. I believe Ruby does not have good NLP tools available as Python has. I am using a separate resque server for process background jobs. I believe I have following </p> <ol> <li>Run python script...
0
2016-05-30T11:41:37Z
37,526,239
<p>I had the same problem a few months ago. After a bit of research and testing this is the solution I implemented </p> <p><strong>Run several python processes</strong> As many as one machine can hold. And use as many machines as you need.</p> <p><strong>Use <a href="http://zeromq.org/" rel="nofollow">ZeroMQ</a> to c...
1
2016-05-30T12:56:16Z
[ "python", "ruby-on-rails", "flask", "nlp", "nltk" ]
lenght of a list of elementtree turn 0 after second call
37,524,883
<p>I have a code like this</p> <pre><code>import xml.etree.ElementTree as etree tree = etree.fromstring("&lt;all_products&gt;&lt;product instrument_name='nice_instrument'&gt;&lt;/product&gt;&lt;/all_products&gt;") product_iter = tree.iterfind("product[@instrument_name='nice_instrument']") len(list(product_iter)) </cod...
0
2016-05-30T11:45:23Z
37,524,951
<p><code>product_iter</code> is an iterator, not a list. If you convert it to a list, the <code>len</code> will stay <code>1</code>:</p> <pre><code>&gt;&gt;&gt; import xml.etree.ElementTree as etree &gt;&gt;&gt; tree = etree.fromstring("&lt;all_products&gt;&lt;product instrument_name='nice_instrument'&gt;&lt;/product&...
0
2016-05-30T11:48:42Z
[ "python", "list", "elementtree" ]
lenght of a list of elementtree turn 0 after second call
37,524,883
<p>I have a code like this</p> <pre><code>import xml.etree.ElementTree as etree tree = etree.fromstring("&lt;all_products&gt;&lt;product instrument_name='nice_instrument'&gt;&lt;/product&gt;&lt;/all_products&gt;") product_iter = tree.iterfind("product[@instrument_name='nice_instrument']") len(list(product_iter)) </cod...
0
2016-05-30T11:45:23Z
37,525,502
<p>Bottom line here I think is to understand iterators in python.</p> <p>Maybe findall instead of iterfind is better in this case.</p>
0
2016-05-30T12:19:14Z
[ "python", "list", "elementtree" ]
Transposing selectively in pandas (python 2.7)
37,524,891
<p>i am trying to create a two-way table with the data i have (sample data below)</p> <pre><code> hour source Group_Count 1 bloomberg 1 1 motley fool 1 1 reuters 1 1 zacks 4...
1
2016-05-30T11:45:35Z
37,524,963
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot.html" rel="nofollow"><code>pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>print (df.pivot(index='hour', columns='...
0
2016-05-30T11:49:11Z
[ "python", "python-2.7", "pandas", "dataframe" ]
jquery on load page send post request
37,524,922
<p>I want to create a html file with auto-login on my bank, this is my current code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; var MyHeaderss = {"User-Agent":"Mozilla/5.0 (Windows ...
0
2016-05-30T11:46:58Z
37,527,209
<p>Your code is correct. In the success function you can handle the response from the service and set the login.</p>
0
2016-05-30T13:42:07Z
[ "javascript", "jquery", "python", "html", "ajax" ]
Pygame loads images with RGB values offset 1px, but not alpha values
37,524,950
<p>When attempting to load an image via Pygames image load functionality, a black bar appears at the top of the loaded image. When slicing the tiles it became apparent that this bar offset the content by 1px.</p> <p>Attempting various file formats (gif, png, alpha, non-alpha etc.) have similar effects with the offset,...
0
2016-05-30T11:48:34Z
37,528,728
<p>Try to set image alpha:</p> <pre><code>pygame.image.load("src/tiles.gif"), (16,16)).convert_alpha () </code></pre>
0
2016-05-30T15:01:25Z
[ "python", "image", "python-3.x", "pygame" ]
What does "'tests' module incorrectly imported" mean?
37,525,075
<p>I have copied a working test line by line and just changed a few names (at least so I thought) and now I get this very cryptic error: (I have replaced some stuff with FOO, BAR)</p> <pre><code>ImportError: 'tests' module incorrectly imported from 'FOO/exports/tests'. Expected 'FOO/exports'. Is this module globally i...
1
2016-05-30T11:54:33Z
37,525,251
<p>In my experience, weird ImportErrors when running tests are caused by an ImportError in the tests module itself.</p> <p>Ensure that your tests module can be imported:</p> <pre><code>$ pyton manage.py shell ... &gt;&gt;&gt; import foo.exports.tests </code></pre> <p><strong>Edit:</strong></p> <p>If that causes an ...
3
2016-05-30T12:05:36Z
[ "python", "django" ]
How to send 1 time download link as email using Flask API?
37,525,079
<p>I need code to create a one-time download link for file uploaded using Flask. This link should be sent as email to the client. I have been able to create the dynamic link as per this solution:<a href="http://stackoverflow.com/questions/5320730/link-generator-using-django-or-any-python-module">Link generator using dj...
1
2016-05-30T11:55:05Z
37,865,532
<p>There is some information missing wrt performance, security etc and I am also unclear on what the cron job "should take care of", but from what I do understand, I have the impression you may be going about it the wrong way.</p> <p>What I understand is that you want a "file" model with a status available (i.e. it wa...
1
2016-06-16T17:14:55Z
[ "python", "flask" ]
How to send 1 time download link as email using Flask API?
37,525,079
<p>I need code to create a one-time download link for file uploaded using Flask. This link should be sent as email to the client. I have been able to create the dynamic link as per this solution:<a href="http://stackoverflow.com/questions/5320730/link-generator-using-django-or-any-python-module">Link generator using dj...
1
2016-05-30T11:55:05Z
37,991,788
<p>unlink($filename); This will delete the file.</p> <p>It needs to be combined with ignore_user_abort()Docs so that the unlink is still executed even the user canceled the download.</p> <p>ignore_user_abort(true);</p> <p>...</p> <p>unlink($f);</p>
-2
2016-06-23T12:35:36Z
[ "python", "flask" ]
How to map rectangle image to quadrilateral with PIL?
37,525,264
<p>Python PIL library allows me to map any quadrilateral in an image to rectangle using</p> <pre><code>im.transform(size, QUAD, data) </code></pre> <p>What I need is a function that does the opposite, i.e. map a rectangular image to specified quadrilateral.</p> <p>I figured this might be achieved with the above ment...
1
2016-05-30T12:06:26Z
37,543,316
<p>So I solved the issue with a simple forward mapping, rather than inverse mapping, which is usually better, but in my application I only ever map the rectangle to a quad that is smaller than the rectangle, so there are usually no holes in the transformed image. The code is as follows:</p> <pre><code>def reverse_quad...
2
2016-05-31T10:35:42Z
[ "python", "geometry", "python-imaging-library" ]
error in creating http server on windows
37,525,387
<p>I want to set up Python SimpleHTTPServer on windows XP. I have Python installed on my computer. I am executing the following command: </p> <pre><code>python -m SimpleHTTPServer 8888 </code></pre> <p>But I am getting the error: </p> <blockquote> <p>python : The term 'python' is not recognized as the name of a...
0
2016-05-30T12:13:17Z
37,525,730
<p>Looks like Python is not in your PATH enviroment variable. To fix this try this answer: <a href="http://stackoverflow.com/a/6318188/6400392">http://stackoverflow.com/a/6318188/6400392</a></p> <blockquote> <ol> <li>Hold Win and press Pause.</li> <li>Click Advanced System Settings.</li> <li>Click Environment ...
0
2016-05-30T12:29:40Z
[ "python", "windows", "python-2.7", "http", "server" ]
Could not update model's data using django
37,525,531
<p>I am hoping when i make a query using form, then the model <code>SearchAllStatics</code>'s <code>view_count</code> would add one. But the fact is, it just still be one.</p> <p>Here's the models.py</p> <pre><code>class SearchAllStatistic(models.Model): content = models.CharField(max_length=255) view_count ...
0
2016-05-30T12:20:27Z
37,525,582
<p>You have mistake</p> <pre><code> w.view_count =+1 </code></pre> <p>which is assigning of <code>1</code> value to <code>view_count</code> variable instead of</p> <pre><code> w.view_count += 1 </code></pre> <p>which is using of <code>+=</code> operator what you want to do actually</p>
1
2016-05-30T12:22:49Z
[ "python", "django" ]
Python creating a string using \ and send it in a json request
37,525,576
<p>I am trying to automate some queries to a API using Python. The problem is that the request needs to be created in a special way, and I just cant make it work. This is the part of the string I am having problems creating.</p> <pre><code>payload = "{\n \"filter\": {\n \"name\":[\"name1\", \"name2\"]\n }" </code...
0
2016-05-30T12:22:37Z
37,525,784
<p>Instead of creating your payload by hand, first create a python dictionary and use the <code>json</code>-module to convert it to a string:</p> <pre><code>payload = {"filter": {"name": list_of_names]}} payload = json.dumps(payload) </code></pre> <p>or with your more complex dictionary:</p> <pre><code>payload = { ...
3
2016-05-30T12:32:54Z
[ "python", "json", "string" ]
Failing to fetch data from MySQLdb database
37,525,578
<p>[enter image description here][1]I am currently making a project for school and the time for reaching the wall has come.</p> <p>I am trying to fetch data from the USB port on Raspberry Pi 3+. I have connected an Arduino Nano and I am sending a string(UID number in decimal of an RFID Card) from it to the Pi via the...
0
2016-05-30T12:22:43Z
37,527,100
<p>Possible solution could be:</p> <pre><code>import sqlite3 conn = sqlite3.connect("users.db")#path to your sqlite db file! cursor = conn.cursor() CardID=ser.readline().strip() sql = "SELECT * FROM cards WHERE serial_no=?" cursor.execute(sql, [(CardID)]) try: results = cursor.fetchall()[0]# just fetching the fi...
0
2016-05-30T13:37:24Z
[ "python", "sqlite3", "arduino", "raspberry-pi3" ]
How to iterate through a dictionary with lists in django template?
37,525,593
<p>I have a dictionary with lists and I am trying to iterate through it, while in my Django template.</p> <p>This is how it looks my dictionary:</p> <pre><code>{u'Canada': [u'Saskatchewan', u'Nunavut', u'Nova Scotia / Nouvelle-\xc9cosse', u'Prince Edward Island / \xcele-du-Prince-\xc9douard', u'Northwest Territories ...
4
2016-05-30T12:23:15Z
37,525,689
<p>You should use a nested loop in your case:</p> <pre><code>{% for cntr, rgn in regions.items %} {% for r in rgn %} &lt;option value="{{ r }}"&gt;{{ r }}&lt;/option&gt; {% endfor %} {% endfor %} </code></pre>
5
2016-05-30T12:28:09Z
[ "python", "django", "loops", "templates", "view" ]
Matlab - Iterating through an array and appending to a new one
37,525,708
<p>I got an array that is a audio recording, and I'd like to add some noise on it so later I can remove it in Simulink and compare the original to the one that I removed the noise.</p> <p>My problem is that I'm pretty new to Matlab's languages/functions, so I got stucked in a for loop that I didnt understand how It wo...
0
2016-05-30T12:28:48Z
37,525,888
<p>Just make a copy of voice and add the values:</p> <pre><code>new_audio = voice new_audio(:, 3) = noise(1) new_audio(:, 4) = noise(2) </code></pre>
0
2016-05-30T12:38:28Z
[ "python", "arrays", "matlab", "simulink" ]
Matlab - Iterating through an array and appending to a new one
37,525,708
<p>I got an array that is a audio recording, and I'd like to add some noise on it so later I can remove it in Simulink and compare the original to the one that I removed the noise.</p> <p>My problem is that I'm pretty new to Matlab's languages/functions, so I got stucked in a for loop that I didnt understand how It wo...
0
2016-05-30T12:28:48Z
37,526,317
<p>I like Daniel's solution, however there are some edits needed:</p> <pre><code>new_audio = voice; new_audio(:,1) = new_audio(:,1) + noise(1); new_audio(:,2) = new_audio(:,2) + noise(2); </code></pre> <p>Here is an alternative way to accomplish the same end:</p> <pre><code>voice = [0.0012, 0.0012;0.0003, 0.0005; 0....
1
2016-05-30T12:59:36Z
[ "python", "arrays", "matlab", "simulink" ]
Matlab - Iterating through an array and appending to a new one
37,525,708
<p>I got an array that is a audio recording, and I'd like to add some noise on it so later I can remove it in Simulink and compare the original to the one that I removed the noise.</p> <p>My problem is that I'm pretty new to Matlab's languages/functions, so I got stucked in a for loop that I didnt understand how It wo...
0
2016-05-30T12:28:48Z
37,526,840
<p>What you want to do is just create a new array from the old one and add the noise. If you want to add <code>[0.0142, 0.0142]</code> to every row, then use <code>bsxfun</code> to broadcast the operation to each row.</p> <pre><code>noisy = bsxfun(@plus, voice, [0.0142, 0.0142]); </code></pre> <p>What I think that yo...
1
2016-05-30T13:24:36Z
[ "python", "arrays", "matlab", "simulink" ]
Python PyObjC_IdToPython(@protocol(NSURLSessionStreamDelegate)) error
37,525,929
<p>when i try to install pyobjc-framework-Cocoa i see this error:</p> <pre><code>In file included from Modules/_Foundation.m:15: Modules/_Foundation_protocols.m:14:28: error: cannot find protocol declaration for 'NSProgressReporting' p = PyObjC_IdToPython(@protocol(NSProgressReporting)); Py_XDECREF(p); ...
4
2016-05-30T12:40:19Z
37,639,767
<p>I was able to avoid the problem in the following environment: </p> <pre><code>Mac OS X 10.10.5 pip8.1.2 python3.4 </code></pre> <p>Please try the following command.</p> <blockquote> <p>pip uninstall pyobjc-core<br> pip install pyobjc==3.0.4</p> </blockquote> <p>The cause of the problem seems to be a d...
4
2016-06-05T08:08:31Z
[ "python", "protocols", "pyobjc" ]
Regex Multline Python
37,525,940
<p>i am currently trying to do a regex on pyhthon that should match multline.</p> <pre><code>([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s{3,}?4 </code></pre> <p>is my regular expression, this is my python call</p> <pre><code>re.findall("([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}...
1
2016-05-30T12:41:07Z
37,526,137
<p>If your input contains a line break with \r\n and you correct the spacing after the 'FG' part, this should work:</p> <p><code>([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s+?4</code></p> <p>Tested here (with \n only for the line break): <a href="https://regex101.com/r/iT1rF2/2" rel="n...
0
2016-05-30T12:50:45Z
[ "python", "regex" ]
Regex Multline Python
37,525,940
<p>i am currently trying to do a regex on pyhthon that should match multline.</p> <pre><code>([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s{3,}?4 </code></pre> <p>is my regular expression, this is my python call</p> <pre><code>re.findall("([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}...
1
2016-05-30T12:41:07Z
37,526,191
<p>Note that in the corrected input shown, the part <code>FG\s{3,}?4</code>of the pattern avoids a match as a single space does not match between <code>FG</code>and the <code>4</code>.</p> <pre><code>#! /usr/bin/env python from __future__ import print_function import re content = "19.04.2016 05:31:03 ASDFASDF\r\n...
2
2016-05-30T12:53:56Z
[ "python", "regex" ]
Regex Multline Python
37,525,940
<p>i am currently trying to do a regex on pyhthon that should match multline.</p> <pre><code>([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s{3,}?4 </code></pre> <p>is my regular expression, this is my python call</p> <pre><code>re.findall("([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}...
1
2016-05-30T12:41:07Z
37,526,192
<p>Works for me:</p> <pre><code>&gt;&gt;&gt; content = '''19.04.2016 05:31:03 ASDFASDF\r ---- FG 4\r 19.04.2016 05:31:03 ASDFASDF\r ---- FG 4\r 19.04.2016 05:31:03 ASDFASDF\r ---- FG 4\r 19.04.2016 05:31:03 ASDFASDF\r ---- FG 4\r 19.04.2016 05:31:03 ASDFASDF\r ---- FG 4''' &gt;&gt;&gt; re.findall("([0-9...
0
2016-05-30T12:54:02Z
[ "python", "regex" ]
Regex Multline Python
37,525,940
<p>i am currently trying to do a regex on pyhthon that should match multline.</p> <pre><code>([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s{3,}?4 </code></pre> <p>is my regular expression, this is my python call</p> <pre><code>re.findall("([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}...
1
2016-05-30T12:41:07Z
37,527,307
<p>Note that you could re-write your regex with shortcuts so that your pattern:</p> <pre><code>([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*?\r\n-{1,}\sFG\s{3,}?4 </code></pre> <p>becomes (shortcut and corrections):</p> <pre><code>(\d{2}\.\d{2}\.\d{4}\s\d{2}:\d{2}:\d{2}).*?\r\n-+\sFG\s+?4 </code></pre...
0
2016-05-30T13:47:33Z
[ "python", "regex" ]
Django app cannot find environment varibles
37,526,114
<p>I posted a question a little bit similar to this earlier on but couldn't find the answers I was looking for, so after some research I have refined it somewhat.</p> <p>I have written a Django app to be deployed with AWS Elastic Beanstalk which uses an RDS database. My Elastic Beanstalk environment has several enviro...
1
2016-05-30T12:49:11Z
37,526,183
<p>On ubuntu go to your home directory and open file <code>.bashrc</code>.</p> <p>add the following line at the end of this file add this:</p> <pre><code>export RDS_DB_NAME='&lt;your_local_db_name&gt;' </code></pre> <p>close terminal and reopen. Run django server and done.</p> <p>EDIT:</p> <p>try </p> <p><code>'N...
0
2016-05-30T12:53:04Z
[ "python", "linux", "django", "bash", "amazon-web-services" ]
Django app cannot find environment varibles
37,526,114
<p>I posted a question a little bit similar to this earlier on but couldn't find the answers I was looking for, so after some research I have refined it somewhat.</p> <p>I have written a Django app to be deployed with AWS Elastic Beanstalk which uses an RDS database. My Elastic Beanstalk environment has several enviro...
1
2016-05-30T12:49:11Z
37,526,244
<p>Another way you could handle this situation is by defining a condition on when to use the environment variables and when to use the local (hardcoded) variables. </p> <p>The following code snippet is taken from <a href="https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/" rel="nofollo...
0
2016-05-30T12:56:33Z
[ "python", "linux", "django", "bash", "amazon-web-services" ]
Django app cannot find environment varibles
37,526,114
<p>I posted a question a little bit similar to this earlier on but couldn't find the answers I was looking for, so after some research I have refined it somewhat.</p> <p>I have written a Django app to be deployed with AWS Elastic Beanstalk which uses an RDS database. My Elastic Beanstalk environment has several enviro...
1
2016-05-30T12:49:11Z
37,526,386
<p>I suggest to use <a href="https://github.com/joke2k/django-environ" rel="nofollow">django-environ</a></p> <p>With it you can just create .env file variable you need. Also it will allow ( but don't force to) you to set whole db configuration ( and other too like cache,etc) as url like this:</p> <pre><code>DATABASE_...
2
2016-05-30T13:03:00Z
[ "python", "linux", "django", "bash", "amazon-web-services" ]
Memory intensive Python program
37,526,149
<p>I was recently asked an interview question whose answer I am curious to know, although I could not answer during the interview itself: Given user A and user B are running their tasks on a ubuntu 12.04 server as non-root user. User A is running mongodb with 52.2% memory usage. Is there a program in python which user ...
2
2016-05-30T12:51:26Z
37,526,794
<p>Most (all?) modern operating systems employ memory protection. They do not allow one process to access the memory of another process, generally. This prevents a memory heavy application from using memory allocated other processes. The memory heavy application's data will get written to the swap file once the physica...
2
2016-05-30T13:22:41Z
[ "python", "mongodb", "python-2.7" ]
Seasonal ARIMA with Python, freq H not understood?
37,526,218
<p>I am new in here. I am trying to decompose a time serie by following this <a href="http://www.seanabu.com/2016/03/22/time-series-seasonal-ARIMA-model-in-python/" rel="nofollow">TIME SERIE DECOMPOSITION EXAMPLE</a> with this <a href="https://datamarket.com/data/set/22w6/portland-oregon-average-monthly-bus-ridership-1...
2
2016-05-30T12:55:11Z
37,527,622
<p>After looking in some blogs, and testing some solutions. I have come with this one :</p> <p>Adding <em>values</em> to df.Close permit to do the decomposition like this :</p> <pre><code>decomposition = seasonal_decompose(df.Close.values, freq=168) </code></pre>
3
2016-05-30T14:02:29Z
[ "python", "statistics", "time-series", "statsmodels" ]
Setuptools installation in Jython
37,526,245
<p>Latest Jython standalone (2.7 final), latest setuptools:</p> <pre><code>C:\projects_intellij\test_jython&gt;jython.bat ez_setup.py C:\projects_intellij\test_jython&gt;java -jar "C:\projects_intellij\test_jython\jython-standalone-2.7.0.jar" ez_setup.py Extracting in C:\Users\myuser\AppData\Local\Temp\tmpt_1anc Now ...
0
2016-05-30T12:56:35Z
37,527,152
<p>Yes, I think you should have.</p> <p>It looks like a version problem.</p> <p>Same here:</p> <p><a href="https://sourceforge.net/p/jython/mailman/jython-users/thread/CAOhO%3DaNmNL6xeKES2JXPkg%2BP3OTBxJCESNA0YtfLVX1L1fv85w@mail.gmail.com/" rel="nofollow">https://sourceforge.net/p/jython/mailman/jython-users/thread/...
0
2016-05-30T13:39:17Z
[ "python", "jython", "windows-7-x64", "setuptools" ]
Python Jira API Screen error for source and region fields
37,526,394
<p>I am trying to create Jira issue using Python-Jira API but getting screen error for source and region fields.Please help me to resolve the same.</p> <p>Error:</p> <pre><code>Exception Value: JiraError HTTP 400 text: Field 'source' cannot be set. It is not on the appropriate screen, or unknown. url: http://jir...
0
2016-05-30T13:03:18Z
37,526,655
<p>Do you have correct configuration? Chceck this post: <a href="https://answers.atlassian.com/questions/265902/answers/19694532" rel="nofollow">https://answers.atlassian.com/questions/265902/answers/19694532</a></p>
1
2016-05-30T13:16:07Z
[ "python", "api", "jira", "python-jira" ]
Fail to run a selenium app in terminal (ImportError: No module named selenium)
37,526,432
<p>I’m new to python and selenium but: So <strong>when I run my python script with the python IDLE (hitting F5), selenium works fine</strong> (opens firefox, go to website, do stuff)</p> <p>but when I try to run my script with the Terminal on OSX (python app.py) it fails with following error:</p> <pre><code>Traceba...
0
2016-05-30T13:04:34Z
37,526,656
<p>You can check your python include path by executing following code (python3):</p> <pre><code>import sys print(sys.executable) </code></pre> <p>See if your package's path is included. If not, then you can append the path by:</p> <pre><code>sys.path.append("/pathtoyourpackage") </code></pre> <hr> <p>As a beginner...
1
2016-05-30T13:16:08Z
[ "python", "selenium" ]
Fail to run a selenium app in terminal (ImportError: No module named selenium)
37,526,432
<p>I’m new to python and selenium but: So <strong>when I run my python script with the python IDLE (hitting F5), selenium works fine</strong> (opens firefox, go to website, do stuff)</p> <p>but when I try to run my script with the Terminal on OSX (python app.py) it fails with following error:</p> <pre><code>Traceba...
0
2016-05-30T13:04:34Z
37,526,779
<p>I think you have two different python versions installed so your IDLE uses Python3 and your command prompt runs Python2. To see the current version and the path of the instance of python run the follwing:</p> <pre><code>import sys sys.version sys.path </code></pre> <p>Finally you could uninstall the version you do...
1
2016-05-30T13:21:53Z
[ "python", "selenium" ]
sort list of tuples in a dictionary
37,526,577
<p>I have a structure looking like this </p> <pre><code>d= { 'image0' : [(image0, image1, 31.58), (image0, image2, 31.56), (image0, image3, 54.65)], 'image2' : [(image0, image2, 31.56), (image1, image2, 45.87), (image2, image3, 14.25)] ...} </code></pre> <p>and I would like it to be sorted by key and then by the last...
-1
2016-05-30T13:12:22Z
37,526,778
<p>I think your problem is with your lambda function, looks like too much indexing than needed.</p> <p>Regardless, since <code>d['imagex']</code> would return a list of your tuples, that means you can call <code>.sort(..)</code> on it with <code>key = lambda x: x[2]</code>. Like below:</p> <pre><code>for itemKey in d...
1
2016-05-30T13:21:50Z
[ "python", "list", "sorting", "dictionary", "tuples" ]
sort list of tuples in a dictionary
37,526,577
<p>I have a structure looking like this </p> <pre><code>d= { 'image0' : [(image0, image1, 31.58), (image0, image2, 31.56), (image0, image3, 54.65)], 'image2' : [(image0, image2, 31.56), (image1, image2, 45.87), (image2, image3, 14.25)] ...} </code></pre> <p>and I would like it to be sorted by key and then by the last...
-1
2016-05-30T13:12:22Z
37,526,903
<p>You need to sort the values first, then the keys (items):</p> <pre><code>from operator import itemgetter for v in d.values(): v.sort(key=itemgetter(2)) a = sorted(d.items()) </code></pre>
0
2016-05-30T13:27:49Z
[ "python", "list", "sorting", "dictionary", "tuples" ]
Python matplotlib -- delete data out of axis limits
37,526,592
<p>I am plotting iteratively using matplotlib in python. I am setting the axis of the plot, so as to display e.g. only 50 lines at a time. A pseudo code is given below as an example:</p> <pre><code>x = 0 y = 1 line_plot = 50 axis.set_ylim(0 , line_plot) while True: plot(x,y) y = y+1 if y...
1
2016-05-30T13:12:50Z
37,528,679
<p>This will depend a little bit on how exactly your script looks like. You need some method to determine the y-coordinates of every line, and based on some criteria remove them or not. But if you do something like:</p> <pre><code>x = np.arange(1) y = np.ones(1) pl.figure() l1 = pl.plot(x,y)[0] y[:] += 1 l2 = pl.plot...
1
2016-05-30T14:58:17Z
[ "python", "matplotlib", "axis" ]
Python matplotlib -- delete data out of axis limits
37,526,592
<p>I am plotting iteratively using matplotlib in python. I am setting the axis of the plot, so as to display e.g. only 50 lines at a time. A pseudo code is given below as an example:</p> <pre><code>x = 0 y = 1 line_plot = 50 axis.set_ylim(0 , line_plot) while True: plot(x,y) y = y+1 if y...
1
2016-05-30T13:12:50Z
37,531,251
<p>You want look at the <a href="http://matplotlib.org/1.5.1/examples/animation/index.html" rel="nofollow">animation examples</a></p> <pre><code># make a figure and axes object fig, ax = plt.subplots() # make a Line2D artist ln, = ax.plot([], [], linestyle='', marker='o') # local version of the data xdata, ydata = [],...
0
2016-05-30T17:48:22Z
[ "python", "matplotlib", "axis" ]
Error while importing matplotlib.pyplot Python
37,526,730
<p>I have a problem while importing matplotlib.pyplot , I have python2.7 windows 7 64bits</p> <pre><code>&gt;&gt;&gt; import matplotlib.pyplot as plt Traceback (most recent call last): File "&lt;pyshell#16&gt;", line 1, in &lt;module&gt; import matplotlib.pyplot as plt File "C:\Python27\lib\site-packages\matp...
0
2016-05-30T13:19:55Z
37,535,606
<p>I soled the issue by uninstalling python27, reinstall it again and install extension pip install matplotlib-1.5.0-cp27-none-win_amd64.whl</p> <p>this will install automaticaly numpy extension</p>
0
2016-05-31T01:40:25Z
[ "python", "matplotlib" ]
How to set trust-store used by Python's httplib?
37,526,788
<p>Per default, Python's <a href="https://docs.python.org/2/library/httplib.html" rel="nofollow">httplib</a>.HTTPSConnection is using the system's trust store to validate a HTTPS certificate. (How) is it possible to set a different CA list to do the validation, replacing the default one?</p> <p>I tried to set the <a h...
3
2016-05-30T13:22:34Z
37,530,426
<p>Stefan, I do see two problems with your attempt: You should use <a href="https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_SSLv23" rel="nofollow"><code>ssl.PROTOCOL_SSLv23</code></a> and not the TLSv1 which is already outdated. Do not be confused by the name of the variable, read the linked documentation to un...
0
2016-05-30T16:45:41Z
[ "python", "python-2.7", "ssl", "https", "httplib" ]
How to set trust-store used by Python's httplib?
37,526,788
<p>Per default, Python's <a href="https://docs.python.org/2/library/httplib.html" rel="nofollow">httplib</a>.HTTPSConnection is using the system's trust store to validate a HTTPS certificate. (How) is it possible to set a different CA list to do the validation, replacing the default one?</p> <p>I tried to set the <a h...
3
2016-05-30T13:22:34Z
37,836,986
<p>As it seems this is not really possible, we 'solved' the problem by using Python-<a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>, since it allows us to set the CA bundle.</p> <pre><code>requests.get('https://' + domain, verify='mozillacerts.pem') </code></pre> <p>See also: <a href=...
0
2016-06-15T13:32:43Z
[ "python", "python-2.7", "ssl", "https", "httplib" ]
Python, running a loop on several CPUs
37,526,808
<p>I created a small code that works similar to sklearn gridsearch, It trains the model <em>(on X and y in the code below)</em> on one set of hyperparameters, checks the model performance using several metrics on validation data (<em>Xt, yt_class)</em> and stores the results in the pandas DataFrame. </p> <pre><code> ...
0
2016-05-30T13:23:16Z
37,527,073
<p>Your <code>get_scores</code> method should only consist of the inner part of the loop</p> <p>Try this:</p> <pre><code>import multiprocessing as mp from sklearn.grid_search import ParameterGrid from sklearn.metrics import precision_score,f1_score def get_scores(params): model = SVC(kernel='rbf',cache_size=1000...
2
2016-05-30T13:36:17Z
[ "python", "multiprocessing" ]
Python static typing does not work
37,526,876
<p>I found out that Python is intending to support static typing, but it still in beta phase. I tried the following code with python 3.4.3:</p> <pre><code>def somme(a: int, b: int) -&gt; int: return a + b </code></pre> <p>the syntax is supported but I did not get the expected result. if I type <code>somme('1', '3...
2
2016-05-30T13:26:10Z
37,526,963
<p>The function annotations there are <em>annotations</em>, nothing more. They're documentation about intended usage. Like it says in <a href="https://www.python.org/dev/peps/pep-3107/" rel="nofollow">PEP 3107</a>, the mechanism provides a single, standard way to specify function parameters and return values, replacing...
9
2016-05-30T13:30:47Z
[ "python", "python-3.x", "static-typing" ]
Python static typing does not work
37,526,876
<p>I found out that Python is intending to support static typing, but it still in beta phase. I tried the following code with python 3.4.3:</p> <pre><code>def somme(a: int, b: int) -&gt; int: return a + b </code></pre> <p>the syntax is supported but I did not get the expected result. if I type <code>somme('1', '3...
2
2016-05-30T13:26:10Z
37,527,107
<p>In reality, you aren't supposed to get static typing here. The code you wrote is actually a form of easy documentation and "type hinting", as explained <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">here</a>. To quote that PEP:</p> <blockquote> <p>While these annotations are available at runti...
2
2016-05-30T13:37:42Z
[ "python", "python-3.x", "static-typing" ]
Make a dataframe with str.count() over the index
37,526,889
<p><strong>EDIT</strong> (thanks to <strong>Jezrael</strong> to lead me on a way to do it): </p> <p>I have a list of phone numbers, and I'd like for every number to count the number of occurences of each digit. You'd understand that a double <code>for</code> loop isn't possible as I have a few hundred thousands phone ...
1
2016-05-30T13:26:36Z
37,527,120
<p>You can first convert <code>index</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_series.html" rel="nofollow"><code>to_series</code></a>, because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> does n...
2
2016-05-30T13:38:29Z
[ "python", "pandas", "count" ]
python pandas dataframe create bins only for data in threshold
37,526,936
<p>In a python pandas dataframe "df", I have the following three columns:</p> <pre><code>song_id | user_id | play_count </code></pre> <p>play_count = how many times a user listened to a song</p> <p>I am trying to add a column "rating" to this table based on play count. For example, if play_count =2, the rating will...
1
2016-05-30T13:29:27Z
37,535,115
<pre><code># get threshholds for first 9 bins _, bins = pd.cut(df[df.play_count &lt; 200].play_count, bins=9,retbins=True) # append threshhold representing class with play_counts &gt; 200 new_bins = pd.np.append(bins,float(max(df.play_count))) # our categorized data out = pd.cut(df.play_count,bins=new_bins) # a hist...
1
2016-05-31T00:24:48Z
[ "python", "pandas", "dataframe", "count", "bin" ]
TIC TAC TOE GAME - python
37,526,939
<p>i wrote a "tic tac toe" game in python(pycharm). At the end of the game i asked the user if he wants to play again: if he pressed 'y' the game began again, and if he pressed 'n' the game/code stopped. do you know how can i show him an error massege like: "you entered a wrong answer! please try again:" when he doesn'...
0
2016-05-30T13:29:34Z
37,527,180
<pre><code>if answer.lower() == "n": print color.BLUE + color.BOLD + "Bye Bye! See you next time! :)" + color.END return True elif answer.lower() == "y": print (color.BLUE + color.BOLD + """\nGreat choice! The game will start again""" + color.END) return False else: print (color.BLUE...
0
2016-05-30T13:40:35Z
[ "python", "pycharm", "tic-tac-toe" ]
TIC TAC TOE GAME - python
37,526,939
<p>i wrote a "tic tac toe" game in python(pycharm). At the end of the game i asked the user if he wants to play again: if he pressed 'y' the game began again, and if he pressed 'n' the game/code stopped. do you know how can i show him an error massege like: "you entered a wrong answer! please try again:" when he doesn'...
0
2016-05-30T13:29:34Z
37,527,214
<p>You can modify the finish function as follows:</p> <pre><code>def finish(): while True: answer = raw_input(color.PURPLE + color.BOLD + """Would you like to play again?! (press \'y\' for yes and \'n\' for no):""" + color.END) if answer.lower() == "n": print "" print colo...
1
2016-05-30T13:42:23Z
[ "python", "pycharm", "tic-tac-toe" ]
open directly "one2many form view" with create button (odoo)
37,526,998
<p>I have simple code.</p> <p>python:</p> <pre class="lang-py prettyprint-override"><code>class Test(osv.osv): _name= 'test.name' _columns= { 'name' = fields.char('Name') } </code></pre> <p>xml:</p> <pre class="lang-xml prettyprint-override"><code>&lt;record model="ir.ui.view" id="test_form_view"&gt...
2
2016-05-30T13:32:41Z
37,528,064
<p>Unfortunately, you cannot overwrite ORM methods like <code>create</code> to make them call other form, so what I recommend you is to try the following:</p> <p>Create a new transient model which is like your model <code>test.name</code>, this way:</p> <pre><code>class YourAbstractModel(osv.TransientModel): _na...
0
2016-05-30T14:25:45Z
[ "python", "forms", "openerp", "openerp-7" ]
Collapse rows based on column 1
37,527,049
<p>I want to parse InterProScan results for TopGO R package.</p> <p>I would like to have a file in a format a bit distant of what I have.</p> <pre><code># input file (gene_ID GO_ID1, GO_ID2, GO_ID3, ....) Q97R95 GO:0004349, GO:0005737, GO:0006561 Q97R95 GO:0004349, GO:0006561 Q97R95 GO:0005737, GO:0006561 Q97R95 ...
0
2016-05-30T13:35:18Z
37,527,447
<p>You can make use of 2-d array of gnu awk:</p> <pre><code>awk -F'[, ]+' '{for(i=2;i&lt;=NF;i++)r[$1][$i]} END{for(x in r){ printf "%s ",x;b=0; for(y in r[x]){printf "%s%s",(b?",":""),y;b=1} print ""} }' file </code></pre> <p>It gives:</p> <pre><code...
1
2016-05-30T13:55:22Z
[ "python", "perl", "awk", "text-processing" ]
Collapse rows based on column 1
37,527,049
<p>I want to parse InterProScan results for TopGO R package.</p> <p>I would like to have a file in a format a bit distant of what I have.</p> <pre><code># input file (gene_ID GO_ID1, GO_ID2, GO_ID3, ....) Q97R95 GO:0004349, GO:0005737, GO:0006561 Q97R95 GO:0004349, GO:0006561 Q97R95 GO:0005737, GO:0006561 Q97R95 ...
0
2016-05-30T13:35:18Z
37,532,017
<p>Here is a, hopefully tidy, Perl solution. It preserves order of keys and values as far as possible, and doesn't keep the whole file contents in memory, only as much as necessary to do the job.</p> <pre><code>#!perl use strict; use warnings; my ($prev_key, @seen_values, %seen_values); while (&lt;&gt;) { # Parse ...
0
2016-05-30T18:47:58Z
[ "python", "perl", "awk", "text-processing" ]
Encoding issue: Some letters disappear when automated typing into web input (Python 2.7.9, Webbrowser, Chrome, Windows)
37,527,057
<p>I am automating web form input via Python 2.7.9, Webbrowser, Chrome (Windows). A website has cp1251 encoding. I'm trying to send cyrillic text to the "input type=text" element. But the resulting text always misses 15 of 33 letters of the cyrillic alphabet.</p> <pre><code>text = "(Cyrillic text)" obj_name = browser....
1
2016-05-30T13:35:34Z
37,527,791
<p>Declare it as unicode and then encode. Then you can work with it somehow</p> <pre><code>text = u"Здравствуй, мир!".encode("cp1251") </code></pre>
0
2016-05-30T14:10:50Z
[ "python", "encoding", "automation" ]
Handle multiprocessing.TimeoutError in multiprocessing pool.map_async()
37,527,085
<p>Up to now I do this:</p> <pre><code>rets=set(pool.map_async(my_callback, args.hosts).get(60*4)) </code></pre> <p>If the timeout is hit, I get an exception:</p> <pre><code> File "/usr/lib/python2.7/multiprocessing/pool.py", line 524, in get raise TimeoutError multiprocessing.TimeoutError </code></pre> <p>I wo...
2
2016-05-30T13:36:43Z
37,690,720
<p>As far as I know, you can't, or at least not with <code>map_async</code>. <code>map_async</code> is a convenience method there to solve a particular problem for a particular use case, and that doesn't match up with what you've got because you want more fine control.</p> <p>However, you can still do it, you just nee...
4
2016-06-07T22:54:52Z
[ "python", "python-multiprocessing" ]
How can I set QGroupBox's title with HTML expressions? (Python)
37,527,124
<p>I want to set my <code>QGroupBox</code>'s title <strong>with HTML expressions</strong> in python program, </p> <p>e.g. : A<sub>BC</sub>. (subscript)</p> <p>Does anybody have an idea how to do this?</p>
0
2016-05-30T13:38:38Z
37,527,462
<p>The following code works for me : </p> <pre><code>QLabel *labelHTML = new QLabel("&lt;strong&gt;Hello&lt;/strong&gt; " "&lt;font color=red&gt;World!"); </code></pre> <p>This displays : </p> <p><a href="http://i.stack.imgur.com/ktXQ2.png" rel="nofollow"><img src="http://i.stack.imgur.com/ktXQ2.png" alt="enter ...
1
2016-05-30T13:55:59Z
[ "python", "html", "qt", "groupbox" ]
How can I set QGroupBox's title with HTML expressions? (Python)
37,527,124
<p>I want to set my <code>QGroupBox</code>'s title <strong>with HTML expressions</strong> in python program, </p> <p>e.g. : A<sub>BC</sub>. (subscript)</p> <p>Does anybody have an idea how to do this?</p>
0
2016-05-30T13:38:38Z
37,530,428
<p>Well, if you want just to change a style, you can call <code>setStyleSheet()</code> method for your <code>QGroupBox</code> (see code below) or use @IAmInPLS's <code>QLabel</code> example.</p> <pre><code>box-&gt;setStyleSheet("QGroupBox { color: red; } "); </code></pre>
1
2016-05-30T16:45:49Z
[ "python", "html", "qt", "groupbox" ]
How can I set QGroupBox's title with HTML expressions? (Python)
37,527,124
<p>I want to set my <code>QGroupBox</code>'s title <strong>with HTML expressions</strong> in python program, </p> <p>e.g. : A<sub>BC</sub>. (subscript)</p> <p>Does anybody have an idea how to do this?</p>
0
2016-05-30T13:38:38Z
37,535,825
<p><code>QGroupBox</code>'s <code>title</code> property does not support HTML. The only customization you can do through the <code>title</code> string (besides the text itself) is the addition of an ampersand (<code>&amp;</code>) for keyboard accelerators.</p> <p>In short, unlike <code>QLabel</code>, you can't use HTM...
1
2016-05-31T02:14:07Z
[ "python", "html", "qt", "groupbox" ]
Problems wth building Python Image Registration Toolkit
37,527,308
<p>I'm having trouble building PIRT (Python Image Registration Toolkit library). I have downloaded from bitbucket using mercurial (<code>hg clone https://bitbucket.org/almarklein/pirt</code>). But when I try to build it using <code>python setup.py</code> I get the following error:</p> <pre><code>Compiling pirt/splineg...
0
2016-05-30T13:47:40Z
37,531,270
<p>Unfortunately, I couldn't find documentation on what exact part of the functions should be declared in <code>.pxd</code> files. Thankfully, one can view the existing ones in <a href="https://github.com/cython/cython/tree/master/Cython/Includes" rel="nofollow"><code>Cython/Includes</code></a> and draw conclusions.</p...
1
2016-05-30T17:50:05Z
[ "python", "cython", "cythonize" ]
Array indexing by array-value and array-value dependant operation
37,527,348
<p>I'm developing a finite-volume heat-transfer model in python with numpy. I've got a number of cells stacked vertically (for the next year a transfer to a 3d-model is planned) with each having a different temperature.</p> <hr> <p>*To calculate the heat transfer between the cells, I need the thermal conductivity dep...
1
2016-05-30T13:49:34Z
37,545,913
<p>Try this one:</p> <pre><code>[a,b,c] = [1,2,3] Arg = numpy.array([[0.12],[0.9],[0],[0],[0.2]]) Solution = Arg Solution[Solution ==0] = 1 Solution = Solution * a * b * c print(Solution) </code></pre> <p>returns:</p> <pre><code>[[ 0.72] [ 5.4 ] [ 6. ] [ 6. ] [ 1.2 ]] </code></pre> <p>Instead of trying to lea...
2
2016-05-31T12:33:54Z
[ "python", "arrays", "python-3.x", "numpy" ]
Pandas, append column based on unique subset of column values
37,527,401
<p>I have a dataframe with many rows. I am appending a column using data produced from a custom function, like this:</p> <pre><code>import numpy df['new_column'] = numpy.vectorize(fx)(df['col_a'], df['col_b']) # takes 180964.377 ms </code></pre> <p>It is working fine, what I am trying to do is speed it up. There i...
2
2016-05-30T13:52:32Z
37,530,812
<p><strong>UPDATE:</strong></p> <p>if you can manage to read up your three columns <code>['stat','a','b_date']</code> belonging to <code>table</code> table into <code>tab</code> DF then you could merge it like this:</p> <pre><code>tab = pd.read_sql('select stat,a,b_date from table', engine) df.merge(tab, left_on=[......
1
2016-05-30T17:13:57Z
[ "python", "pandas", "optimization", "dataframe" ]
Pandas, append column based on unique subset of column values
37,527,401
<p>I have a dataframe with many rows. I am appending a column using data produced from a custom function, like this:</p> <pre><code>import numpy df['new_column'] = numpy.vectorize(fx)(df['col_a'], df['col_b']) # takes 180964.377 ms </code></pre> <p>It is working fine, what I am trying to do is speed it up. There i...
2
2016-05-30T13:52:32Z
37,531,248
<p>MaxU's answer may be already something you want. But I'll show another approach which may be a bit faster (I didn't measure).</p> <p>I assume that:</p> <ol> <li><p><code>df[['col_a', 'col_b']]</code> is sorted so that all identical entries are in consecutive rows (it's important)</p></li> <li><p><code>df</code> ha...
1
2016-05-30T17:48:12Z
[ "python", "pandas", "optimization", "dataframe" ]
Put numbers in a txt file
37,527,534
<p>I am trying to put the output of these numbers into a file but I am failing a bit. This is my code so far :</p> <pre><code>import os import sys with open('somefile.txt', 'rt') as f: print('Hello World!') os.system("pause") num = int(input("Display multiplication table of? ")) for i in range(1,1000001): pri...
-1
2016-05-30T13:58:52Z
37,528,712
<p>Two things you did wrong:</p> <p><code>- Didn't have f defined when you wrote to the file - Didn't have the file opened as a write - you had it open as a read</code></p> <p>After fixing them, the code executed perfectly!</p> <pre><code>import os import sys f = open('somefile.txt', 'wt') # CHANGED LINE print('He...
0
2016-05-30T15:00:32Z
[ "python", "math" ]
How to do a HTTP Get request with a deferred inside another (cascade defer)?
37,527,580
<p>I am want to do a GET request to check if the return code is what I expect. This request occurrs inside a function called by a addCallback of a general deferred chain, as is showed in the bellow code.</p> <p>My specif question if: <strong>How to make the return of line -D- arrives at line -E-?</strong></p> <p>It s...
0
2016-05-30T14:00:24Z
37,531,373
<p>You're using <a href="https://twistedmatrix.com/documents/current/web/howto/client.html" rel="nofollow">Twisted Agent</a> which requires running reactor to work properly, see linked examples in docs. Your code sample will work just fine if you start Twisted reactor. </p> <pre><code>if __name__ == '__main__': ts...
0
2016-05-30T17:58:29Z
[ "python", "twisted", "deferred" ]
How to do a HTTP Get request with a deferred inside another (cascade defer)?
37,527,580
<p>I am want to do a GET request to check if the return code is what I expect. This request occurrs inside a function called by a addCallback of a general deferred chain, as is showed in the bellow code.</p> <p>My specif question if: <strong>How to make the return of line -D- arrives at line -E-?</strong></p> <p>It s...
0
2016-05-30T14:00:24Z
37,540,597
<p>You are calling tst.deferredChain() synchronously and trying to read d.result within it and this is not correct. The correct solution is letting it return a deferred as well and attach to it a callback. </p>
0
2016-05-31T08:28:34Z
[ "python", "twisted", "deferred" ]
List of strings, get common substring of n elements, Python
37,527,585
<p>My problem is maybe similar to <a href="http://stackoverflow.com/questions/37514193/count-the-number-of-occurrences-of-n-length-not-given-string-in-string-python">this</a>, but another situation. Consider this list in input :</p> <pre><code>['ACCCACCCGTGG','AATCCC','CCCTGAGG'] </code></pre> <p>And the other input...
0
2016-05-30T14:00:32Z
37,527,873
<pre><code>def long_substr(data): substr = '' if len(data) &gt; 1 and len(data[0]) &gt; 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j &gt; len(substr) and is_substr(data[0][i:i+j], data): substr = data[0][i:i+j] return substr ...
1
2016-05-30T14:15:33Z
[ "python", "string", "substring" ]
List of strings, get common substring of n elements, Python
37,527,585
<p>My problem is maybe similar to <a href="http://stackoverflow.com/questions/37514193/count-the-number-of-occurrences-of-n-length-not-given-string-in-string-python">this</a>, but another situation. Consider this list in input :</p> <pre><code>['ACCCACCCGTGG','AATCCC','CCCTGAGG'] </code></pre> <p>And the other input...
0
2016-05-30T14:00:32Z
37,528,847
<p>So this is my take on it. It is definitely not the prettiest thing on the planet but it should work just fine.</p> <pre><code>a = ['ACCCWCCCGTGG', 'AATCCC', 'CCCTGAGG'] def occur(the_list, a_substr): i_found = 0 for a_string in the_list: for i_str in range(len(a_string) - len(a_substr) + 1): ...
1
2016-05-30T15:07:16Z
[ "python", "string", "substring" ]