title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to solve "No module named 'cStringIO'" when importing the logging module in Python 3
40,134,421
<p>I'm trying to run the following script, named <code>msgpack_checker.py</code>, in Python 3:</p> <pre><code>import msgpack from faker import Faker import logging from logging.handlers import RotatingFileHandler fake = Faker() fake.seed(0) data_file = "my_log.log" logger = logging.getLogger('my_logger') logger.set...
0
2016-10-19T14:33:30Z
40,134,620
<p>As pointed out in several comments, I accidentally left a directory <code>logging</code> in the same directory which is what the error message refers to. After removing that directory, I get a different error message,</p> <pre><code>Printing unpacked contents: Traceback (most recent call last): File "msgpack_chec...
0
2016-10-19T14:41:28Z
[ "python", "python-3.x" ]
Most efficient way to set value in column based on prefix of the index
40,134,453
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame(index=['pre1_xyz', 'pre1_foo', 'pre3_bar', 'pre3_foo', 'pre10_foo', 'pre10_bar', 'pre10_xyz']) </code></pre> <p>to which I want to add a column <code>values</code> whereby the value is determined based on the prefix of the index of the respective row u...
1
2016-10-19T14:34:33Z
40,134,970
<p>Because you have repeats of the prefix, you want to first separate out the prefix to make sure you don't generate a new random number for the same prefix. Therefore the removal of duplicates is necessary from your prefix list. I did this in a more condensed way by making a new column for the prefix and then using df...
3
2016-10-19T14:56:00Z
[ "python", "pandas", "optimization" ]
How to copy content of a numpy matrix to another?
40,134,604
<p>I have a simple question about basics of <code>python</code> and <code>numpy</code> module. I have a function as following:</p> <pre><code>def update_x_last(self, x): self.x_last = x </code></pre> <p>The class attribute x_last and function argument x are both initialized as of type <code>numpy.matrix</code> an...
0
2016-10-19T14:40:51Z
40,134,704
<pre><code>import numpy as np self.x_last = np.copy(x) </code></pre>
3
2016-10-19T14:44:41Z
[ "python", "numpy", "matrix" ]
How to copy content of a numpy matrix to another?
40,134,604
<p>I have a simple question about basics of <code>python</code> and <code>numpy</code> module. I have a function as following:</p> <pre><code>def update_x_last(self, x): self.x_last = x </code></pre> <p>The class attribute x_last and function argument x are both initialized as of type <code>numpy.matrix</code> an...
0
2016-10-19T14:40:51Z
40,136,875
<p>If the shapes are the same, then any of these meet both of your requirements:</p> <pre><code>self.x_last[...] = x # or self.x_last[()] = x # or self.x_last[:] = x </code></pre> <p>I'd argue that the first one is probably most clear</p> <hr> <p>Let's take a look at your requirements quickly:</p> <blockquote> <...
1
2016-10-19T16:25:07Z
[ "python", "numpy", "matrix" ]
Getting column values from multi index data frame pandas
40,134,637
<p>I have a multi index data frame shown below:</p> <pre><code> 1 2 panning sec panning sec None 5.0 None 0.0 None 6.0 None 1.0 Panning 7.0 None 2.0 None 8.0 Panning 3.0 None 9.0 None 4.0 Panning 10.0...
2
2016-10-19T14:41:57Z
40,135,270
<p><code>df.iterrows()</code> return a <code>Series</code>, if you want the original <code>index</code> you need to call the <code>name</code> of that <code>Series</code> such has:</p> <pre><code>for index,row in df.iterrows(): print row.name </code></pre>
0
2016-10-19T15:07:20Z
[ "python", "pandas" ]
Getting column values from multi index data frame pandas
40,134,637
<p>I have a multi index data frame shown below:</p> <pre><code> 1 2 panning sec panning sec None 5.0 None 0.0 None 6.0 None 1.0 Panning 7.0 None 2.0 None 8.0 Panning 3.0 None 9.0 None 4.0 Panning 10.0...
2
2016-10-19T14:41:57Z
40,135,849
<p>consider the <code>pd.DataFrame</code> <code>df</code> in the setup reference below</p> <p><strong><em>method 1</em></strong> </p> <ul> <li><code>xs</code> for cross section</li> <li><code>any(1)</code> to check if any in row</li> </ul> <hr> <pre><code>df.loc[df.xs('Panning', axis=1, level=1).eq('Panning').any(...
3
2016-10-19T15:33:35Z
[ "python", "pandas" ]
problems dealing with pandas read csv
40,134,664
<p>I've got a problem with pandas read_csv. I had a many txt files that associate with stock market.It's like this:</p> <pre><code>SecCode,SecName,Tdate,Ttime,LastClose,OP,CP,Tq,Tm,Tt,Cq,Cm,Ct,HiP,LoP,SYL1,SYL2,Rf1,Rf2,bs,s5,s4,s3,s2,s1,b1,b2,b3,b4,b5,sv5,sv4,sv3,sv2,sv1,bv1,bv2,bv3,bv4,bv5,bsratio,spd,rpd,depth1,dept...
5
2016-10-19T14:43:04Z
40,136,108
<p>Use <code>names</code> instead of <code>usecols</code> while specifying parameter.</p>
0
2016-10-19T15:45:53Z
[ "python", "pandas" ]
problems dealing with pandas read csv
40,134,664
<p>I've got a problem with pandas read_csv. I had a many txt files that associate with stock market.It's like this:</p> <pre><code>SecCode,SecName,Tdate,Ttime,LastClose,OP,CP,Tq,Tm,Tt,Cq,Cm,Ct,HiP,LoP,SYL1,SYL2,Rf1,Rf2,bs,s5,s4,s3,s2,s1,b1,b2,b3,b4,b5,sv5,sv4,sv3,sv2,sv1,bv1,bv2,bv3,bv4,bv5,bsratio,spd,rpd,depth1,dept...
5
2016-10-19T14:43:04Z
40,138,275
<p>In your message, you said that you're a running:</p> <pre><code>df = pd.read_csv('SHL1_TAQ_600000_201201.txt',usecols=fields) </code></pre> <p>Which did not throw an error for me and @Anil_M. But from your traceback, it is possible to see that the command used is another one:</p> <pre><code>df = pd.read_csv('SHL1...
1
2016-10-19T17:47:52Z
[ "python", "pandas" ]
Python/Flask: UnicodeDecodeError/ UnicodeEncodeError: 'ascii' codec can't decode/encode
40,134,690
<p>Sorry for the millionth question about this, but I've read so much about the topic and still don't get this error fixed (newbie to all of this). I'm trying to display the content of a postgres table on a website with flask (using Ubuntu 16.04/python 2.7.12). There are non-ascii characters in the table ('ü' in this ...
1
2016-10-19T14:44:06Z
40,134,981
<p>since in Python 2 bytecode is not enforced, one can get confused with them. Encoding and Decoding works as far as i know from string to bytecode and reverse. So if your resultset is a string, there should be no need to encode it again. If you get wrong representations for special characters like "§", i would try so...
0
2016-10-19T14:56:24Z
[ "python", "unicode", "utf-8", "flask", "psycopg2" ]
Python/Flask: UnicodeDecodeError/ UnicodeEncodeError: 'ascii' codec can't decode/encode
40,134,690
<p>Sorry for the millionth question about this, but I've read so much about the topic and still don't get this error fixed (newbie to all of this). I'm trying to display the content of a postgres table on a website with flask (using Ubuntu 16.04/python 2.7.12). There are non-ascii characters in the table ('ü' in this ...
1
2016-10-19T14:44:06Z
40,135,563
<p>See: <a href="https://wiki.python.org/moin/UnicodeEncodeError" rel="nofollow">https://wiki.python.org/moin/UnicodeEncodeError</a></p> <blockquote> <p>The encoding of the postgres database is utf-8. The type of queryResult[row][6] returns type 'str'. </p> </blockquote> <p>You've got it right so far. Remember, in ...
0
2016-10-19T15:20:32Z
[ "python", "unicode", "utf-8", "flask", "psycopg2" ]
Python Global Variable Not Defined - Declared inside Class
40,134,743
<p>I've seen a lot of questions on global variables, but for some reason I still can't get mine to work.</p> <p>Here is my scenario - I have my individual test cases and a separate python script that includes different functions for the various error messages you can get in the application I'm testing. If one of the...
1
2016-10-19T14:46:18Z
40,134,932
<p>You're declaring a class attribute 'failures', not a global, within the ErrorValidations</p> <p>Instead of using global failures try:</p> <pre><code>class ErrorValidations: failures = 0 def CheckforError1(driver): try: if error1.is_displayed(): ErrorValidations.failures...
1
2016-10-19T14:54:40Z
[ "python", "selenium", "testing", "qa" ]
Making a quiver plot from .dat files
40,134,745
<p>Hi I am trying to make a quiver (vector field) plot from data that is stored in .dat files. I have 4 .dat files which are 1D arrays, one for the x axis, y axis, f(x,y) along x and f(x,y) along y.</p> <p>Note, I am able to construct a quiver plot without importing data from .dat files, I just followed this basic ex...
1
2016-10-19T14:46:33Z
40,135,501
<p>In the <a href="http://www.scipy-lectures.org/intro/matplotlib/auto_examples/plot_quiver_ex.html" rel="nofollow">example for the quiver plot</a> you provided all <code>X</code>, <code>Y</code>, <code>U</code> and <code>V</code> are 2D arrays, with shape <code>(n,n)</code>.</p> <p>In your example you are importing a...
1
2016-10-19T15:17:22Z
[ "python", "matplotlib", "plot" ]
Identify drive letter of USB composite device using Python
40,134,760
<p>I have a USB composite device that has an SD card. Using Python, I need a way to find the drive letter of the SD card when the device is connected. Does anyone have experience with this? Initially it needs to work in Windows, but I'll eventually need to port it to Mac and Linux.</p>
-1
2016-10-19T14:47:27Z
40,137,725
<p>I don't have an SD card attached to a USB port. To get you started, you could <em>try</em> this on Windows. Install <a href="http://timgolden.me.uk/python/wmi/index.html" rel="nofollow">Golden's WMI</a>. I found that the Windows .zip wouldn't install but the pip version works fine, or at least it does on Win7. Then ...
0
2016-10-19T17:16:04Z
[ "python" ]
Convert .fbx to .obj with Python FBX SDK
40,134,800
<p>I have a ten frame .fbx file of an animal walking. This file includes a rigged model with textures, but I am only interested in the mesh of the model at each frame. </p> <p>How can I use Python FBX SDK or Python Blender SDK to export each frame of the fbx file into an obj file?</p> <p>Am I approaching this the w...
1
2016-10-19T14:49:20Z
40,135,741
<p>its a example for fbx to obj import fbx</p> <pre><code># Create an SDK manager manager = fbx.FbxManager.Create() # Create a scene scene = fbx.FbxScene.Create(manager, "") # Create an importer object ...
2
2016-10-19T15:28:07Z
[ "python", "blender", "maya", ".obj", "fbx" ]
cast numpy array into memmap
40,134,810
<p>I generate some data in my memory and I want to cast it into numpy.memmap to save up RAM. What should I do? my data is in:</p> <pre><code> X_list_total_standardized=np.array(X_list_total_standardized) </code></pre> <p>I know that I could initialize an empty numpy.memmap:</p> <pre><code>X_list_total_standardize...
0
2016-10-19T14:49:32Z
40,136,066
<p>I found next example in numpy documentation :</p> <pre><code>data = np.arange(12, dtype='float32') data.resize((3,4)) fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4)) fp[:] = data[:] </code></pre> <p>So your last command is ok.</p>
1
2016-10-19T15:44:09Z
[ "python", "arrays", "numpy", "numpy-memmap" ]
Issues with try/except, attempting to convert strings to integers in pandas data frame where possible
40,134,811
<p>I made a function to clean up any HTML code/tags from strings in my dataframe. The function takes every value from the data frame, cleans it with the remove_html function, and returns a clean df. After converting the data frame to string values and cleaning it up I'm attempting to convert where possible the values i...
4
2016-10-19T14:49:33Z
40,134,973
<p>insert the <code>columm.append</code> into the <code>try:</code></p> <pre><code>for col in list_of_columns: column = [] for row in list(df[col]): try: column.append(remove_html(row)) except ValueError: pass del df[col] df[col] = column return df </code></pr...
2
2016-10-19T14:56:04Z
[ "python", "pandas", "try-except" ]
Issues with try/except, attempting to convert strings to integers in pandas data frame where possible
40,134,811
<p>I made a function to clean up any HTML code/tags from strings in my dataframe. The function takes every value from the data frame, cleans it with the remove_html function, and returns a clean df. After converting the data frame to string values and cleaning it up I'm attempting to convert where possible the values i...
4
2016-10-19T14:49:33Z
40,135,527
<p>consider the <code>pd.DataFrame</code> <code>df</code></p> <pre><code>df = pd.DataFrame(dict(A=[1, '2', '_', '4'])) </code></pre> <p><a href="https://i.stack.imgur.com/m05NY.png" rel="nofollow"><img src="https://i.stack.imgur.com/m05NY.png" alt="enter image description here"></a></p> <p>You want to use the functi...
0
2016-10-19T15:18:32Z
[ "python", "pandas", "try-except" ]
Issues with try/except, attempting to convert strings to integers in pandas data frame where possible
40,134,811
<p>I made a function to clean up any HTML code/tags from strings in my dataframe. The function takes every value from the data frame, cleans it with the remove_html function, and returns a clean df. After converting the data frame to string values and cleaning it up I'm attempting to convert where possible the values i...
4
2016-10-19T14:49:33Z
40,135,720
<p>Works like this:</p> <pre><code>def clean_df(df): df = df.astype(str) list_of_columns = list(df.columns) for col in list_of_columns: column = [] for row in list(df[col]): try: column.append(int(remove_html(row))) except ValueError: column.append(remove_html(row)) ...
0
2016-10-19T15:27:24Z
[ "python", "pandas", "try-except" ]
Issues with try/except, attempting to convert strings to integers in pandas data frame where possible
40,134,811
<p>I made a function to clean up any HTML code/tags from strings in my dataframe. The function takes every value from the data frame, cleans it with the remove_html function, and returns a clean df. After converting the data frame to string values and cleaning it up I'm attempting to convert where possible the values i...
4
2016-10-19T14:49:33Z
40,135,964
<p>Use the try/except in a function and use that function with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html" rel="nofollow"><code>DataFrame.applymap()</code></a></p> <pre><code>df = pd.DataFrame([['a','b','1'], ['2','c','d'], ['e','...
0
2016-10-19T15:38:50Z
[ "python", "pandas", "try-except" ]
Django says there are no changes to be made when I migrate
40,134,859
<p>I'm attempted to create a database for a fictional school. Unfortunatley when I try to migrate the tables this happens:</p> <p>C:\Python34\Scripts\schoolDatabase>manage.py makemigrations school</p> <p>C:\Python34\Scripts\schoolDatabase>python manage.py makemigrations school No changes detected in app 'school'</p> ...
0
2016-10-19T14:51:39Z
40,136,214
<p>Your models should derive from models.Model:</p> <pre><code> class Person(models.Model): ... class Subject(models.Model): ... ... </code></pre>
0
2016-10-19T15:50:13Z
[ "python", "django", "migration" ]
getting an average of values from dictionaries with keys with a list of values
40,135,001
<p>For my final python assignment at my university I need to create functions within Jupyter Notebook to conduct a small research. I need to create dictionaries and lists from .csv files and build functions for the dictionaries that I get from my read_csv() function. For this assignment I am allowed to ask and google b...
-1
2016-10-19T14:57:21Z
40,135,158
<p><code>zip</code> the values to get the columns, and divide each column's <code>sum</code> by its <code>len</code>.</p>
0
2016-10-19T15:03:33Z
[ "python", "list", "python-2.7", "dictionary", "jupyter-notebook" ]
getting an average of values from dictionaries with keys with a list of values
40,135,001
<p>For my final python assignment at my university I need to create functions within Jupyter Notebook to conduct a small research. I need to create dictionaries and lists from .csv files and build functions for the dictionaries that I get from my read_csv() function. For this assignment I am allowed to ask and google b...
-1
2016-10-19T14:57:21Z
40,135,182
<p>First collect the values, transpose them and then its easy:</p> <pre><code># values of the dict values = data_dict.values() # transposed average averages = [sum(x)/float(len(x)) for x in zip(*values)] print (averages) </code></pre> <p>returns:</p> <pre><code>[4.333333333333333, 5.333333333333333, 6.3333333333333...
3
2016-10-19T15:04:31Z
[ "python", "list", "python-2.7", "dictionary", "jupyter-notebook" ]
getting an average of values from dictionaries with keys with a list of values
40,135,001
<p>For my final python assignment at my university I need to create functions within Jupyter Notebook to conduct a small research. I need to create dictionaries and lists from .csv files and build functions for the dictionaries that I get from my read_csv() function. For this assignment I am allowed to ask and google b...
-1
2016-10-19T14:57:21Z
40,135,200
<p>One approach could be:</p> <pre><code>data_dict = { "abc" : [1, 2, 3, 4], "def" : [4, 5, 6, 7], "ghi" : [8, 9, 10, 11] } print data_dict for i in data_dict: sum_items = 0 num_items = 0 for j in data_dict[i]: num_items += 1 sum_items += j print...
0
2016-10-19T15:05:06Z
[ "python", "list", "python-2.7", "dictionary", "jupyter-notebook" ]
String formatting of floats
40,135,080
<p>I would like to convert a number to a string in such a way that it only shows a certain number of significant digits, without superfluous zeros. The following is an example of some desired in/outputs, given that I want 5 significant digits:</p> <pre><code>0.0000123456789 &gt; 1.2346e-5 0.00123456789 &gt; 1.2346e-3 ...
0
2016-10-19T15:00:47Z
40,135,232
<pre><code>'{:.4g}'.format(float(input)) if x&lt;=1000 or x&gt;=.0001 else '{:.4e}'.format(float(input)) </code></pre>
2
2016-10-19T15:06:33Z
[ "python" ]
String formatting of floats
40,135,080
<p>I would like to convert a number to a string in such a way that it only shows a certain number of significant digits, without superfluous zeros. The following is an example of some desired in/outputs, given that I want 5 significant digits:</p> <pre><code>0.0000123456789 &gt; 1.2346e-5 0.00123456789 &gt; 1.2346e-3 ...
0
2016-10-19T15:00:47Z
40,135,307
<p>You're almost there, you just need <code>e</code>, not <code>g</code>:</p> <pre><code>"{:.5g}".format(0.000123456789) # '1.23457e-04' </code></pre> <p>Though the number in the format string indicates the amount of decimal points, so you'll want 4 (plus the one digit to the left of the decimal point):</p> <pre><co...
1
2016-10-19T15:08:39Z
[ "python" ]
String formatting of floats
40,135,080
<p>I would like to convert a number to a string in such a way that it only shows a certain number of significant digits, without superfluous zeros. The following is an example of some desired in/outputs, given that I want 5 significant digits:</p> <pre><code>0.0000123456789 &gt; 1.2346e-5 0.00123456789 &gt; 1.2346e-3 ...
0
2016-10-19T15:00:47Z
40,136,096
<pre><code>if 1 &lt;= x &lt;10000: print '{:.5g}'.format(x) elif 1 &gt; x or x &gt;= 10000: print '{:.4e}'.format(x) </code></pre> <p>Similar to A.Kot's answer but not a one liner and outputs what you want given your sample. </p>
0
2016-10-19T15:45:31Z
[ "python" ]
pylint: getting it to understand decorators
40,135,129
<p>pylint doesn't seem to take into account decorators.</p> <p>I have a decorator such that</p> <pre><code>@decorator def foo(arg1, arg2): pass </code></pre> <p>becomes</p> <pre><code>def foo(arg2): pass </code></pre> <p>but pylint keeps complaining that when I call foo I'm missing an argument. I'd rather ...
0
2016-10-19T15:02:28Z
40,135,962
<p>If you have something like that </p> <pre><code>def decorator(f): def wrapper(*args, **kwargs): return f(1, *args, **kwargs) return wrapper @decorator def z(a, b): return a + b print( z(5) ) </code></pre> <p>A simple solution that don't ask for too much change in your code is to just forget t...
0
2016-10-19T15:38:49Z
[ "python", "python-decorators", "pylint" ]
Django: create database tables programmatically/dynamically
40,135,179
<p>I've been working on a Django app for some time now and have encountered a need for dynamic model and database table generation. I've searched far and wide and it seems as though the Django API does not include this function. From what I have gathered, <a href="http://south.readthedocs.io/en/latest/databaseapi.html#...
1
2016-10-19T15:04:21Z
40,135,599
<p>The reason South is incompatible with recent Django versions is that it has been <a href="http://south.readthedocs.io/en/latest/releasenotes/1.0.html" rel="nofollow">rolled into Django</a> as of Django 1.7, under the name "migrations". If you are looking for similar functionality the starting point would be the <a h...
2
2016-10-19T15:22:07Z
[ "python", "mysql", "django", "database", "django-south" ]
Executing C++ code from python
40,135,225
<p>I am a beginner to python, and I have no idea if this seems to be a doable thing.</p> <p>I have a simple loop in python that gives me all the files in the current directory. What I want to do is to execute a C++ code I wrote before on all those files in the directory from python</p> <p>The proposed python loop sh...
1
2016-10-19T15:06:20Z
40,136,244
<p>Fairly easy to execute an external program from Python - regardless of the language:</p> <pre><code>import os import subprocess for filename in os.listdir(os.getcwd()): print filename proc = subprocess.Popen(["./myprog", filename]) proc.wait() </code></pre> <p>The list used for arguments is platfor...
1
2016-10-19T15:51:28Z
[ "python", "c++", "file", "directory" ]
How to create a subset of document using lxml?
40,135,280
<p>Suppose you have an lmxl.etree element with the contents like:</p> <pre><code>&lt;root&gt; &lt;element1&gt; &lt;subelement1&gt;blabla&lt;/subelement1&gt; &lt;/element1&gt; &lt;element2&gt; &lt;subelement2&gt;blibli&lt;/sublement2&gt; &lt;/element2&gt; &lt;/root&gt; </code></pre> <p>...
1
2016-10-19T15:07:39Z
40,136,567
<p>I am not sure there is something built-in for it, but here is a terrible, "don't ever use it in real life" type of a workaround using the <a href="http://lxml.de/api/lxml.etree._Element-class.html#iterancestors" rel="nofollow"><code>iterancestors()</code> parent iterator</a>:</p> <pre><code>from lxml import etree a...
2
2016-10-19T16:07:50Z
[ "python", "python-2.7", "lxml" ]
How to create a subset of document using lxml?
40,135,280
<p>Suppose you have an lmxl.etree element with the contents like:</p> <pre><code>&lt;root&gt; &lt;element1&gt; &lt;subelement1&gt;blabla&lt;/subelement1&gt; &lt;/element1&gt; &lt;element2&gt; &lt;subelement2&gt;blibli&lt;/sublement2&gt; &lt;/element2&gt; &lt;/root&gt; </code></pre> <p>...
1
2016-10-19T15:07:39Z
40,137,106
<p>The following code removes elements that don't have any <code>subelement1</code> descendants and are not named <code>subelement1</code>.</p> <pre><code>from lxml import etree tree = etree.parse("input.xml") # First XML document in question for elem in tree.iter(): if elem.xpath("not(.//subelement1)") and not...
1
2016-10-19T16:39:42Z
[ "python", "python-2.7", "lxml" ]
Find a certain difference between members of a list (or set) of numbers
40,135,439
<p>my first question, so please be gentle, I hope I get the formatting right :) I think the question is self explaining. I am looking for a better/faster way to find a difference in a set of numbers... maybe I want a tolerance with it. All I came up with is:</p> <pre><code> def difference(numbers,diff,tol): '''dif...
-1
2016-10-19T15:14:40Z
40,135,660
<p>You could avoid running the lowest part of the numbers in the second loop (no need for <code>low</code>, just check numbers ahead)</p> <p>With that you can drop the <code>set</code> and use a <code>list</code> instead: less hashing, less processing. Also, don't change the <code>numbers</code> input by sorting it, t...
0
2016-10-19T15:24:44Z
[ "python" ]
Find a certain difference between members of a list (or set) of numbers
40,135,439
<p>my first question, so please be gentle, I hope I get the formatting right :) I think the question is self explaining. I am looking for a better/faster way to find a difference in a set of numbers... maybe I want a tolerance with it. All I came up with is:</p> <pre><code> def difference(numbers,diff,tol): '''dif...
-1
2016-10-19T15:14:40Z
40,136,323
<pre><code> count = len(numbers) numbers1 = numbers[:count - 1] numbers2 = numbers[1:] for i in range(0, count - 1): dif = numbers2[i] - numbers1[i] if abs(dif) &lt;= tol: match.add(numbers1[i]) match.add(numbers2[i]) </code></pre>
0
2016-10-19T15:54:59Z
[ "python" ]
Reading a text file using Pandas where some rows have empty elements?
40,135,459
<p>I have a dataset in a textfile that looks like this.</p> <pre><code> 0 0CF00400 X 8 66 7D 91 6E 22 03 0F 7D 0.021650 R 0 18EA0080 X 3 E9 FE 00 0.022550 R 0 00000003 X 8 D5 64 22 E1 FF FF FF F0 0.023120 R </code></pre> <p...
5
2016-10-19T15:15:38Z
40,135,692
<p>It seems like your data is fixed width columns, you can try <code>pandas.read_fwf()</code>:</p> <pre><code>from io import StringIO import pandas as pd df = pd.read_fwf(StringIO("""0 0CF00400 X 8 66 7D 91 6E 22 03 0F 7D 0.021650 R 0 18EA0080 X 3 E9 FE 00 ...
6
2016-10-19T15:26:28Z
[ "python", "pandas" ]
Django – remove trailing zeroes for a Decimal in a template
40,135,464
<p>Is there a way to remove trailing zeros from a <code>Decimal</code> field in a django template? </p> <p>This is what I have: <code>0.0002559000</code> and this is what I need: <code>0.0002559</code>. </p> <p>There are answers suggesting to do this using <code>floatformat</code> filter:</p> <pre><code>{{ balance.b...
0
2016-10-19T15:15:47Z
40,135,465
<p>The solution is to use <code>normalize()</code> method of a <code>Decimal</code> field:</p> <pre><code>{{ balance.bitcoins.normalize }} </code></pre>
0
2016-10-19T15:15:47Z
[ "python", "django", "django-templates" ]
How to tell Python to save files in this folder?
40,135,670
<p>I am new to Python and have been assigned the task to clean up the files in Slack. I have to backup the files and save them to the designated folder Z drive Slack Files and I am using the open syntax below but it is producing the permission denied error for it. This script has been prepared by my senior to finish up...
-1
2016-10-19T15:25:17Z
40,136,124
<p>To iterate over files in a particular folder, we can simply use os.listdir() to traverse a single tree.</p> <pre><code>import os for fn in os.listdir(r'Z:\Slack_Files'): if os.path.isfile(fn): open(fn,'r') # mode is r means read mode </code></pre>
-1
2016-10-19T15:46:32Z
[ "python" ]
Python- request.post login credentials for website
40,135,835
<p>So I am trying to write this python script and add it to my Windows Task Scheduler to be executed every time I log on my Work Machine. The script should open a webpage and post my login info.</p> <pre><code>import webbrowser import os url = 'www.example.com' webbrowser.open(url) import requests url = 'www.example...
1
2016-10-19T15:33:04Z
40,140,052
<p>That is what your dict should look like</p> <pre><code>values = {'username': 'username','password': 'somepass'} </code></pre>
0
2016-10-19T19:33:06Z
[ "python", "request" ]
Continue on exception in Python
40,136,016
<p>I'm working on a series of scripts that pulls URLs from a database and uses the <a href="https://pypi.org/project/textstat/#description" rel="nofollow">textstat package</a> to calculate the readability of the page based on a set of predefined calculations. The function below takes a url (from a CouchDB), calculates...
0
2016-10-19T15:41:43Z
40,136,717
<p>It is generally good practice to keep <code>try: except:</code> blocks as small as possible. I would wrap your <code>textstat</code> functions in some sort of decorator that catches the exception you expect, and returns the function output and the exception caught.</p> <p>for example:</p> <pre><code>def catchExcep...
0
2016-10-19T16:16:30Z
[ "python", "exception-handling" ]
Ipython cv2.imwrite() not saving image
40,136,070
<p>I have written a code in python opencv. I am trying to write the processed image back to disk but the image is not getting saved and it is not showing any error(runtime and compilation) The code is</p> <pre><code>""" Created on Wed Oct 19 18:07:34 2016 @author: Niladri """ import numpy as np import cv2 if __...
0
2016-10-19T15:44:23Z
40,136,150
<p>As a general and absolute rule, you <em>have</em> to protect your windows path strings (containing backslashes) with <code>r</code> prefix or some characters are interpreted (ex: <code>\n,\b,\v,\x</code> aaaaand <code>\t</code> !):</p> <p>so when doing this:</p> <pre><code>cv2.imwrite('C:\Users\Niladri\Desktop\tro...
1
2016-10-19T15:47:37Z
[ "python", "opencv" ]
Ipython cv2.imwrite() not saving image
40,136,070
<p>I have written a code in python opencv. I am trying to write the processed image back to disk but the image is not getting saved and it is not showing any error(runtime and compilation) The code is</p> <pre><code>""" Created on Wed Oct 19 18:07:34 2016 @author: Niladri """ import numpy as np import cv2 if __...
0
2016-10-19T15:44:23Z
40,138,289
<p>As Jean suggested, the error is due to the \ being interpretted as an escape sequence. It is hence always safer to use <code>os.path.join()</code> as it is more cross platform and you need not worry about the escape sequence problem. For instance, in your case, you further need not worry about the first few argument...
0
2016-10-19T17:48:41Z
[ "python", "opencv" ]
Read a CSV to insert data into Postgres SQL with Pyhton
40,136,162
<p>I want to read a csv file to insert data into postgres SQL with Python but I have these error :</p> <pre><code> cursor.execute(passdata) psycopg2.IntegrityError: duplicate key value violates unique constraint "prk_constraint_project" DETAIL: Key (project_code)=(%s) already exists. </code></pre> <p>My code is...
0
2016-10-19T15:47:57Z
40,136,634
<p>The immediate problem with your code is that you are trying to include the literal <code>%s</code>. Since you probably did run it more than once you already have a literal <code>%s</code> in that unique column hence the exception.</p> <p>It is necessary to pass the values wrapped in an iterable as parameters to the...
0
2016-10-19T16:11:43Z
[ "python", "postgresql", "csv", "psycopg2" ]
Writing rows in a csv using dictionaries in a loop (python 3)
40,136,283
<p>I´m writing on a csv file by adding each row in a loop and using dictionaries. The following is the code:</p> <pre><code>fieldnames = ['id', 'variable1', 'variable2'] f = open('file.csv', 'w') my_writer = csv.DictWriter(f, fieldnames) my_writer.writeheader() f.close() for i in something: something wher...
0
2016-10-19T15:53:14Z
40,138,021
<p>My solution was:</p> <pre><code>fieldnames = ['id', 'variable1', 'variable2'] f= open('file.csv', 'w', newline='') my_writer = csv.DictWriter(f, fieldnames) my_writer.writeheader() for i in something: something where I get data for mydict writer.writerow(mydict) f.close() </code></pre>
0
2016-10-19T17:34:45Z
[ "python", "python-3.x", "csv", "for-loop", "dictionary" ]
How to expose user passwords in the most "secure" way in django?
40,136,285
<p>I am working on Django 1.9 project and I have been asked to enable some users to print a page with a list of a set of users and their passwords. Of course passwords are encrypted and there is no out-of-the-box ways of doing this. I know this would imply a security breach so my question is kind of contradictory, but ...
1
2016-10-19T15:53:22Z
40,136,359
<p>No, there is no logical way of doing this that doesn't imply a huge security breach in the software. </p> <p>If the passwords are stored correctly (salted and hashed), then even site admins with unrestricted access on the database can not tell you what the passwords are in plain text. </p> <p>You should push bac...
3
2016-10-19T15:56:51Z
[ "python", "django", "passwords", "password-encryption" ]
Invalid Syntax from except
40,136,295
<p>I am receiving an invalid syntax from the line that says except: from this code...</p> <pre><code>from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings import discord from discord.ext import commands import aiohttp import asyncio ...
-2
2016-10-19T15:53:41Z
40,136,379
<p>An <code>except</code> clause only makes sense after a <code>try</code> block, and there isn't one. It seems you're not looking for exception handling but simply an <code>else</code> clause.</p> <p>Either</p> <pre><code>try: code_that_might_fail() except ValueError: print("ouch.") </code></pre> <p>or</p> ...
2
2016-10-19T15:58:15Z
[ "python" ]
Invalid Syntax from except
40,136,295
<p>I am receiving an invalid syntax from the line that says except: from this code...</p> <pre><code>from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings import discord from discord.ext import commands import aiohttp import asyncio ...
-2
2016-10-19T15:53:41Z
40,136,383
<p>you should put a</p> <p><code>try-except</code> block together but in your code. You have used only the <code>except block</code>... No <code>try</code> statement.</p> <pre><code> try: if name == (): mouse = "+".join(name) link = "http://api.micetigri.fr/json/player/" + mouse ...
0
2016-10-19T15:58:27Z
[ "python" ]
how do i find my ipv4 using python?
40,136,310
<p>my server copy it if you want! :) how do i find my ipv4 using python? can i you try to keep it real short?</p> <pre><code>import socket def Main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.bind((host,port)) s.listen(1) c1, addr1 = s.accept() sending = "Connection:" + str(...
0
2016-10-19T15:54:07Z
40,136,358
<p>That's all you need for the local address (returns a string):</p> <pre><code>socket.gethostbyname(socket.gethostname()) </code></pre>
0
2016-10-19T15:56:47Z
[ "python", "python-3.x", "ipv4" ]
Python: How to filter a DataFrame of dates in Pandas by a particular date within a window of some days?
40,136,428
<p>I have a DataFrame of dates and would like to filter for a particular date +- some days.</p> <pre><code>import pandas as pd import numpy as np import datetime dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D") df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power']) </...
0
2016-10-19T16:00:50Z
40,136,429
<p>The function I created to accomplish this is <code>filterDaysWindow</code> and can be used as follows:</p> <pre><code>import pandas as pd import numpy as np import datetime dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D") df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns...
1
2016-10-19T16:00:50Z
[ "python", "date", "datetime", "pandas", "dataframe" ]
Method like argument in function
40,136,496
<p>I want use method in python / pandas like argument in a function. For example rolling statistics for dataframe:</p> <pre><code>def rolling (df, prefix = 'r', window = 3, method = 'here I wanna choose a method' ): for name in df.columns: df[prefix + name] = df[name].rolling(window).'here this method been...
2
2016-10-19T16:04:20Z
40,136,558
<p>You can use <a href="https://docs.python.org/3.6/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> with a str of the name of the method. This gets the attribute with that name from the object (In this case, a method)</p> <pre><code>def rolling (df, prefix='r', window=3, method='sum'): for ...
3
2016-10-19T16:07:10Z
[ "python", "function", "pandas", "methods" ]
Method like argument in function
40,136,496
<p>I want use method in python / pandas like argument in a function. For example rolling statistics for dataframe:</p> <pre><code>def rolling (df, prefix = 'r', window = 3, method = 'here I wanna choose a method' ): for name in df.columns: df[prefix + name] = df[name].rolling(window).'here this method been...
2
2016-10-19T16:04:20Z
40,136,571
<p>I do this</p> <pre><code>def rolling (df, prefix='r', window=3, method='method_name'): for name in df.columns: df[prefix + name] = df[name].rolling(window).__getattribute__(method)() return df </code></pre>
1
2016-10-19T16:08:05Z
[ "python", "function", "pandas", "methods" ]
Method like argument in function
40,136,496
<p>I want use method in python / pandas like argument in a function. For example rolling statistics for dataframe:</p> <pre><code>def rolling (df, prefix = 'r', window = 3, method = 'here I wanna choose a method' ): for name in df.columns: df[prefix + name] = df[name].rolling(window).'here this method been...
2
2016-10-19T16:04:20Z
40,136,587
<p>A method is an attribute like any other (it just happens to be callable when bound to an object), so you can use <code>getattr</code>. (A default value of <code>None</code> is nonsense, of course, but I didn't want to reorder your signature to make <code>method</code> occur earlier without a default value.)</p> <pr...
0
2016-10-19T16:09:07Z
[ "python", "function", "pandas", "methods" ]
Append to dictionary in defaultdict
40,136,544
<p>I have a defaultdict, I want to create a dictionary as the value part, can I append to this dictionary? At the moment I am appending to a list which means that the dictionaries are separated. </p> <pre><code>dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.dat...
0
2016-10-19T16:06:22Z
40,137,056
<p>if i understood you correctly, you want to replace the list with a dict, that you can later add to it values.</p> <p>if so you can do this:</p> <pre><code>dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.date(2016, 10, 20), datetime.date(2016, 10, 21), dateti...
0
2016-10-19T16:36:49Z
[ "python", "defaultdict" ]
Append to dictionary in defaultdict
40,136,544
<p>I have a defaultdict, I want to create a dictionary as the value part, can I append to this dictionary? At the moment I am appending to a list which means that the dictionaries are separated. </p> <pre><code>dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.dat...
0
2016-10-19T16:06:22Z
40,137,304
<p>if i understand correctly</p> <pre><code>import datetime dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.date(2016, 10, 20), datetime.date(2016, 10, 21), datetime.date(2016, 10, 22), datetime.date(2016, 10, 23)] dict_x = {} for i in map(str,set(dates)): ...
0
2016-10-19T16:51:20Z
[ "python", "defaultdict" ]
Learn Python the Hard way ex25 - Want to check my understanding
40,136,550
<p>total noob here confused all to hell about something in "Learn Python the Hard Way." Apologies if this has been covered; I searched and could only find posts about not getting the desired results from the code.</p> <p>My question relates to the interaction of two functions in <a href="https://learnpythonthehardway....
1
2016-10-19T16:06:40Z
40,137,282
<p>How Python functions more or less work is the following:</p> <pre><code>def function_name(parameter_name_used_locally_within_function_name): #do stuff with parameter_name_used_locally_within_function_name some_new_value = parameter_name_used_locally_within_function_name return some_new_value </code></p...
1
2016-10-19T16:49:58Z
[ "python" ]
Learn Python the Hard way ex25 - Want to check my understanding
40,136,550
<p>total noob here confused all to hell about something in "Learn Python the Hard Way." Apologies if this has been covered; I searched and could only find posts about not getting the desired results from the code.</p> <p>My question relates to the interaction of two functions in <a href="https://learnpythonthehardway....
1
2016-10-19T16:06:40Z
40,137,638
<blockquote> <p>that the argument label doesn't matter</p> </blockquote> <p>It matters in the sense that it's used "locally" within the function definition. Basically think of it as another local variable you define in the function definition but the values of the arguments are given to the function.</p> <p>Keepin...
0
2016-10-19T17:10:37Z
[ "python" ]
Django: authenticate the user
40,136,636
<p>I have the following code:</p> <p><strong># creating user:</strong></p> <pre><code>def create_user(request): if request.method == 'POST': user_info = forms.UserInfoForm(request.POST) if user_info.is_valid(): cleaned_info = user_info.cleaned_data User.objects.create_user(...
0
2016-10-19T16:11:55Z
40,137,099
<p>Save the user in one var, and then call user.save() because User can't call the method save() try it:</p> <pre><code>def create_user(request): if request.method == 'POST': user_info = forms.UserInfoForm(request.POST) if user_info.is_valid(): cleaned_info = user_info.c...
0
2016-10-19T16:39:21Z
[ "python", "django" ]
Django: authenticate the user
40,136,636
<p>I have the following code:</p> <p><strong># creating user:</strong></p> <pre><code>def create_user(request): if request.method == 'POST': user_info = forms.UserInfoForm(request.POST) if user_info.is_valid(): cleaned_info = user_info.cleaned_data User.objects.create_user(...
0
2016-10-19T16:11:55Z
40,137,547
<p>Your code seems to be correct. </p> <p>The problem might be in the way the params are being passed to your <code>create_user</code> view (Param passing in <code>get_entry</code> view highly unlikely to be a problem since the params <code>username</code> and <code>password</code> are hard-coded).</p> <p>Try printin...
0
2016-10-19T17:05:32Z
[ "python", "django" ]
'Stack()' output with all Individual index's filled in Pandas DataFrame
40,136,651
<p>I have the following DataFrame:</p> <pre><code>import pandas as pd import numpy as np dates = pd.date_range('20130101',periods=6) df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD')) </code></pre> <p>which is:</p> <pre><code>out[]:df A B C D 2013-0...
1
2016-10-19T16:12:41Z
40,137,007
<p>the relevant pandas option is <code>'display.multi_sparse'</code><br> you can set it yourself with</p> <pre><code>pd.set_option('display.multi_sparse', False) </code></pre> <p>or use <code>pd.option_context</code> to temporarily set it in a <code>with</code> block</p> <pre><code>with pd.option_context('display.mu...
1
2016-10-19T16:33:44Z
[ "python", "pandas", "dataframe", "data-munging" ]
Using Google API for Python- where do I get the client_secrets.json file from?
40,136,699
<p>I am looking into using the Google API to allow users to create/ edit calendar entries in a company calendar (Google calendar) from within iCal.</p> <p>I'm following the instructions at: <a href="https://developers.google.com/api-client-library/python/auth/web-app" rel="nofollow">https://developers.google.com/api-c...
0
2016-10-19T16:15:37Z
40,136,814
<p>If you go to your <a href="https://console.developers.google.com/apis/credentials" rel="nofollow">Google developers console</a> you should see a section titled <strong>OAuth 2.0 client IDs</strong>. Click on an entry in that list, and you will see a number of fields, including <strong>Client secret</strong>. </p> <...
0
2016-10-19T16:22:24Z
[ "python", "json", "google-api" ]
AWS Lambda sending HTTP request
40,136,746
<p>This is likely a question with an easy answer, but i can't seem to figure it out.</p> <p>Background: I have a python Lambda function to pick up changes in a DB, then using HTTP post the changes in json to a URL. I'm using urllib2 sort of like this:</p> <pre><code># this runs inside a loop, in reality my error hand...
0
2016-10-19T16:18:27Z
40,139,889
<p>If you've deployed your Lambda function inside your VPC, it does not obtain a public IP address, even if it's deployed into a subnet with a route to an Internet Gateway. It only obtains a private IP address, and thus can not communicate to the public Internet by itself.</p> <p>To communicate to the public Internet...
2
2016-10-19T19:22:55Z
[ "python", "python-2.7", "amazon-web-services", "aws-lambda" ]
How to assert call order and parameters when mocking multiple calls to the same method?
40,136,811
<p>I have multiple calls to the same mock and I want to check each calls parameters and order in which it was called.</p> <p>E.g. if I needed to check just the last call, I would use this:</p> <pre><code>mock.assert_called_once_with( 'GET', 'https://www.foobar.com', params=OrderedDict([ ('email', ...
0
2016-10-19T16:22:12Z
40,136,908
<p>You probably want to use the <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls" rel="nofollow"><code>Mock.assert_has_calls</code></a> method.</p> <pre><code>self.assertEqual(self.request_mock.call_count, 2) self.request_mock.assert_has_calls([ mock.call( '...
3
2016-10-19T16:27:41Z
[ "python", "unit-testing", "mocking" ]
Filter by a Reference Property in Appnengine
40,136,910
<p>I am doing a blog in appengine. I want make a query to get the numbers of post by category. So I need filter by a Reference Property in appengine. Look my actual Code.</p> <p>Those are my models :</p> <pre><code>class Comment(db.Model) : user = db.ReferenceProperty(User) post = db.ReferenceProperty(Blog) ...
0
2016-10-19T16:28:02Z
40,141,393
<p>I haven't used <code>db</code> in a while, but I think something like this will work:</p> <pre><code>count = 0 # Get all blogs of the desired category blogs = Blog.all().filter("category =", cat.key()) for blog in blogs: # For each blog, count all the comments. count += Comment.all().filter("post =", blog.k...
0
2016-10-19T20:57:18Z
[ "python", "google-app-engine", "gae-datastore" ]
Call a Python function with arguments based on user input
40,136,965
<p>I would like to call a function from a user input, but include arguments in the parenthesis. For example, if I have a function that takes one argument:</p> <pre><code>def var(value): print(value) </code></pre> <p>I would like to ask the user for a command and arguments, then call the function with the argumen...
-2
2016-10-19T16:30:52Z
40,137,267
<p>Split the function name from the arguments. Look up the function by name using a predefined map. Parse the arguments with <code>literal_eval</code>. Call the function with the arguments.</p> <pre><code>available = {} def register_func(f): available[f.__name__] = f @register_func def var(value): print(v...
6
2016-10-19T16:49:04Z
[ "python" ]
Call a Python function with arguments based on user input
40,136,965
<p>I would like to call a function from a user input, but include arguments in the parenthesis. For example, if I have a function that takes one argument:</p> <pre><code>def var(value): print(value) </code></pre> <p>I would like to ask the user for a command and arguments, then call the function with the argumen...
-2
2016-10-19T16:30:52Z
40,137,349
<p>I am going to post this solution as an alternative, under the assumption that you are dealing with <em>simple</em> inputs such as: </p> <pre><code>var(arg) </code></pre> <p>Or, a single function call that can take a list of positional arguments. </p> <p>By using <code>eval</code> it would be a horrible un-recomme...
1
2016-10-19T16:53:15Z
[ "python" ]
Call a Python function with arguments based on user input
40,136,965
<p>I would like to call a function from a user input, but include arguments in the parenthesis. For example, if I have a function that takes one argument:</p> <pre><code>def var(value): print(value) </code></pre> <p>I would like to ask the user for a command and arguments, then call the function with the argumen...
-2
2016-10-19T16:30:52Z
40,137,449
<p>Instead of using eval, you can parse it yourself. This way, you have control over how each function should parse/deserialize the user input's arguments.</p> <pre class="lang-python prettyprint-override"><code>import sys, re def custom_print(value): print value def custom_add(addends): print sum(addends) ...
0
2016-10-19T16:59:36Z
[ "python" ]
Call a Python function with arguments based on user input
40,136,965
<p>I would like to call a function from a user input, but include arguments in the parenthesis. For example, if I have a function that takes one argument:</p> <pre><code>def var(value): print(value) </code></pre> <p>I would like to ask the user for a command and arguments, then call the function with the argumen...
-2
2016-10-19T16:30:52Z
40,138,089
<p>You should investigate the <a href="https://docs.python.org/2/library/cmd.html?highlight=cmd#module-cmd" rel="nofollow">cmd</a> module. This allows you to parse input similar to shell commands, but I believe you can get tricky and change the delimiters if the parentheses are an important part of the specification.</...
1
2016-10-19T17:38:03Z
[ "python" ]
Validating input with inquirer
40,137,035
<p>I'm trying to check if the length of my input is valid like this:</p> <pre><code>questions = [ inquirer.Text('b_file', message='.GBK File', validate=lambda file: len(str(file))), inquirer.Text('e_file', message='.XLS File', validate=lambda file: len(str(file)))] </code></...
1
2016-10-19T16:35:09Z
40,137,206
<p>The function used for <code>validate</code> must take <strong>two</strong> arguments; the first is a dictionary with previously given answers, and the second is the current answer.</p> <p>The <a href="https://github.com/magmax/python-inquirer/blob/master/inquirer/questions.py#L115-L121" rel="nofollow">code to handl...
0
2016-10-19T16:44:47Z
[ "python" ]
How to find the longest sub-array within a threshold?
40,137,051
<p>Let's say you have a sorted array of numbers <code>sorted_array</code> and a threshold <code>threshold</code>. What is the fastest way to find the longest sub-array in which all the values are within the threshold? In other words, find indices <code>i</code> and <code>j</code> such that:</p> <ol> <li><code>sorted_a...
1
2016-10-19T16:36:27Z
40,137,068
<p>Here's a simple loop-based solution in Python:</p> <pre><code>def longest_subarray_within_threshold(sorted_array, threshold): result = (0, 0) longest = 0 i = j = 0 end = len(sorted_array) while i &lt; end: if j &lt; end and sorted_array[j] - sorted_array[i] &lt;= threshold: c...
2
2016-10-19T16:37:28Z
[ "python", "arrays", "algorithm", "numpy" ]
How to find the longest sub-array within a threshold?
40,137,051
<p>Let's say you have a sorted array of numbers <code>sorted_array</code> and a threshold <code>threshold</code>. What is the fastest way to find the longest sub-array in which all the values are within the threshold? In other words, find indices <code>i</code> and <code>j</code> such that:</p> <ol> <li><code>sorted_a...
1
2016-10-19T16:36:27Z
40,137,780
<p>Here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>def longest_thresh_subarray(sorted_array,thresh): diffs = (sorted_array[:,None] - sorted_array) r = np.arange(sorted_array.size) valid...
0
2016-10-19T17:19:16Z
[ "python", "arrays", "algorithm", "numpy" ]
How to find the longest sub-array within a threshold?
40,137,051
<p>Let's say you have a sorted array of numbers <code>sorted_array</code> and a threshold <code>threshold</code>. What is the fastest way to find the longest sub-array in which all the values are within the threshold? In other words, find indices <code>i</code> and <code>j</code> such that:</p> <ol> <li><code>sorted_a...
1
2016-10-19T16:36:27Z
40,138,678
<p>Most likely, the OP's own answer is the best possible algorithm, as it is O(n). However, the pure-python overhead makes it very slow. However, this overhead can easily be reduced by compiling the algorithm using <a href="http://numba.pydata.org/" rel="nofollow" title="numba">numba</a>, with the current version (0.28...
2
2016-10-19T18:10:35Z
[ "python", "arrays", "algorithm", "numpy" ]
Why is hash() slower under python3.4 vs python2.7
40,137,072
<p>I was doing some performance evaluation using timeit and discovered a performance degredation between python 2.7.10 and python 3.4.3. I narrowed it down to the <code>hash()</code> function:</p> <p>python 2.7.10:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit('for x in xrange(100): hash(x)', n...
4
2016-10-19T16:37:45Z
40,137,700
<p>There are two changes in <code>hash()</code> function between Python 2.7 and Python 3.4</p> <ol> <li>Adoptions of <em>SipHash</em></li> <li>Default enabling of <em>Hash randomization</em></li> </ol> <hr> <p><em>References:</em></p> <ul> <li>Since from Python 3.4, it uses <a href="https://131002.net/siphash/" rel...
2
2016-10-19T17:14:42Z
[ "python", "python-3.4" ]
How to make multiple file from different folder same name in one file in python
40,137,134
<p>I want to combine multiple file from different folder data in one file but only same file name is all folder</p> <p>Script:</p> <pre><code>import os filenames = [os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Input/','*.txt'), os.path.join('C:/Users/Vishnu/Desktop/Test_folder/Output/','*.txt')] f = open(r'C:/U...
0
2016-10-19T16:41:13Z
40,137,208
<p>Firstly, you are trying to open the folder itself. Secondly, we have to close the file everytime we read it to avoid Permission issues</p> <p>I tried this code. It should work now</p> <pre><code>import os import glob #So that * in directory listing can be interpretted as all filenames filenames = [glob.glob(os...
1
2016-10-19T16:44:50Z
[ "python", "python-2.7", "python-3.x" ]
draw horizontal bars on the same line
40,137,137
<p>I have to draw a gantt resource type of chart. Idea is to draw several horizontal bars on the same line (corresponding to a resource) each length represented by start date and and date</p> <p>this is the expected result: <a href="https://i.stack.imgur.com/aqj97.png" rel="nofollow"><img src="https://i.stack.imgur.co...
-2
2016-10-19T16:41:15Z
40,137,659
<p>Actually, I'm gonna cheat and post you something straight from the <a href="http://matplotlib.org/users/event_handling.html#draggable-rectangle-exercise" rel="nofollow">Matplotlib Documentation</a>. This should get you started with draggable objects in mpl. you'll have to come up with your own dynamic object creatio...
1
2016-10-19T17:11:54Z
[ "python", "bar-chart" ]
read data in specific column and row of a text file
40,137,219
<p>I Have a text file which contain 3 columns and 20000 rows. I like to know what should I do to get the specific data (for example) in row 1000 and column 2? My first column is formatted like AAAA and my second column is a number like 1234. I tried this solution but I got an error based on my first column being letter...
1
2016-10-19T16:45:29Z
40,137,335
<p>You are trying to use <code>float()</code> on something that contains letters. this happens when you call:</p> <pre><code>numfloat = map(float , line.split()) </code></pre> <p>You need to tell us the exact output that you are looking for but here is one possible solution</p> <pre><code>num_float = map(float, li...
2
2016-10-19T16:52:36Z
[ "python", "text", "row", "line" ]
read data in specific column and row of a text file
40,137,219
<p>I Have a text file which contain 3 columns and 20000 rows. I like to know what should I do to get the specific data (for example) in row 1000 and column 2? My first column is formatted like AAAA and my second column is a number like 1234. I tried this solution but I got an error based on my first column being letter...
1
2016-10-19T16:45:29Z
40,137,486
<p>make '=' to '==' at line 3 of your code </p> <pre><code>with open('my_file', 'r') as f: for x, line in enumerate(f): if x == 1000: print float(line.split()[1]) </code></pre>
0
2016-10-19T17:01:33Z
[ "python", "text", "row", "line" ]
read data in specific column and row of a text file
40,137,219
<p>I Have a text file which contain 3 columns and 20000 rows. I like to know what should I do to get the specific data (for example) in row 1000 and column 2? My first column is formatted like AAAA and my second column is a number like 1234. I tried this solution but I got an error based on my first column being letter...
1
2016-10-19T16:45:29Z
40,137,562
<pre><code>import re with open('my_file', 'r') as f: for x, line in enumerate(f): if x == 1000: array = re.split('(\d+)',line) # array=['AAAA','123'] if line='AAAA123' print array[1] # your required second row. </code></pre>
0
2016-10-19T17:06:12Z
[ "python", "text", "row", "line" ]
Exponentional values in Python Pandas
40,137,232
<p>Have a case of quite huge numbers in python pandas, so the dataframe looks like this:</p> <pre><code>trades 4.536115e+07 3.889124e+07 2.757327e+07 </code></pre> <p>How can these numbers be transformed into "normal" values from exponential in pandas?</p> <p>Thanks!</p>
0
2016-10-19T16:46:38Z
40,137,374
<pre><code>&gt;&gt;&gt; float(4.536115e+07) 45361150.0 </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; f = 4.536115e+07 &gt;&gt;&gt; "%.16f" % f '45361150.0000000000000000' </code></pre>
0
2016-10-19T16:54:58Z
[ "python", "pandas", "dataframe", "exponential" ]
Exponentional values in Python Pandas
40,137,232
<p>Have a case of quite huge numbers in python pandas, so the dataframe looks like this:</p> <pre><code>trades 4.536115e+07 3.889124e+07 2.757327e+07 </code></pre> <p>How can these numbers be transformed into "normal" values from exponential in pandas?</p> <p>Thanks!</p>
0
2016-10-19T16:46:38Z
40,137,528
<p>You could change the pandas options as such:</p> <pre><code>&gt;&gt;&gt; data = np.array([4.536115e+07, 3.889124e+07, 2.757327e+07]) &gt;&gt;&gt; pd.set_option('display.float_format', lambda x: '%.f' % x) &gt;&gt;&gt; pd.DataFrame(data, columns=['trades']) trades 0 45361150 1 38891240 2 27573270 </code><...
1
2016-10-19T17:04:03Z
[ "python", "pandas", "dataframe", "exponential" ]
Error when passing parameter to form
40,137,243
<p>I'm trying to pass a parameter to a form, in this case is an object_id. The form gets used only on the <em>change_view</em>, this code works:</p> <p>My form:</p> <pre><code>class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.my_id = kwargs.pop('my_id', None) super(MyForm, s...
0
2016-10-19T16:47:39Z
40,143,003
<p>In <code>self.form = MyForm</code> you assign a class object to self.form. In <code>self.form = MyForm(my_id=obj_id)</code> you instantiate an object of class MyForm and assign it to self.form. </p> <p>Django expect to find a class in <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib...
0
2016-10-19T23:15:34Z
[ "python", "django", "django-forms" ]
Concatinating multiple Data frames of different length
40,137,372
<p>I have 88 different dataFrame of different lengths, which I need to concatenate. And its all are located in one directory and I used the following python script to produce such a single data frame.</p> <p>Here is what I tried,</p> <pre><code> path = 'GTFS/' files = os.listdir(path) files_txt = [os.path....
0
2016-10-19T16:54:51Z
40,139,190
<p>The key is to make a <code>list</code> of different data-frames and then concatenate the list instead of individual concatenation.</p> <p>I created 10 <code>df</code> filled with random length data of one column and saved to <code>csv</code> files to simulate your data.</p> <pre><code>import pandas as pd import nu...
2
2016-10-19T18:39:22Z
[ "python", "pandas", "numpy", "dataframe" ]
Calc value count in few columns of DataFrame (Pandas Python)
40,137,389
<p>I have a dataFrame: </p> <pre><code> id code_1 code_2 0 11 1451 ffx 1 15 2233 ffx 2 24 1451 mmg 3 15 1451 ffx </code></pre> <p>I need get number of each code value (for all code_1 values and all code_2 values) for unique id. For example:</p> <pre><code> id 1451 2233 ...
0
2016-10-19T16:55:59Z
40,140,491
<p>Consider merging pivot_tables using the aggfunc <em>len</em> for counts.</p> <pre><code>from io import StringIO import pandas as pd data = ''' id code_1 code_2 11 1451 ffx 15 2233 ffx 24 1451 mmg 15 1451 ffx''' df = pd.read_table(StringIO(data), sep="\s+") df = pd.merge(df[['id',...
1
2016-10-19T20:01:13Z
[ "python", "pandas", "dataframe" ]
Python - reduce complexity using sets
40,137,536
<p>I am using <code>url_analysis</code> tools from <code>spotify</code> <code>API</code> (wrapper <code>spotipy</code>, with <code>sp.</code>) to process tracks, using the following code:</p> <pre><code>def loudness_drops(track_ids): names = set() tids = set() tracks_with_drop_name = set() tracks_with_drop_id = set()...
-2
2016-10-19T17:04:33Z
40,138,843
<p>This is what I see, not knowing much about spotify:</p> <pre><code>for id_ in track_ids: # this runs N times, where N = len(track_ids) ... tids.add(track_id) # tids contains all track_ids processed until now # in the end: len(tids) == N ... features = sp.audio_features(tids) # features ...
0
2016-10-19T18:20:19Z
[ "python", "list", "set", "time-complexity", "spotify" ]
Having troubles with pip and importing
40,137,597
<p>I have both Python 3.5 and Python 2.7 installed. I install tweepy via CMD using " python -m pip install tweepy", yet when I import tweepy in either IDLE 2.7 or 3.5, I get the error "Module not installed", even though CMD says it has downloaded and installed it properly.</p> <p>What could be the error, as I think th...
0
2016-10-19T17:08:08Z
40,137,642
<p>Launch python 2.7 and type </p> <p><code>&gt;&gt;&gt;import tweepy</code></p> <p>Than launch python 3.5 and type </p> <pre><code>&gt;&gt;&gt;import tweepy </code></pre> <p>Whichever one does not work means that is probably not your default Python installation.</p> <p>One of your Python installations doesn't hav...
1
2016-10-19T17:10:47Z
[ "python", "python-2.7", "pip" ]
webdriver + reset Chrome
40,137,619
<p>I'm trying to 'reset' Chrome browser using webdriver(python). What I'm doing is:</p> <blockquote> <p>driver = webdriver.Chrome()</p> <p>driver.get('chrome://settings/resetProfileSettings')</p> </blockquote> <p>above shows pop-up with 'reset' button, and I can't locate it using </p> <blockquote> <p>driver...
0
2016-10-19T17:09:25Z
40,137,784
<pre><code>driver = webdriver.Chrome() main_window_handle = None while not main_window_handle: main_window_handle = driver.current_window_handle popup_handle = None while not popup_handle: for handle in driver.window_handles: if handle != main_window_handle: popup_handle = handle ...
0
2016-10-19T17:19:40Z
[ "python", "google-chrome", "webdriver" ]
how does pickle know which to pick?
40,137,712
<p>I have my pickle function working properly</p> <pre><code> with open(self._prepared_data_location_scalar, 'wb') as output: # company1 = Company('banana', 40) pickle.dump(X_scaler, output, pickle.HIGHEST_PROTOCOL) pickle.dump(Y_scaler, output, pickle.HIGHEST_PROTOCOL) with open(self....
1
2016-10-19T17:15:24Z
40,137,758
<p>wow I did not even know you could do this ... and I have been using python for a very long time... so thats totally awesome in my book, however you really should not do this it will be very hard to work with later(especially if it isnt you working on it)</p> <p>I would recommend just doing </p> <pre><code>pickle...
2
2016-10-19T17:18:13Z
[ "python", "pickle" ]
how does pickle know which to pick?
40,137,712
<p>I have my pickle function working properly</p> <pre><code> with open(self._prepared_data_location_scalar, 'wb') as output: # company1 = Company('banana', 40) pickle.dump(X_scaler, output, pickle.HIGHEST_PROTOCOL) pickle.dump(Y_scaler, output, pickle.HIGHEST_PROTOCOL) with open(self....
1
2016-10-19T17:15:24Z
40,137,793
<p>Yes, pickle pick objects in order of saving.</p> <p>Intuitively, pickle append to the end when it write (dump) to a file, and read (load) sequentially the content from a file.</p> <p>Consequently, order is preserved, allowing you to retrieve your data in the exact order you serialize it.</p>
1
2016-10-19T17:20:30Z
[ "python", "pickle" ]
how does pickle know which to pick?
40,137,712
<p>I have my pickle function working properly</p> <pre><code> with open(self._prepared_data_location_scalar, 'wb') as output: # company1 = Company('banana', 40) pickle.dump(X_scaler, output, pickle.HIGHEST_PROTOCOL) pickle.dump(Y_scaler, output, pickle.HIGHEST_PROTOCOL) with open(self....
1
2016-10-19T17:15:24Z
40,137,943
<p>What you have is fine. It's a <a href="https://docs.python.org/2/library/pickle.html#pickle.Pickler" rel="nofollow">documented feature</a> of pickle:</p> <blockquote> <p>It is possible to make multiple calls to the dump() method of the same Pickler instance. These must then be matched to the same number of calls...
5
2016-10-19T17:30:29Z
[ "python", "pickle" ]
Using subprocess for accessing HBase
40,137,812
<p>I'm trying simple commands to access HBase through subprocess in Python. The following code gives me the wrong output:</p> <pre><code>import subprocess cmd=['hbase','shell','list'] subprocess.call(cmd) </code></pre> <p>Instead of giving me the list of tables in HBase, I get the following output: </p> <pre><code> ...
1
2016-10-19T17:21:39Z
40,137,966
<p>If you need to access HBase from Python I strongly suggest you looks at the <strong>happybase</strong> modules.</p> <p>I have been using them in production for the past 4 years - and they have simplified our ETL tasks.</p> <p>Out of the box they are Python 2.X, but with a few minutes work - you can upgrade them to...
0
2016-10-19T17:31:26Z
[ "python", "subprocess", "hbase" ]
AttributeError when creating tkinter.PhotoImage object with PIL.ImageTk
40,137,813
<p>I am trying to place an image resized with PIL in a tkinter.PhotoImage object. </p> <pre><code>import tkinter as tk # I use Python3 from PIL import Image, ImageTk master = tk.Tk() img =Image.open(file_name) image_resized=img.resize((200,200)) photoimg=ImageTk.PhotoImage(image_resized) </code></pre> <p>However, wh...
-1
2016-10-19T17:21:43Z
40,138,134
<p><code>ImageTk.PhotoImage</code> as in <code>PIL.ImageTk.PhotoImage</code> is not the same class as <code>tk.PhotoImage</code> (<code>tkinter.PhotoImage</code>) they just have the same name</p> <p>here is ImageTk.PhotoImage docs: <a href="http://pillow.readthedocs.io/en/3.1.x/reference/ImageTk.html#PIL.ImageTk.Phot...
2
2016-10-19T17:40:39Z
[ "python", "tkinter", "python-imaging-library", "photoimage" ]
Sort a List of a Tuple.. of a list. Case insensitive
40,138,048
<p>So what I have currently is a string that looks like this, </p> <pre><code>hello here, hello there, hello Everywhere </code></pre> <p>I'm making a iteration of kwic if anyone knows what that is. The format that is required is a list of tuples.. of list while sorting case insensitive. So in the end I have a unsorte...
0
2016-10-19T17:36:04Z
40,138,115
<p>Right now, your sort is only taking into account the first word in the list. In order to make it sort lexicographically based on <em>all</em> the words in the list, your sort key should return a <em>list</em> of lower-cased words (one lower-cased word for each word in the input list)</p> <pre><code>def sort_key(t)...
2
2016-10-19T17:39:26Z
[ "python" ]
Sort a List of a Tuple.. of a list. Case insensitive
40,138,048
<p>So what I have currently is a string that looks like this, </p> <pre><code>hello here, hello there, hello Everywhere </code></pre> <p>I'm making a iteration of kwic if anyone knows what that is. The format that is required is a list of tuples.. of list while sorting case insensitive. So in the end I have a unsorte...
0
2016-10-19T17:36:04Z
40,138,148
<pre><code>Final_Array.sort(key=lambda x: list(map(str.lower, x[0]))) </code></pre>
-1
2016-10-19T17:41:35Z
[ "python" ]
Drawing on python and pycharm
40,138,060
<p>I am a beginner on Python. I draw a square with this code.</p> <pre><code>import turtle square=turtle.Turtle() print(square) for i in range(4): square.fd(100) square.lt(90) turtle.mainloop() </code></pre> <p>However, there is another code for drawing square with this code in the book. Apparently, I tried t...
1
2016-10-19T17:36:42Z
40,138,217
<p>You need to call the function so it will start:</p> <pre><code>import turtle def drawSquare(t, size): for i in range(4): t.forward(size) t.left(90) turtle.mainloop() drawSquare(turtle.Turtle(), 100) </code></pre>
2
2016-10-19T17:45:03Z
[ "python", "turtle-graphics" ]
Work with a row in a pandas dataframe without incurring chain indexing (not coping just indexing)
40,138,090
<p>My data is organized in a dataframe:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) </code></pre> <p>Which looks like this (only...
0
2016-10-19T17:38:08Z
40,138,251
<p>This should work:</p> <pre><code>row_of_interest = df.loc['R2', :] row_of_interest.is_copy = False row_of_interest['Col2'] = row_of_interest['Col2'] + 1000 </code></pre> <p>Setting <code>.is_copy = False</code> is the trick</p> <p>Edit 2:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4...
0
2016-10-19T17:46:39Z
[ "python", "pandas", "indexing", "dataframe", "series" ]
Work with a row in a pandas dataframe without incurring chain indexing (not coping just indexing)
40,138,090
<p>My data is organized in a dataframe:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) </code></pre> <p>Which looks like this (only...
0
2016-10-19T17:38:08Z
40,138,272
<p>most straight forward way to do this</p> <pre><code>df.loc['R2', 'Col2'] += 1000 df </code></pre> <p><a href="https://i.stack.imgur.com/5m2KA.png" rel="nofollow"><img src="https://i.stack.imgur.com/5m2KA.png" alt="enter image description here"></a></p>
0
2016-10-19T17:47:37Z
[ "python", "pandas", "indexing", "dataframe", "series" ]
Work with a row in a pandas dataframe without incurring chain indexing (not coping just indexing)
40,138,090
<p>My data is organized in a dataframe:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) </code></pre> <p>Which looks like this (only...
0
2016-10-19T17:38:08Z
40,138,567
<p>You can remove the warning by creating a series with the slice you want to work on:</p> <pre><code>from pandas import Series row_of_interest = Series(data=df.loc['R2', :]) row_of_interest.loc['Col2'] += 1000 print(row_of_interest) </code></pre> <p>Results in:</p> <pre><code>Col1 5 Col2 1020 Col3 50 ...
0
2016-10-19T18:03:22Z
[ "python", "pandas", "indexing", "dataframe", "series" ]
Search for a combination in dataframe to change cell value
40,138,350
<p>I want to replace values in a column if the a combination of values in two columns is valid. Lets say I have the following <code>DataFrame</code></p> <pre><code>df = pd.DataFrame([ ['Texas 1', '111', '222', '333'], ['Texas 1', '444', '555', '666'], ['Texas 2', '777','888','999'] ]) ...
2
2016-10-19T17:51:38Z
40,139,238
<p>You have all almost all your code, just create <code>dictionary</code> or <code>list</code> and iterate over it and you are done.</p> <pre><code>import pandas as pd combinations = [['key1', 'key2', 'msg']] combinations.append(['Texas 1', '222', 'triple two']) combinations.append(['Texas 1', '555', 'triple five']) ...
1
2016-10-19T18:43:29Z
[ "python", "pandas" ]
Search for a combination in dataframe to change cell value
40,138,350
<p>I want to replace values in a column if the a combination of values in two columns is valid. Lets say I have the following <code>DataFrame</code></p> <pre><code>df = pd.DataFrame([ ['Texas 1', '111', '222', '333'], ['Texas 1', '444', '555', '666'], ['Texas 2', '777','888','999'] ]) ...
2
2016-10-19T17:51:38Z
40,139,439
<h1>Great Use Case for <code>DataFrame.apply()</code>. Lamda functions all the way!!</h1> <pre><code>df = pd.DataFrame([ ['Texas 1', 111, 222, 333], ['Texas 1', 444, 555, 666], ['Texas 2', 777,888,999] ]) val_dict = {} # assumption # str_like_Success : [column_0 , column_1] val_dict["Succ...
0
2016-10-19T18:56:42Z
[ "python", "pandas" ]
'DataFrame' object is not callable
40,138,380
<p>I'm trying to create a heatmap using Python on Pycharms. I've this code:</p> <pre><code>import numpy as np import pandas as pd import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt data1 = pd.read_csv(FILE") freqMap = {} for line in data1: for item in line: if not item in freqMap: fr...
1
2016-10-19T17:53:07Z
40,139,988
<p>You are reading a csv file but it has no header, the delimiter is a space not a comma, and there are a variable number of columns. So that is three mistakes in your first line.</p> <p>And data1 is a DataFrame, freqMap is a dictionary that is completely unrelated. So it makes no sense to do data1[freqMap].</p> <p>I...
2
2016-10-19T19:28:34Z
[ "python", "pandas", "matplotlib", "dataframe" ]
Database Connect Error: Centos 6 / Apache 2.4 / Postgres 9.4 / Django 1.9 / mod_wsgi 3.5 / python 2.7
40,138,417
<p>I am trying to get my website up and running. Everything seems to work fine, but when I go to a page with a database write - I get this:</p> <pre><code>[Wed Oct 19 09:53:12.319824 2016] [mpm_prefork:notice] [pid 12411] AH00173: SIGHUP received. Attempting to restart [Wed Oct 19 09:53:13.001121 2016] [ssl:warn] [...
0
2016-10-19T17:55:11Z
40,138,772
<p>MySQL and PostgreSQL both do not come along with a user called 'leechprotect'. But a google search points out, that this username <a href="https://confluence2.cpanel.net/display/1152Docs/Leech+Protect" rel="nofollow">is related to cPanel</a> - might be worth reading that to understand whats going on. Afterwards you ...
0
2016-10-19T18:16:10Z
[ "python", "mysql", "django", "apache", "postgresql" ]
Querying MySQL from multiple uWSGI workers returns mismatched rows
40,138,527
<p>I am running a query against a MySQL database from a Flask app being run with uWSGI with multiple workers. I've noticed that sometimes when I query a resource by id, the id of the returned row is different than the one I queried with.</p> <p>I thought that query isolation meant that this was not possible. However, ...
1
2016-10-19T18:01:25Z
40,142,636
<p><strong>For anyone else facing this issue, I have found the following solution.</strong></p> <p>According to <a href="http://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html" rel="nofollow">http://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html</a>.</p> <blockquote> <p>uWSGI tries to (ab)use the Copy ...
0
2016-10-19T22:37:16Z
[ "python", "mysql", "flask", "uwsgi", "pymysql" ]
Why is my Python script not running via command line?
40,138,529
<p>Thanks!</p> <pre><code>def hello(a,b): print "hello and that's your sum:" sum=a+b print sum import sys if __name__ == "__main__": hello(sys.argv[2]) </code></pre> <p>It does not work for me, I appreciate the help!!! Thanks!</p>
-1
2016-10-19T18:01:27Z
40,138,630
<p>Without seeing your error message it's hard to say exactly what the problem is, but a few things jump out:</p> <ul> <li>No indentation after if __name__ == "__main__":</li> <li>you're only passing one argument into the hello function and it requires two.</li> <li>the sys module is not visible in the scope outside t...
4
2016-10-19T18:06:56Z
[ "python" ]