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 trap an exception that occurs in code underlying Python for-loop?
37,890,123
<p>I STILL DO NOT HAVE A SOLUTION.</p> <p>I am writing a mail processing program. I have a big INBOX file downloaded (by Thunderbird) that has my gmail.</p> <p>It runs on some mailboxes, but not the INBOX from gmail. It goes for a long while, but then I get a <code>UnicodeDecodeError</code> exception with a message...
0
2016-06-17T20:43:48Z
37,890,504
<p>A <code>UnicodeDecodeError</code> doesn't mean that your mailbox is broken, but that it contains characters beyond the Ascii range. It sounds like you can afford to skip the broken messages (if you didn't have a problem with the first thirty thousand messages, there might not be more than a handful in the whole file...
2
2016-06-17T21:17:50Z
[ "python", "exception", "for-loop" ]
(osx) ffmpeg combining mp3 and png to mp4 resulting in mp4 with no audio
37,890,159
<p>I'm writing a python script that uses unix commands to do some file conversions/renderings. I'm trying to join some mp3 files with png files to get mp4s that are the picture with the mp3 playing over them. However, I've tried this with lots of different codecs and settings, and the output mp4 video never seems to ha...
1
2016-06-17T20:47:23Z
37,899,820
<p>QuickTime* does not decode MP3 audio in MP4 container. Windows Media Player also has issues, but will only decode some audio sample rates. VLC and mpv work fine. Some solutions:</p> <ul> <li>Use a better player such as VLC or mpv.</li> <li>Output to a different container format such as <code>.mov</code>.</li> <li>R...
1
2016-06-18T17:33:40Z
[ "python", "unix", "audio", "video", "ffmpeg" ]
Reduce execution time on huge list generation
37,890,199
<p>I'm fairly new to Python, and I'm trying to write some huge lists (with random letters inside). Actually it takes me around 75 - 80 seconds on my machine for 2,000,000 lines.</p> <pre><code>import timeit import random, string global_tab = [] global_nb_loop = 2000000 print("Generate %d lines" % global_nb_loop)...
2
2016-06-17T20:50:11Z
37,891,653
<p>I am pretty sure your lock is not necessary and is slowing you down. (edit: actually, I just noticed the lock is used <em>after</em> the majority of the work is done, so isn't really relevant.)</p> <p><code>global_tab += self.tab</code> is (I think) atomic through the Python GIL. (Actually, <a href="http://effbot....
2
2016-06-17T23:22:04Z
[ "python", "multithreading", "python-3.5", "execution-time" ]
Reduce execution time on huge list generation
37,890,199
<p>I'm fairly new to Python, and I'm trying to write some huge lists (with random letters inside). Actually it takes me around 75 - 80 seconds on my machine for 2,000,000 lines.</p> <pre><code>import timeit import random, string global_tab = [] global_nb_loop = 2000000 print("Generate %d lines" % global_nb_loop)...
2
2016-06-17T20:50:11Z
37,892,161
<p>From <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">python threading docs</a>:</p> <blockquote> <p>CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might...
2
2016-06-18T00:35:51Z
[ "python", "multithreading", "python-3.5", "execution-time" ]
Reduce execution time on huge list generation
37,890,199
<p>I'm fairly new to Python, and I'm trying to write some huge lists (with random letters inside). Actually it takes me around 75 - 80 seconds on my machine for 2,000,000 lines.</p> <pre><code>import timeit import random, string global_tab = [] global_nb_loop = 2000000 print("Generate %d lines" % global_nb_loop)...
2
2016-06-17T20:50:11Z
37,904,905
<p>Since you are working with large amounts of data, I recommend a look at numpy. Generally numpy is slower than lists but more memory efficient, and really good for many vectorized operations. You can always go down the multiprocessing route, even with numpy.</p> <p>Here is a version that runs 3x faster than the orig...
1
2016-06-19T07:24:22Z
[ "python", "multithreading", "python-3.5", "execution-time" ]
OpenCV Python - findHomography with RANSAC
37,890,256
<p>I'm trying to run <a href="http://docs.opencv.org/3.0-beta/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#Mat%20findHomography(InputArray%20srcPoints,%20InputArray%20dstPoints,%20int%20method,%20double%20ransacReprojThreshold,%20OutputArray%20mask,%20const%20int%20maxIters%20,%20const%20double%20c...
0
2016-06-17T20:55:51Z
37,890,578
<p>Your error is occurring because you are attempting to specify the <code>method</code> parameter twice; once as a positional argument, and again as a keyword argument. The <code>False</code> argument can be removed to correct your error. If you are trying to use RANSAC to find the homography, the correct call looks l...
1
2016-06-17T21:23:46Z
[ "python", "opencv" ]
TypeError: list() takes at most 1 argument (3 given) for list class inheritance
37,890,267
<p>I searched other posts in stackoverflow and even copied them to try on my machine as answered. However, it keep failing throwing <code>"TypeError"</code></p> <pre><code># this is as one of other post in StackOverflow. class ListClass(list): def __init__(self, *args): super().__init__(self, *args) ...
0
2016-06-17T20:57:00Z
37,890,372
<p>You are giving it to many paramerters when you create the ListClass object, this is what you are doing:</p> <pre><code>s = list(2,3,3) </code></pre> <p>This is what you shuold be doing:</p> <pre><code>s = list([2,3,3]) </code></pre> <p>Try this snippets on you interpreter.</p>
0
2016-06-17T21:06:29Z
[ "python" ]
TypeError: list() takes at most 1 argument (3 given) for list class inheritance
37,890,267
<p>I searched other posts in stackoverflow and even copied them to try on my machine as answered. However, it keep failing throwing <code>"TypeError"</code></p> <pre><code># this is as one of other post in StackOverflow. class ListClass(list): def __init__(self, *args): super().__init__(self, *args) ...
0
2016-06-17T20:57:00Z
37,890,688
<p>Pass the tuple of arguments <code>args</code> to your instance's <code>extend</code>:</p> <pre><code>&gt;&gt;&gt; class ListClass(list): ... def __init__(self, *args): ... super().__init__() ... self.extend(args) ... self.append('a') ... self.name = 'test' ... &gt;&gt;&gt; ListCl...
1
2016-06-17T21:34:52Z
[ "python" ]
Shooting in pygame not working
37,890,274
<p>I am trying to make a code in pygame to shoot bullets but it isn't working as it gives an out of index error. Here is my code. What am I doing wrong? Thanks.</p> <pre><code>while fire ==True: print 'FIRE' for bullet in bullets[:]: nowtime=pygame.time.get_ticks() if (nowtime-bullets[3])&gt;10...
-1
2016-06-17T20:57:47Z
37,890,443
<p>While the specific stack trace would be helpful, your issue probably stems from this line:</p> <pre><code>if (nowtime-bullets[3])&gt;1000: </code></pre> <p>I think you mean to check the fourth parameter of the bullet array (which you have referenced as <code>bt</code> later). However, that would be <code>bullet[3]...
0
2016-06-17T21:13:05Z
[ "python", "pygame" ]
How to replace the '\\' in a directory with '/'?
37,890,280
<p>I wanted to replace the backslashes in the directory with a forward slash. Currently, this program just terminates, so I'm not exactly sure what to do. I would appreciate any input/assistance! </p> <pre><code>def fix(result): '''this will correct the \\ in directory by replacing with /''' result=['C:/Use...
-2
2016-06-17T20:58:16Z
37,890,300
<p>To easily replace a substring in a string <code>txt</code>with another:</p> <pre><code>txt = txt.replace('\\', '/') #Replacing \\ with / </code></pre> <p><br/></p> <blockquote> <p>Remember kids, python has a built in function for <strong>everything</strong></p> </blockquote>
5
2016-06-17T20:59:52Z
[ "python", "python-3.x" ]
.ini file load environment variable
37,890,284
<p>I am using <a href="http://alembic.readthedocs.io/en/latest/" rel="nofollow">Alembic</a> for migrations implementation in a <code>Flask</code> project. There is a <code>alembic.ini</code> file where the database configs must be specified:</p> <p><code>sqlalchemy.url = driver://user:password@host/dbname</code></p> ...
0
2016-06-17T20:58:40Z
37,891,036
<p>I've solved the problem by setting <code>sqlalchemy.url</code> in <code>env.py</code> as @dirn suggested.</p> <p><code>config.set_main_option('sqlalchemy.url', &lt;db_uri&gt;)</code> did the trick, where <code>&lt;db_uri&gt;</code> can be loaded from environment or config file.</p>
0
2016-06-17T22:06:38Z
[ "python", "flask", "ini", "alembic" ]
Python reshape array
37,890,373
<p>I have a very unique error I feel. I am working with an array 'A' of shape</p> <pre><code>&gt;&gt;&gt; A.shape (1L, 1823L, 24L) </code></pre> <p>I am trying to get rid of first dimension as it is empty. So, I do something as:</p> <pre><code>&gt;&gt;&gt; z1 = A[0,:,:] &gt;&gt;&gt; z1.shape (1253L,) &gt;&gt;&gt; z1...
1
2016-06-17T21:06:31Z
37,890,393
<p>You can use <code>np.reshape()</code> for this.</p> <p>Example <a href="http://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.reshape.html" rel="nofollow">from the docs</a>:</p> <pre><code>&gt;&gt;&gt; a = np.arange(6).reshape((3, 2)) &gt;&gt;&gt; a array([[0, 1], [2, 3], [4, 5]]) </code><...
0
2016-06-17T21:08:43Z
[ "python", "numpy" ]
Most efficient way to fill missing elements of dataframe with a function of column and row indices
37,890,389
<p>I have a dataframe with missing values.</p> <pre><code>import pandas as pd import numpy as np np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((0, np.nan), (5, 5))) print df 0 1 2 3 4 0 0.0 NaN 0.0 NaN 0.0 1 0.0 NaN 0.0 NaN NaN 2 NaN NaN 0.0 NaN NaN 3 0.0 NaN 0.0 0.0...
1
2016-06-17T21:08:06Z
37,892,441
<p>Both <code>arraymap</code> in <code>pir1</code> and the double for-loop in <code>pir2</code> call <code>f</code> once for each pair of index and column values. If <code>f</code> can be vectorized -- i.e. defined so as to accept NumPy arrays as input instead of scalars, then for large inputs the calculation can be s...
2
2016-06-18T01:28:02Z
[ "python", "pandas" ]
How to include end date in pandas date_range method?
37,890,391
<p>From <code>pd.date_range('2016-01', '2016-05', freq='M', ).strftime('%Y-%m')</code>, the last month is <code>2016-04</code>, but I was expecting it to be <code>2016-05</code>. It seems to me this function is behaving like the <code>range</code> method, where the end parameter is not included in the returning array....
3
2016-06-17T21:08:38Z
37,890,432
<p>I dont think so. <strong>You need to add the (n+1) boundary</strong></p> <pre><code> pd.date_range('2016-01', '2016-06', freq='M' ).strftime('%Y-%m') </code></pre> <blockquote> <p>The start and end dates are strictly inclusive. So it will not generate any dates outside of those dates if specified. <a href=...
0
2016-06-17T21:11:52Z
[ "python", "string", "datetime", "pandas", "range" ]
How to include end date in pandas date_range method?
37,890,391
<p>From <code>pd.date_range('2016-01', '2016-05', freq='M', ).strftime('%Y-%m')</code>, the last month is <code>2016-04</code>, but I was expecting it to be <code>2016-05</code>. It seems to me this function is behaving like the <code>range</code> method, where the end parameter is not included in the returning array....
3
2016-06-17T21:08:38Z
37,890,457
<p>Include the day when specifying the dates in <code>date_range</code> call</p> <pre><code>pd.date_range('2016-01-31', '2016-05-31', freq='M', ).strftime('%Y-%m') array(['2016-01', '2016-02', '2016-03', '2016-04', '2016-05'], dtype='|S7') </code></pre>
0
2016-06-17T21:14:03Z
[ "python", "string", "datetime", "pandas", "range" ]
How to include end date in pandas date_range method?
37,890,391
<p>From <code>pd.date_range('2016-01', '2016-05', freq='M', ).strftime('%Y-%m')</code>, the last month is <code>2016-04</code>, but I was expecting it to be <code>2016-05</code>. It seems to me this function is behaving like the <code>range</code> method, where the end parameter is not included in the returning array....
3
2016-06-17T21:08:38Z
37,890,592
<p>A way to do it without messing with figuring out month ends yourself.</p> <pre><code>pd.date_range(*(pd.to_datetime(['2016-01', '2016-05']) + pd.offsets.MonthEnd()), freq='M') DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30', '2016-05-31'], dtype='datetime64[ns]', freq='M'...
1
2016-06-17T21:24:57Z
[ "python", "string", "datetime", "pandas", "range" ]
How to include end date in pandas date_range method?
37,890,391
<p>From <code>pd.date_range('2016-01', '2016-05', freq='M', ).strftime('%Y-%m')</code>, the last month is <code>2016-04</code>, but I was expecting it to be <code>2016-05</code>. It seems to me this function is behaving like the <code>range</code> method, where the end parameter is not included in the returning array....
3
2016-06-17T21:08:38Z
37,890,629
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.union.html#pandas.DatetimeIndex.union" rel="nofollow"><code>.union</code></a> to add the next logical value after initializing the <code>date_range</code>. It should work as written for any frequency:</p> <pre><code>d =...
1
2016-06-17T21:29:09Z
[ "python", "string", "datetime", "pandas", "range" ]
Tensorflow GradientDescentOptimizer - how does it connect to tf.Variables?
37,890,394
<p><a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#GradientDescentOptimizer" rel="nofollow">Documentation</a></p> <p>I'm just curious how you tell it to minimize which variables. For example in this linear regression code, TF does fine optimizing weights/bias without being told the names o...
0
2016-06-17T21:08:47Z
37,890,463
<p>It takes them from <code>tf.trainable_variables()</code> which includes all variables created with <code>trainable=True</code> flag (the default)</p>
1
2016-06-17T21:14:39Z
[ "python", "tensorflow" ]
Increment matplotlib color cycle
37,890,412
<p>Is there a simple way to increment the matplotlib color cycle without digging into axes internals?</p> <p>When plotting interactively a common pattern I use is:</p> <pre><code>import matplotlib.pyplot as plt plt.figure() plt.plot(x,y1) plt.twinx() plt.plot(x,y2) </code></pre> <p>The <code>plt.twinx()</code> in n...
1
2016-06-17T21:10:38Z
37,891,126
<p>You could call </p> <pre><code>ax2._get_lines.get_next_color() </code></pre> <p>to advance the color cycler on color. Unfortunately, this accesses the private attribute <code>._get_lines</code>, so this is not part of the official public API and not guaranteed to work in future versions of matplotlib.</p> <p>A sa...
2
2016-06-17T22:15:49Z
[ "python", "matplotlib", "jupyter-notebook" ]
List index out of range: Hello Python
37,890,515
<p>Hello i'm new to Python and i'm having a little trouble. I'm reading Hello Python and i'm typing a code down it told me to type, but when i run the code, it gives me an error.</p> <p>Error: caves[next_cave].append(i) List index out of range</p> <p>This is the code i'm typing out.</p> <p>Code:</p> <pre><code>from...
-3
2016-06-17T21:18:46Z
37,890,567
<p>That error means that at some point, the value in <code>next_cave</code> exceeds the length of the <code>caves</code> list.</p> <p>You'd get that same error by doing this:</p> <pre><code>caves = [[0,1,2], [4,5,6]] caves[2].append([7,8,9]) </code></pre>
-1
2016-06-17T21:23:14Z
[ "python" ]
List index out of range: Hello Python
37,890,515
<p>Hello i'm new to Python and i'm having a little trouble. I'm reading Hello Python and i'm typing a code down it told me to type, but when i run the code, it gives me an error.</p> <p>Error: caves[next_cave].append(i) List index out of range</p> <p>This is the code i'm typing out.</p> <p>Code:</p> <pre><code>from...
-3
2016-06-17T21:18:46Z
37,890,601
<p><code>choice(unvisited_caves)</code> in going to return a number from <code>unvisited_caves = range(0,20)</code>, so that would be a random number from 0..19. </p> <p><code>caves[next_cave].append(i)</code> will error 90% of the time (18/20 times) because all you have done is <code>caves = []</code> and <code>cave...
3
2016-06-17T21:26:12Z
[ "python" ]
List index out of range: Hello Python
37,890,515
<p>Hello i'm new to Python and i'm having a little trouble. I'm reading Hello Python and i'm typing a code down it told me to type, but when i run the code, it gives me an error.</p> <p>Error: caves[next_cave].append(i) List index out of range</p> <p>This is the code i'm typing out.</p> <p>Code:</p> <pre><code>from...
-3
2016-06-17T21:18:46Z
37,890,646
<p>I think your problem is just with indentation. I believe that your intent was to use the for loop to give your list of caves 20 empty arrays before you begin your simulation. As you had it, your loop would add one array and then start the simulation right away. Your caves list is not ready for this, and so it errors...
1
2016-06-17T21:30:08Z
[ "python" ]
Python plotting percentile contour lines of a probability distribution
37,890,550
<p>Given a probability distribution with unknown functional form (example below), I like to plot "percentile-based" contour lines, i.e.,those that correspond to regions with an integral of 10%, 20%, ..., 90% etc.</p> <pre><code>## example of an "arbitrary" probability distribution ## from matplotlib.mlab import bivari...
3
2016-06-17T21:21:44Z
37,894,227
<p>You can do something like this:</p> <pre><code>from matplotlib.mlab import bivariate_normal import matplotlib.pyplot as plt import matplotlib.mlab as mlab import numpy as np X, Y = np.mgrid[-3:3:100j, -3:3:100j] sigma = 0.5 z = bivariate_normal(X,Y,.5, .5, 0., 0.) z1 = bivariate_normal(0, 1 * sigma, sigma, sigma...
-1
2016-06-18T07:00:13Z
[ "python", "matplotlib", "probability", "contour", "kernel-density" ]
Python plotting percentile contour lines of a probability distribution
37,890,550
<p>Given a probability distribution with unknown functional form (example below), I like to plot "percentile-based" contour lines, i.e.,those that correspond to regions with an integral of 10%, 20%, ..., 90% etc.</p> <pre><code>## example of an "arbitrary" probability distribution ## from matplotlib.mlab import bivari...
3
2016-06-17T21:21:44Z
37,932,566
<p>Look at the integral of p(x) inside the contour p(x) &ge; t and solve for the desired value of t:</p> <pre><code>import matplotlib from matplotlib.mlab import bivariate_normal import matplotlib.pyplot as plt import numpy as np X, Y = np.mgrid[-3:3:100j, -3:3:100j] z1 = bivariate_normal(X, Y, .5, .5, 0., 0.) z2 = b...
3
2016-06-20T22:04:42Z
[ "python", "matplotlib", "probability", "contour", "kernel-density" ]
Paired Delimeter Matching
37,890,551
<p>I would like to write a class that will return true if and only if the expression entered contains only correctly matching delimiters such as " (), &lt;>, [], {} " What I have written thus far will do exactly that.</p> <pre><code>delim_openers = '{([&lt;' delim_closers = '})]&gt;' def check_delimiters(expr): v...
0
2016-06-17T21:21:46Z
37,890,703
<p>No need for <code>any</code>, a simple contains-check will suffice. Then you have to check whether the <code>closer</code> matches the <code>opener</code>, otherwise you are just checking whether closers and openers are equal in numbers and that the closers never take the lead count-wise:</p> <pre><code>class Stack...
0
2016-06-17T21:35:59Z
[ "python", "stack", "delimiter" ]
SciPy compatibility issue with MKL libraries
37,890,627
<p>I recently installed SciPy for Python3.4 on Ubuntu 12.04 with</p> <pre><code>pip3 install scipy </code></pre> <p>When I import scipy in Python3.4 as:</p> <pre><code>import scipy </code></pre> <p>it imports, but when I import the function interpolate as</p> <pre><code>import scipy.interpolate </code></pre> <p>I...
3
2016-06-17T21:28:56Z
37,892,566
<p>Numpy and Scipy are popular packages. You probably can find them in Ubuntu repository. So it's better to install them with apt-get but not pip. </p> <p>If you want MKL support, I would suggest anaconda - a full Python distribution with MKL and other acceleration libraries integrated such as CUDA. This will make you...
1
2016-06-18T01:57:53Z
[ "python", "scipy", "python-3.4", "intel-mkl" ]
HTTP 403 'Rate Limit Exceeded' ERROR in Google Blogger v3 API
37,890,637
<p>I have a python script which uses Google Blogger API with oauth 2.0. Now the problem is that there is a function <code>blogger.posts.insert</code>. It is returning an error "HTTP 403 'Rate Limited Exceeded'". </p> <p>Can anybody tell me how to fix this? I also tried to do the same in python and the error is still ...
0
2016-06-17T21:29:31Z
37,899,851
<p>I was right, there is a bug with Google Blogger API when using the <code>insert</code> to add posts so <strong>this is how I fixed it</strong>:</p> <ol> <li>I started <code>Apache</code> using <code>XAMP</code> and apache was running on port <code>80</code> ( can be different for you so check it in XAMP control pan...
0
2016-06-18T17:38:23Z
[ "python", "http", "blogger" ]
How do I specify na_values in pandas using read_sql?
37,890,649
<p>I'm trying to create a pandas dataframe from a sql table. I read in the data using <code>data=pd.read_sql(query,con=con)</code>, and this works just fine. However, I wish to set which type of elements in the data frame is NaN. When reading a csv, this can be set using <code>pd.read_csv('file.csv',na_values=['',[]'])...
0
2016-06-17T21:30:14Z
37,890,811
<p>There is no such parameter because pandas/numpy <code>NaN</code> corresponds <code>NULL</code> (in the database), so there is one to one relation.</p> <p>But if you want to replace other values with NaNs you can do it this way:</p> <pre><code>df = df.replace(['', 'null'], [np.nan, np.nan]) </code></pre>
1
2016-06-17T21:46:04Z
[ "python", "pandas" ]
django - persisting an email to database to be able to send it later?
37,890,690
<p>In my django project I want to store an email in the database to be able to retrieve it later and send it. I'm implementing a throttling mechanism for sending emails to many users.</p> <p>I thought it would be as easy as storing 'to, from, subject, body' but then I realized there are attachments, multipart emails, ...
0
2016-06-17T21:34:53Z
37,891,070
<p>I'm going to make a guess based on your <code>can't pickle lock objects</code> message that you may be trying to <code>pickle</code> your objects with the default SMTP <code>connection</code> included.</p> <p>Try it without it - grepping through the source it is the <code>smtp</code> module that has a <code>self._l...
1
2016-06-17T22:10:05Z
[ "python", "django", "email", "django-email" ]
Python - failing to read correctly the first line of a text file to a list
37,890,696
<p>I'm having a problem understanding why my python program does what it does when reading (first) lines from files and adding the lines into a list. For some reason the first line needs to be empty or it'll not read the first line correctly. If the first line is empty, it's not empty (at least not according to python)...
1
2016-06-17T21:35:21Z
37,890,826
<p>A classic approach to reading text files in Python is:</p> <pre><code>with open(fname, 'r') as f: lines = f.readlines() </code></pre> <p>After which you can process the lines like this:</p> <pre><code>for line in lines: # do something with line... </code></pre> <p>As other comments have hinted, you may w...
0
2016-06-17T21:46:43Z
[ "python", "file", "line" ]
Python - failing to read correctly the first line of a text file to a list
37,890,696
<p>I'm having a problem understanding why my python program does what it does when reading (first) lines from files and adding the lines into a list. For some reason the first line needs to be empty or it'll not read the first line correctly. If the first line is empty, it's not empty (at least not according to python)...
1
2016-06-17T21:35:21Z
37,894,771
<p>Looks like you've already done the legwork on this, but according to <a href="http://stackoverflow.com/questions/8432584/how-to-make-notepad-to-save-text-in-utf-8-without-bom">How to make Notepad to save text in UTF-8 without BOM?</a>, the best answer is not to use Notepad (but Notepad++ is ok). :)</p> <p>Alternati...
1
2016-06-18T08:08:34Z
[ "python", "file", "line" ]
Big Integer in JSON getting corrupted by Angular but not by CURL?
37,890,762
<p>I have created a Django REST API using <a href="http://www.django-rest-framework.org/" rel="nofollow">Django Rest Framework</a>.</p> <p>I use 3 different clients to hit this app:</p> <ul> <li>Curl (for debugging purposes)</li> <li>Swagger Interface (for debugging purposes)</li> <li>My Angular application</li> </ul...
6
2016-06-17T21:41:02Z
37,919,800
<p>You are trying to store a number which is greater than the safe maximum javascript integer <code>value(+/- 9007199254740991)</code>.</p> <p>Your <code>make_id</code> generator should return values with respect to javascript limitations.</p> <p>For more information read: <a href="http://blog.vjeux.com/2010/javascri...
5
2016-06-20T10:10:14Z
[ "python", "angularjs", "json", "django", "rest" ]
Big Integer in JSON getting corrupted by Angular but not by CURL?
37,890,762
<p>I have created a Django REST API using <a href="http://www.django-rest-framework.org/" rel="nofollow">Django Rest Framework</a>.</p> <p>I use 3 different clients to hit this app:</p> <ul> <li>Curl (for debugging purposes)</li> <li>Swagger Interface (for debugging purposes)</li> <li>My Angular application</li> </ul...
6
2016-06-17T21:41:02Z
37,919,893
<h2>TLDR</h2> <p>To cut a long story short. Have your view return the response as String.</p> <p>{"id": "10150133855458395", "name": "my-name"}</p> <h2>The Long Story</h2> <p>Let's narrow this down. In fact you can and should test this without the involvement of django at all. Please save the json you get from <cod...
3
2016-06-20T10:15:18Z
[ "python", "angularjs", "json", "django", "rest" ]
Is the object data type static in Python?
37,890,845
<p>I have a data frame which contains two columns: one with strings and the other with integers. As expected, the data type of the integer column is <code>int64</code>. For the string column, however, it is <code>object</code>.</p> <p>Now I wanted to convert the string column to an integer column by assigning each str...
1
2016-06-17T21:49:06Z
37,890,936
<p>i would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map()</a> function in this case:</p> <pre><code>In [84]: toList = pd.Series(range(len(df['catCol'].unique())), index=df['catCol'].unique()) In [85]: toList Out[85]: NM 0 VT 1 VA 2 NY 3 dtyp...
0
2016-06-17T21:56:10Z
[ "python", "object", "pandas", "data-type-conversion" ]
Pandas Series: Log Normalize
37,890,849
<p>I have a Pandas Series, that needs to be log-transformed to be normal distributed. But I can´t log transform yet, because there are values =0 and values below 1 (0-4000). Therefore I want to normalize the Series first. I heard of StandardScaler(scikit-learn), Z-score standardization and Min-Max scaling(normalizatio...
0
2016-06-17T21:49:23Z
37,892,018
<p>To transform to logarithms, you need positive values, so translate your range of values (-1,1] to normalized (0,1] as follows</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.uniform(-1,1,(10,1))) df['norm'] = (1+df[0])/2 # (-1,1] -&gt; (0,1] df['lognorm'] = np.log(df['norm']) </co...
0
2016-06-18T00:10:29Z
[ "python", "pandas", "normalization" ]
Pandas Series: Log Normalize
37,890,849
<p>I have a Pandas Series, that needs to be log-transformed to be normal distributed. But I can´t log transform yet, because there are values =0 and values below 1 (0-4000). Therefore I want to normalize the Series first. I heard of StandardScaler(scikit-learn), Z-score standardization and Min-Max scaling(normalizatio...
0
2016-06-17T21:49:23Z
37,905,017
<p>If your data is in the range (-1;+1) (assuming you lost the minus in your question) then <strong>log transform is probably not what you need</strong>. At least from a theoretical point of view, it's obviously the <em>wrong</em> thing to do.</p> <p>Maybe your data has already been preprocessed (inadequately)? Can yo...
0
2016-06-19T07:41:11Z
[ "python", "pandas", "normalization" ]
How to set env variable in Jupyter notebook
37,890,898
<p>I've a problem that Jupyter can't see env variable in bashrc file, is there a way to load these variables in jupyter or add custome variable to it?</p>
0
2016-06-17T21:53:15Z
37,890,954
<p>You can setup environment variables in your code as follows:</p> <pre><code>import sys,os,os.path sys.path.append(os.path.expanduser('~/code/eol_hsrl_python')) os.environ['HSRL_INSTRUMENT']='gvhsrl' os.environ['HSRL_CONFIG']=os.path.expanduser('~/hsrl_config') </code></pre> <p>This if of course a temporary fix, to...
0
2016-06-17T21:58:23Z
[ "python", "bash", "environment-variables", "jupyter-notebook" ]
Attribute error in urls.py
37,890,908
<p>I am doing the django tutorial so I am literally cutting and pasting code. I keep getting this error on step 1</p> <pre><code> from django.conf.urls import url from django.conf.urls import include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre> <p>I am gettin...
0
2016-06-17T21:53:49Z
38,024,070
<p>The answer was indeed there had to be something wrong with my views. Deleting the django project and rebuilding the entire tutorial from scratch remedied the issue. </p>
1
2016-06-25T01:20:30Z
[ "python", "django" ]
Django - How to count the number of deletions that occur for a model?
37,890,920
<p>I have an application that has both posting and wishlist models. Users create posting and wishlist objects and hypothetically when they delete these objects that means they successfully bought or sold whatever the item was.</p> <p>I want to continuously count the number of objects that are deleted for each model an...
0
2016-06-17T21:54:57Z
37,891,017
<p>One solution is to never hard delete any of the objects, but keep a boolean called "is_deleted" in your model. This way, you can count the number of deleted objects, and you can also count specific elements of the deleted objects. You might want to override the <code>delete()</code> fuction, see <a href="http://stac...
1
2016-06-17T22:05:06Z
[ "python", "django", "django-models" ]
Django - How to count the number of deletions that occur for a model?
37,890,920
<p>I have an application that has both posting and wishlist models. Users create posting and wishlist objects and hypothetically when they delete these objects that means they successfully bought or sold whatever the item was.</p> <p>I want to continuously count the number of objects that are deleted for each model an...
0
2016-06-17T21:54:57Z
37,891,044
<p>You have many ways to do this:</p> <ol> <li><p>Implement an auditing mechanism; using any number of <a href="https://www.djangopackages.com/grids/g/model-audit/" rel="nofollow">audit applications available</a>.</p></li> <li><p>As of django 1.9, the <code>delete()</code> method <a href="https://docs.djangoproject.co...
2
2016-06-17T22:07:17Z
[ "python", "django", "django-models" ]
Flask - User input and Buttons with back-end actions, returning text to user
37,890,972
<p>I'm running a small Flask test and attempting to do the following:</p> <p>I have two forms.</p> <p>The first - receives users input, then has a submit button. When the submit button is pressed I would like to 1.) execute a back-end Python program using the two values from 'doritos' and 'oreos' then 2.) return some...
-1
2016-06-17T22:00:04Z
37,892,070
<p>Flask has the <a href="http://flask.pocoo.org/docs/0.11/templating/" rel="nofollow">Jinja2</a> built in (you're already using it in the form of <code>render_template</code>), so one simple solution to this problem could be to create a template with your forms, and pass a "success" or "fail" message to the template w...
0
2016-06-18T00:20:53Z
[ "python", "flask" ]
Difference between a view and assignment
37,891,008
<p>I can understand the difference between an assignment, shallow and deep copy. But I am still unclear what is the difference between a view(<code>c=a</code>) and an assignment(<code>c=a.view()</code>). Both reflect changes and seem the same. Please give <strong>examples</strong> if possible.</p> <p>I am referring to...
-1
2016-06-17T22:04:07Z
37,891,450
<p>A array object in NumPy is a ndarray struct with a <code>data</code> pointer that point to the raw values in the array.</p> <ul> <li><code>b = a</code>: Just give the array another name.</li> <li><code>c = a.view()</code>: Create a view of array <code>a</code> means create a new ndarray struct that point to the sam...
4
2016-06-17T22:54:02Z
[ "python", "numpy", "dictionary", "scipy" ]
Difference between a view and assignment
37,891,008
<p>I can understand the difference between an assignment, shallow and deep copy. But I am still unclear what is the difference between a view(<code>c=a</code>) and an assignment(<code>c=a.view()</code>). Both reflect changes and seem the same. Please give <strong>examples</strong> if possible.</p> <p>I am referring to...
-1
2016-06-17T22:04:07Z
37,891,981
<p>Dictionary <code>dictview</code> has nothing to do with <code>numpy</code> array views. It's just a cover term for the object that <code>dict.keys()</code>, <code>dict.values()</code> and <code>dict.items()</code> create in Python3. They are are more like generators, that require a <code>list(...)</code> wrapper....
2
2016-06-18T00:04:36Z
[ "python", "numpy", "dictionary", "scipy" ]
Qt-PyQt5 is it possible to put interval between every letter when set a text to QLineEdit.setText()
37,891,023
<p>My goal is, when I set a string <code>QLineEdit.setText(string)</code>, I want to see that string's letters appear letter by letter, like there is an interval between every letter.</p> <p>I tried to use <code>pyautogui.typewrite(string,interval = 0.25)</code> but it didn't work. Also I tried a for loop on the strin...
0
2016-06-17T22:05:30Z
37,891,904
<p>Try:</p> <pre><code>import time tt = "Test" for idx in range(len(tt)+1): text = tt[:idx] self.line_edit.setText(text) QApplication.processEvents() time.sleep(2) </code></pre> <p>change 2 to however many seconds you want the delay.</p> <p>Edit* Solution updated with ekhumoro's edit</p>
-2
2016-06-17T23:53:41Z
[ "python", "qt", "setinterval", "pyqt5" ]
Qt-PyQt5 is it possible to put interval between every letter when set a text to QLineEdit.setText()
37,891,023
<p>My goal is, when I set a string <code>QLineEdit.setText(string)</code>, I want to see that string's letters appear letter by letter, like there is an interval between every letter.</p> <p>I tried to use <code>pyautogui.typewrite(string,interval = 0.25)</code> but it didn't work. Also I tried a for loop on the strin...
0
2016-06-17T22:05:30Z
37,892,590
<p>In C++ pseudocode and comments (my Python is too rusty to be useful):</p> <pre><code>class DelayedLineEdit : public QLineEdit { ... public Q_SLOTS: void setTextDelayed(const QString &amp;txt); protected Q_SLOTS: void updateText(); private: QTimer textTimer; QString finalText; int currentText...
0
2016-06-18T02:03:51Z
[ "python", "qt", "setinterval", "pyqt5" ]
Qt-PyQt5 is it possible to put interval between every letter when set a text to QLineEdit.setText()
37,891,023
<p>My goal is, when I set a string <code>QLineEdit.setText(string)</code>, I want to see that string's letters appear letter by letter, like there is an interval between every letter.</p> <p>I tried to use <code>pyautogui.typewrite(string,interval = 0.25)</code> but it didn't work. Also I tried a for loop on the strin...
0
2016-06-17T22:05:30Z
37,897,511
<p>I solved this problem with a timer, check it out. Don't mind the modules that I imported, too lazy to delete useless ones.</p> <pre><code>from PyQt5.QtWidgets import (QMessageBox,QApplication, QWidget, QToolTip, QPushButton, QDesktopWidget, QMainWindow, QAction, qApp, QToolBar, QVBoxLay...
0
2016-06-18T13:28:14Z
[ "python", "qt", "setinterval", "pyqt5" ]
Getting scores too high when using SelectPercentile (from sklearn) and SVM as classifier
37,891,108
<p>In Python, I applied SelectPercentile (from sklearn) in order to use only the most relevant features and trained a SVM classifier. I want to mention that I have only one corpus, so I have to perform <code>cross_validation</code> on this corpus.<br> After selecting features with <code>SelectPercentile</code>, when I ...
1
2016-06-17T22:13:33Z
37,901,514
<p>I think you should not perform feature selection (<code>SelectPercentile</code>) using all the data (<code>X_all</code>). By doing that the data you held out for testing in cross-validation 'leaked' into your model. Therefore, your feature selection kind of seen the data in the test set and tells your classifier a s...
0
2016-06-18T20:51:49Z
[ "python", "scikit-learn", "svm", "cross-validation", "tf-idf" ]
Is there some better way just to keep the duplicated rows in Pandas?
37,891,125
<p>I am just curious if pandas has a easier way just to keep the duplicated rows ? </p> <p>Pls dont understand me wrong. I have such a problem, because I unintented get the Pandas Dataframe wrong and have to work with the duplicated rows manuelly. </p> <p>Thank you all!</p>
-2
2016-06-17T22:15:45Z
37,892,679
<p>Pandas has a .duplicated() method for the DataFrame class that allows you to find duplicated columns.</p> <pre><code>&gt;&gt;&gt; df = DataFrame([[1,2,3],[3,4,6],[1,2,3],[1,2,3]],columns=['T1','T2','T3']) &gt;&gt;&gt; df T1 T2 T3 0 1 2 3 1 3 4 6 2 1 2 3 3 1 2 2 &gt;&gt;&gt; df[df.dup...
1
2016-06-18T02:26:08Z
[ "python", "pandas" ]
Using fuzzywuzzy to create a column of matched results in the data frame
37,891,131
<p>I'm running into a challenge with using the FuzzyWuzzy library to store all my results in a data frame column (I'm guessing it might require a loop?) I've been scratching my head over this all day, now I want to see if any of you can help me with the solution! Would be super helpful!</p> <hr> <p>As an example of w...
1
2016-06-17T22:16:07Z
37,891,679
<p>It's not a good idea to store lists in DataFrame, I suggest store every match as a row in DataFrame. Here is the code:</p> <pre><code>from fuzzywuzzy import fuzz from fuzzywuzzy import process import pandas as pd import io master = pd.read_csv(io.StringIO("""ID,ITEM 1,Pepperoni Pizza 2,Cheese Pizza 3,Chicken Sala...
1
2016-06-17T23:25:06Z
[ "python", "pandas", "fuzzywuzzy" ]
klein script CSS isn't working
37,891,145
<p>I have a very simple klein script that is just a reverse-proxy:</p> <pre><code>from klein import run, route, Klein from twisted.web.proxy import ReverseProxyResource @route('/') def home(request, branch=True): return ReverseProxyResource('www.example.com', 80, ''.encode('utf-8')) run("MY_IP", 80) </code></pre...
1
2016-06-17T22:17:26Z
37,913,257
<p>This first block of code based on yours was my first pass, but it doesn't work. </p> <p>It appeared to work for things like <code>GET /a</code>, but that's because <code>/&lt;path&gt;</code> doesn't include additional <code>/</code>'s. So anything that is deeper than one level won't get proxied.</p> <p>Looking i...
0
2016-06-20T00:32:47Z
[ "python", "python-3.x", "twisted", "klein-mvc" ]
klein script CSS isn't working
37,891,145
<p>I have a very simple klein script that is just a reverse-proxy:</p> <pre><code>from klein import run, route, Klein from twisted.web.proxy import ReverseProxyResource @route('/') def home(request, branch=True): return ReverseProxyResource('www.example.com', 80, ''.encode('utf-8')) run("MY_IP", 80) </code></pre...
1
2016-06-17T22:17:26Z
37,950,719
<p>this will work</p> <pre><code>from klein import run, route, Klein from twisted.web.proxy import ReverseProxyResource @route('/',branch=True) def home(request): return ReverseProxyResource('example.com', 80, ''.encode('utf-8')) run("MY_IP", 80) </code></pre> <p>basically branch is argument to @route annotatio...
0
2016-06-21T17:17:43Z
[ "python", "python-3.x", "twisted", "klein-mvc" ]
Openpyxl auto-height row
37,891,149
<p>I'm trying to set wrap text. But when i using wrap text row doesn't change height automatically. How can I set auto-height row?</p>
-1
2016-06-17T22:17:51Z
37,894,677
<p>You need to look at the <code>RowDimension</code> object for the relevant row, specifically the height attribute:</p> <p>rd = ws.row_dimensions[3] rd.height = 25 # value in points, there is no "auto"</p>
0
2016-06-18T07:56:08Z
[ "python", "openpyxl" ]
Openpyxl auto-height row
37,891,149
<p>I'm trying to set wrap text. But when i using wrap text row doesn't change height automatically. How can I set auto-height row?</p>
-1
2016-06-17T22:17:51Z
38,021,089
<p>If your data stored in DataFrame, I would recommend you to use StyleFrame. It automatically auto-adjust columns width and rows height and also have some nice features.</p> <p><a href="https://github.com/DeepSpace2/StyleFrame" rel="nofollow">styleframe</a></p>
0
2016-06-24T19:50:00Z
[ "python", "openpyxl" ]
How to find the position of repeated elements in a list, then sum those elements?
37,891,172
<p>I want to find the position of the repeated elements in the column "1" and the column "2" in a specified matrix "x" (the matrix "x" has a nx3 size ("n" is the maximum number between the column "1" and the column "2", in the next example is max(3,4)=4)), for then in the principal diagonal (number 1 to "n") of a new m...
0
2016-06-17T22:21:25Z
37,907,469
<p>Your problem is clarified if you introduce graph-theoretic terminology. Your <code>x</code> could be thought of as describing a weighted graph. A row like <code>[1,3,2]</code> can be interpreted as describing the existence of an edge of weight 2 connecting node 1 and node 3. The matrix <code>z</code> contains the fo...
0
2016-06-19T12:56:12Z
[ "python", "list" ]
Convert python 2 code to 3 in PyCharm
37,891,188
<p>I have a large ML project in python 2 code and I just started using PyCharm as an IDE. I'm currently using WinPython 3.4 and I'd preferably like to do everything in python 3 instead of continue using legacy 2. When I cloned the project from git a popup in pycharm came up that was something along the lines of convert...
0
2016-06-17T22:22:43Z
37,891,297
<p>There's a <a href="https://docs.python.org/2/library/2to3.html" rel="nofollow">script</a> included with Python, usually at <code>[Python Root]/Tools/Scripts/2to3.py</code>. You can run that script on a python file (or directory of python files) and it will handle a lot of the conversions, at least for changes in th...
0
2016-06-17T22:33:49Z
[ "python", "git", "python-2.7", "python-3.x", "pycharm" ]
Convert python 2 code to 3 in PyCharm
37,891,188
<p>I have a large ML project in python 2 code and I just started using PyCharm as an IDE. I'm currently using WinPython 3.4 and I'd preferably like to do everything in python 3 instead of continue using legacy 2. When I cloned the project from git a popup in pycharm came up that was something along the lines of convert...
0
2016-06-17T22:22:43Z
37,891,359
<p>Before anything I would save a backup copy of your Python 2 file first.</p> <p>You can then try to convert the code using the "2to3" Automated Python 2 to 3 code translation tool which is built into Python via the Standard Library. Details on usage can be found here: <a href="https://docs.python.org/2/library/2to3....
0
2016-06-17T22:41:42Z
[ "python", "git", "python-2.7", "python-3.x", "pycharm" ]
Check when page has switched to another page using Selenium in Python
37,891,222
<p>I'm currently using Selenium in Python and I'm running into the issue of tracking when a page has switched to another page. So say I have the following code to open up a page and then login: </p> <pre><code>self.driver.get(targeturl) login = self.driver.find_element_by_name("login") login.send_keys("user1") passwo...
1
2016-06-17T22:26:54Z
37,891,361
<pre><code> while(self.driver.getCurrentUrl() != nextPageUrl) </code></pre>
1
2016-06-17T22:41:44Z
[ "python", "selenium", "selenium-webdriver" ]
Check when page has switched to another page using Selenium in Python
37,891,222
<p>I'm currently using Selenium in Python and I'm running into the issue of tracking when a page has switched to another page. So say I have the following code to open up a page and then login: </p> <pre><code>self.driver.get(targeturl) login = self.driver.find_element_by_name("login") login.send_keys("user1") passwo...
1
2016-06-17T22:26:54Z
37,891,972
<p>Each page will have different attributes, for example, you can try looking up a page's <code>&lt;title&gt;</code> tag. If that changes, it means you have navigated to a different page. </p> <p>For example, this page's title is <a href="http://i.stack.imgur.com/CAgzT.png" rel="nofollow"><img src="http://i.stack.img...
1
2016-06-18T00:02:11Z
[ "python", "selenium", "selenium-webdriver" ]
Check when page has switched to another page using Selenium in Python
37,891,222
<p>I'm currently using Selenium in Python and I'm running into the issue of tracking when a page has switched to another page. So say I have the following code to open up a page and then login: </p> <pre><code>self.driver.get(targeturl) login = self.driver.find_element_by_name("login") login.send_keys("user1") passwo...
1
2016-06-17T22:26:54Z
37,892,376
<p>Use an explicit wait with an expected condition to tell when one of your login elements has gone stale:</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC self.driver.get(targeturl) login = self.driver.find_element_by_name("login"...
3
2016-06-18T01:16:10Z
[ "python", "selenium", "selenium-webdriver" ]
Check when page has switched to another page using Selenium in Python
37,891,222
<p>I'm currently using Selenium in Python and I'm running into the issue of tracking when a page has switched to another page. So say I have the following code to open up a page and then login: </p> <pre><code>self.driver.get(targeturl) login = self.driver.find_element_by_name("login") login.send_keys("user1") passwo...
1
2016-06-17T22:26:54Z
37,926,827
<p>The best solution I found was a combination of suggestions. The solution is to check for the presence of a new <code>&lt;body&gt;</code> tag based on Bryan Oakley's comment and check for elements, like in Yu's responses (I used <code>&lt;body&gt;</code> instead of <code>&lt;html&gt;</code> because <code>&lt;html&gt;...
1
2016-06-20T15:54:50Z
[ "python", "selenium", "selenium-webdriver" ]
How to initialize a genetic algorithm (GA) with a specific population in Python
37,891,256
<p>The following equations show a randomly initial population for a genetic algorithm by Python.<br> <code>toolbox.register("attr_bool", random.randint, 0, 1)</code></p> <p><code>toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 100)</code></p> <p><code> toolbox.register("po...
0
2016-06-17T22:30:22Z
37,912,766
<p>The best answer found in "<a href="https://groups.google.com/forum/#!topic/deap-users/B_KaNroEJjE" rel="nofollow">https://groups.google.com/forum/#!topic/deap-users/B_KaNroEJjE</a>". It is from Google group </p>
0
2016-06-19T23:10:43Z
[ "python", "random", "theano", "genetic-algorithm", "genetic-programming" ]
How to plot a function on the secondary y-axis of a histogram in python?
37,891,257
<p>Let's use the famous Titanic dataset, found here:</p> <p><a href="http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.xls" rel="nofollow">http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.xls</a></p> <p>And read it in as a dataframe: <code>df</code></p> <p>The features that I'm interes...
0
2016-06-17T22:30:32Z
37,891,640
<p>You have to set up second y-axis by <code>twinx()</code>:</p> <pre><code>sns.set_style("white") df_age = df[df.age &gt;= 0] age = df_age.age fig, ax1 = plt.subplots()#.figure(figsize=(12,6)) n, bins, patches = ax1.hist(age.values, facecolor='gray', bins=20, alpha=.8) plt.axvline(age.median(), color='gray', linest...
0
2016-06-17T23:20:37Z
[ "python", "matplotlib", "histogram" ]
Write data from a df to an excel workbook that already has other worksheets
37,891,371
<p>I want to write data to an Excel WorkBook from a dataframe. The Workbook has other worksheet with existing data. I want to write the data from the dataframe to a new Worksheet</p> <p>When I use </p> <p><code>df.to_excel('name.xlsx', 'Sheet3')</code> </p> <p>data from other lists(sheets) are deleted. How can I wri...
0
2016-06-17T22:43:12Z
37,896,001
<p>You can use the below <code>add_xlsx_sheet</code> function that includes a few settings available for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow"><code>to_excel</code></a>, and checks (and removes) if the <code>sheet</code> with the desire names alrea...
1
2016-06-18T10:35:32Z
[ "python", "excel", "pandas" ]
Dropping rows in pandas with a certain condition
37,891,387
<p>I have a list of ID's and a dataframe, where one of the columns is ID. I want to drop all rows in the dataframe where the ID is not one of the ID's in the list of ID's. This is the code I use:</p> <pre><code>df = df.drop(df[df.ID not in list_IDs].index) </code></pre> <p>but I get this error message:</p> <blockquo...
1
2016-06-17T22:45:57Z
37,891,409
<p>try this:</p> <pre><code>df.ix[~df.ID.isin(list_IDs)] </code></pre> <p><strong>Explanation</strong></p> <p>constructions like <code>df.ID not in list_IDs</code> won't work even in vanilla Python:</p> <pre><code>In [12]: [1,2,3] in [1,2,3] Out[12]: False In [13]: [1,2] in [1,2,3] Out[13]: False </code></pre> <p...
0
2016-06-17T22:48:48Z
[ "python", "pandas" ]
Dropping rows in pandas with a certain condition
37,891,387
<p>I have a list of ID's and a dataframe, where one of the columns is ID. I want to drop all rows in the dataframe where the ID is not one of the ID's in the list of ID's. This is the code I use:</p> <pre><code>df = df.drop(df[df.ID not in list_IDs].index) </code></pre> <p>but I get this error message:</p> <blockquo...
1
2016-06-17T22:45:57Z
37,892,640
<p>Check out the answer from unutbu at <a href="http://stackoverflow.com/questions/23461502/evaluating-pandas-series-values-with-logical-expressions-and-if-statements">Evaluating pandas series values with logical expressions and if-statements</a> . Basically, pandas always raises an error if you try to evaluate TRUE/FA...
0
2016-06-18T02:18:06Z
[ "python", "pandas" ]
Dropping rows in pandas with a certain condition
37,891,387
<p>I have a list of ID's and a dataframe, where one of the columns is ID. I want to drop all rows in the dataframe where the ID is not one of the ID's in the list of ID's. This is the code I use:</p> <pre><code>df = df.drop(df[df.ID not in list_IDs].index) </code></pre> <p>but I get this error message:</p> <blockquo...
1
2016-06-17T22:45:57Z
37,892,764
<pre><code>import pandas as pd x = pd.Series([1,2,3]) </code></pre> <p>Now, think about how you expect python to evaluate this</p> <pre><code>(x in [1,2]) </code></pre> <p>or more directly</p> <pre><code>pd.Series([1,2,3]) in [1,2] </code></pre> <p>As you can see</p> <blockquote> <p>"ValueError: The truth value...
0
2016-06-18T02:44:44Z
[ "python", "pandas" ]
AES encryption in Node.js to match expected decryption in Python
37,891,516
<p>I have the following Python script for decryption:</p> <pre><code>from Crypto.Cipher import AES shared_secret = raw_input('Enter crypted_shared_secret: ').strip() cipher = AES.new(shared_secret.decode('base64'), AES.MODE_ECB) blob = raw_input('Enter crypted_blob: ').strip() plain = cipher.decrypt(blob.decode('bas...
0
2016-06-17T23:03:07Z
37,919,314
<p>You need to encode the shared secret key to Base64 only <em>after</em> you use it for encryption:</p> <pre><code>var shared_secret = Crypto.randomBytes(32); var cipher = Crypto.createCipheriv('aes-256-ecb', shared_secret, ""); crypted_blob = cipher.update(blob, 'utf8', 'base64') + cipher.final('base64'); // send `s...
2
2016-06-20T09:47:24Z
[ "python", "node.js", "encryption", "aes" ]
Python imaging library, ImageFont IOError
37,891,545
<p>I have python-FotoBox-Script working perfectly well on my Ubuntu labtop, but on Raspberry-Pi running Raspbian the script is having the following problem:</p> <pre><code>pi@raspberrypi:~/Desktop/FotoBox $ python PythonCollage_31.py Traceback (most recent call last): File "PythonCollage_31.py", line 49, in ...
0
2016-06-17T23:07:27Z
37,893,743
<p>The correct syntax for ImageFont.truetype is this:</p> <pre><code>ImageFont.truetype(file, size, encoding=value) </code></pre> <p>So, if you add encoding= to the start of your forth parameter, use "" instead of '', and remove the third parameter, that should look like this:</p> <pre><code>ImageFont.truetype("/usr...
0
2016-06-18T05:53:58Z
[ "python", "raspberry-pi", "python-imaging-library" ]
jupyter notebook running kernel in different env
37,891,550
<p>I've gotten myself into some kind of horrible virtualenv mess. Help?!</p> <p>I manage environments with <code>conda</code>. Until recently, I only had a python2 jupyter notebook kernel, but I decided to drag myself kicking and screaming into the 21st century and installed a python3 kernel; I forget how I did it. ...
1
2016-06-17T23:08:22Z
37,891,993
<p>This is a tricky part of ipython / Jupyter. The set of kernels available are independent of what your virtualenv is when you start jupyter Notebook. The trick is setting up the the ipykernel package in the environment you want to identify itself uniquely to jupyter. From <a href="https://ipython.readthedocs.io/en/st...
2
2016-06-18T00:06:24Z
[ "python", "packages", "jupyter", "conda", "virtual-environment" ]
Adding values associated with the same key in two different dictionaries
37,891,608
<p>I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are <code>dict1</code></p> <pre><code>{'A': 25 , 'B': 41, 'C': 32} </code></pre> <p>and <code>dict2</code></p> <pre><code>{'D':21, 'A': 12, 'B':62} </code></pre> <p>I'm writing a pr...
1
2016-06-17T23:14:58Z
37,891,629
<p>I am going to assume you are working to preserve dict_1 as the result</p> <pre><code>for key in dict_1: if key in dict_2: dict_1[key] = dict_1[key] + dict_2[key] </code></pre> <p>Need to copy key-value pairs that exist in 2 but not in 1</p> <pre><code>for key in dict_2: if key not in dict_1: ...
0
2016-06-17T23:19:05Z
[ "python", "dictionary" ]
Adding values associated with the same key in two different dictionaries
37,891,608
<p>I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are <code>dict1</code></p> <pre><code>{'A': 25 , 'B': 41, 'C': 32} </code></pre> <p>and <code>dict2</code></p> <pre><code>{'D':21, 'A': 12, 'B':62} </code></pre> <p>I'm writing a pr...
1
2016-06-17T23:14:58Z
37,891,692
<pre><code>&gt;&gt;&gt; dict1= {'A':25,'B':41,'C':32} &gt;&gt;&gt; dict2= {'D':21, 'A':12, 'B':62} &gt;&gt;&gt; for e in dict2: if e in dict1: dict1[e]=dict1[e]+dict2[e] else: dict1[e]=dict2[e] </code></pre> <p>Now your dict1 becomes the answer you want. Hope that helps. :)</p>
0
2016-06-17T23:26:28Z
[ "python", "dictionary" ]
Adding values associated with the same key in two different dictionaries
37,891,608
<p>I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are <code>dict1</code></p> <pre><code>{'A': 25 , 'B': 41, 'C': 32} </code></pre> <p>and <code>dict2</code></p> <pre><code>{'D':21, 'A': 12, 'B':62} </code></pre> <p>I'm writing a pr...
1
2016-06-17T23:14:58Z
37,891,776
<p>I think what you're missing in your solution is the use of the <code>keys</code>-method and the <code>get</code>-method that comes with dictionaries. The <code>keys</code>-method will return a list of all of keys in the key-value pairs from your dictionary. Whereas, the <code>get</code>-method will return the valu...
0
2016-06-17T23:34:35Z
[ "python", "dictionary" ]
How to add a field to a dbf file?
37,891,686
<p>I have something about like this: </p> <pre><code>from dbfpy import dbf import random db = dbf.Dbf('DMWWGS84/DMAWGS84.dbf',new=False) db.addField(("Data","D")) for record in db: print record record["Data"]=random.random() db.close() </code></pre> <p>But it complains: </p> <pre><code>Traceback (most recen...
1
2016-06-17T23:25:41Z
37,892,060
<p>Use my <a href="https://pypi.python.org/pypi/dbf" rel="nofollow">dbf</a> library instead:</p> <blockquote> <p>pip install dbf</p> </blockquote> <p>(you may need to <code>pip install enum34</code> first)</p> <p>and then the commands:</p> <pre><code># lightly tested import dbf import random db = dbf.Table('wha...
2
2016-06-18T00:18:42Z
[ "python", "dbf" ]
How to compare one employee to all employees salary in django model?
37,891,697
<pre><code>emp = Employee.objects.filter(id=1) Persons = Employee.objects.extra(select={'difference':(emp.values_list("Salary",flat=True)[0]-float('Salary'))}) </code></pre> <p>But it give Error :</p> <blockquote> <p>Exception Type: ValueError</p> <p>Exception Value:could not convert string to float: 'Sala...
0
2016-06-17T23:26:48Z
37,892,208
<p><code>'Salary'</code> is indeed a string, and not a number. So python cannot make that conversion. You don't want the string <code>'Salary'</code>, you want the field <code>Salary</code>. To do that, you need to use <a href="https://docs.djangoproject.com/en/1.9/ref/models/expressions/#f-expressions" rel="nofollow">...
0
2016-06-18T00:44:53Z
[ "python", "django", "django-models" ]
Django - Query parameter takes model type? RelatedObjectDoesNotExist: Posting has no textbook
37,891,711
<p>I have installed this Django app: <a href="http://django-auditlog.readthedocs.io/en/latest/_modules/auditlog/models.html#LogEntry" rel="nofollow">http://django-auditlog.readthedocs.io/en/latest/_modules/auditlog/models.html#LogEntry</a></p> <p>The log entries are setup with two different models which are below:</p>...
0
2016-06-17T23:28:13Z
37,892,763
<p>The <code>content_type</code> argument should be a <code>ContentType</code> object, not a model class.</p> <p>Instead of doing doing this manually you should use the <code>LogEntryManager</code>s <code>get_for_model</code> method:</p> <pre><code>LogEntry.objects.get_for_model(Posting).filter(action=2).count() </co...
1
2016-06-18T02:44:20Z
[ "python", "django", "postgresql", "foreign-keys" ]
Python - Add buttons dyanmically to layout in PyQt
37,891,774
<p>I am currently developing a desktop app using PyQt 5 and Python 3.5. Recently, I have encountered an issue while trying to dynamically add buttons to a layout. Here's what I am doing:</p> <pre><code>for i in range(len(movieList)): movies[i][0] = QtWidgets.QLabel("Title: " + movieList[i][0]) movies[...
1
2016-06-17T23:34:21Z
37,891,836
<p>I think if you change to partial then all will work fine</p> <pre><code>from functools import partial ... for i in range(len(movieList)): movies[i][0] = QtWidgets.QLabel("Title: " + movieList[i][0]) movies[i][0].setGeometry(30, 50, 15, 20) movies[i][0].setFont(self.movieTitleFont) ...
1
2016-06-17T23:42:58Z
[ "python", "python-3.x", "button", "pyqt", "desktop-application" ]
python reference preceding items in list loop
37,891,848
<p>I am trying to loop through a list but at the same time make reference to the items before so i can compare. </p> <p><strong>This is my code</strong>:</p> <pre><code>list1=[(1,'a','hii'),(2,'a','byee'),(3,'a','yoo'),(4,'b','laa'),(5,'a','mehh')] </code></pre> <p>I want to loop through my list1 tuples such that if...
3
2016-06-17T23:44:57Z
37,891,921
<p>I was making this WAY harder than it needed to be</p> <pre><code>def combine(inval): outval = [inval[0]] for item in inval[1:]: if item[0] == outval[-1][0] + 1 and item[1] == outval[-1][1]: outval[-1] = (item[0], item[1], ",".join([outval[-1][2], item[2]])) continue o...
4
2016-06-17T23:55:28Z
[ "python", "list", "loops" ]
python reference preceding items in list loop
37,891,848
<p>I am trying to loop through a list but at the same time make reference to the items before so i can compare. </p> <p><strong>This is my code</strong>:</p> <pre><code>list1=[(1,'a','hii'),(2,'a','byee'),(3,'a','yoo'),(4,'b','laa'),(5,'a','mehh')] </code></pre> <p>I want to loop through my list1 tuples such that if...
3
2016-06-17T23:44:57Z
37,891,962
<p>Edit: I've updated the algorithm according to the requirements. You can group all tuples with the same key by calling group(values, sort=True) or only group adjacent tuples with the same key by calling group(values). This algorithm also gathers all elements after the key for the final tuple instead of only grabbin...
2
2016-06-18T00:00:44Z
[ "python", "list", "loops" ]
Keras, how do I predict after I trained a model?
37,891,954
<p>I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use <code>models.predict()</code>?</p> <p>Do I have to prepare this text in a special way?</p...
3
2016-06-18T00:00:07Z
37,903,706
<p><a href="http://keras.io/models/model/#predict" rel="nofollow"><code>model.predict()</code></a> expects the first parameter to be a numpy array. You supply a list, which does not have the <code>shape</code> attribute a numpy array has.</p> <p>Otherwise your code looks fine, except that you are doing nothing with th...
2
2016-06-19T03:33:47Z
[ "python", "theano", "deep-learning", "keras" ]
Keras, how do I predict after I trained a model?
37,891,954
<p>I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use <code>models.predict()</code>?</p> <p>Do I have to prepare this text in a special way?</p...
3
2016-06-18T00:00:07Z
38,372,361
<p>I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.</p> <pre><code>fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5" modelConfig = joblib.load('modelConfig.p...
1
2016-07-14T10:56:10Z
[ "python", "theano", "deep-learning", "keras" ]
Automating install of Docker and image pull using python or bash
37,891,976
<p>I am trying to automate the process of installing the docker-engine and then asking the user if he would like to pull rhel/suse/centos images.</p> <p>Using python was my first idea but I have added bash script to make things easier, python seemed not too friendly to run cli commands.</p> <p>Now, I am planning to ...
1
2016-06-18T00:03:06Z
37,933,166
<p>Ok, so I was able to make it work in Python. I will leave the code here, in case anyone needs it. </p> <p>Cheers! Rohit</p> <pre><code>from subprocess import Popen, PIPE uid = Popen(['id', '-u'], stdin=PIPE, stdout=PIPE, stderr=PIPE) uid_get = uid.stdout.read(1) if uid_get != '0': print "This script needs to...
1
2016-06-20T23:04:55Z
[ "python", "bash", "shell", "docker", "automation" ]
Setting Python Alias on Mac Reverting after Terminal restart
37,892,063
<p>ok, so every-time I start a new terminal window I have to reset the python alias in order for it to run python3 by default.</p> <p>I'm doing the following:</p> <pre><code>alias python=python3 </code></pre> <p>This works but then resets itself, pretty sure this is not expected and wondering if anyone knows why thi...
-1
2016-06-18T00:19:43Z
37,892,143
<p>This is expected, as the alias command will only work for that specific instance of the shell. In other words, if you open another tab or window, the alias will no longer exist.</p> <p>To fix this, you need to set the alias in your shell's startup file, which is found in your home directory. For bash (the default s...
1
2016-06-18T00:32:42Z
[ "python", "osx", "python-3.x", "alias" ]
how to color HTML rows?
37,892,081
<p>I have the following code where I construct HTML rows,now when key is present in dict1 I want to color the row and when key is present in dict2 another color? how can I modify this code to color the rows?</p> <pre><code>for item in jiradb : MailBody = MailBody + "&lt;tr&gt;" MailBody = MailBody + "&lt;td&gt...
0
2016-06-18T00:23:15Z
37,892,256
<p>To solve your problem, try to fetch the values first, and use css styling to color the rows.</p> <pre><code>rows = [] for item in jiradb: data = [] key = item['key'] dict1_value = dict1.get(key) dict2_value = dict2.get(key) key_after_none_check = get_field(item,'key') crashid_link = "https://company.com...
0
2016-06-18T00:53:17Z
[ "python", "html" ]
how to color HTML rows?
37,892,081
<p>I have the following code where I construct HTML rows,now when key is present in dict1 I want to color the row and when key is present in dict2 another color? how can I modify this code to color the rows?</p> <pre><code>for item in jiradb : MailBody = MailBody + "&lt;tr&gt;" MailBody = MailBody + "&lt;td&gt...
0
2016-06-18T00:23:15Z
37,900,985
<p>Your code is quite a tangled mess. I'm not sure if I got it all right, but take a look at this version. I don't know where icount comes from, but you can get it from enumerate. I made a string to contain what I think is a template for your table rows. Then I took out all the repetitive logic in the if clauses. ...
0
2016-06-18T19:42:32Z
[ "python", "html" ]
SQLAlchemy - How to add dynamic left joins to a query?
37,892,088
<p>I have six tables, modeled like the following:</p> <pre><code>+--&lt; B &gt;--C | A | +--&lt; D &gt;--E </code></pre> <p>I would like to be able to dynamically query any of these options:</p> <pre><code>A A, B, C A, D, E A, B, C, D E </code></pre> <p>For example, querying all four would look like</p> <pre><cod...
2
2016-06-18T00:24:33Z
37,893,686
<p>Each <code>outerjoin</code> (and other SLQALchemy query methods) modifies a <code>query</code> object and returns a new query - which you can further modify by calling <code>outerjoin</code> (or <code>filter</code>, etc...) methods on. So, just use a for loop to repeatedly modify your query with an extra <code>ou...
2
2016-06-18T05:46:38Z
[ "python", "python-2.7", "sqlalchemy" ]
TD/IDF in scikit-learn
37,892,105
<p>Is there a complete Python 2.7 example about how to use TfidfTransformer (<a href="http://scikit-learn.org/stable/modules/feature_extraction.html" rel="nofollow">http://scikit-learn.org/stable/modules/feature_extraction.html</a>) to generate TF/IDF for n-grams for a corpus? Look around scikit-learn pages and it only...
0
2016-06-18T00:27:04Z
37,978,326
<p>For TF-IDF feature extraction, scikit-learn has 2 classes <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html#sklearn.feature_extraction.text.TfidfTransformer" rel="nofollow"><code>TfidfTransformer</code></a> and <a href="http://scikit-learn.org/stable/modu...
1
2016-06-22T21:13:49Z
[ "python", "python-2.7", "scikit-learn", "tf-idf" ]
iOS Push Notifications (APNs) over GAE, SSL Handshake Failure
37,892,165
<p>I am attempting to show proof of concept for iOS Push Notifications from a Google AppEngine application instance using this RPC handler...</p> <pre><code>PAYLOAD = {'aps': {'alert':'Push!','sound':'default'}} TOKEN = '[...]' class APNsTest(BaseRPCHandler): def get(self, context, name): self._call_method(co...
3
2016-06-18T00:36:16Z
37,892,193
<p>Look into using a library such as <a href="https://github.com/djacobs/PyAPNs" rel="nofollow">pyapns</a>, which is what I used to get push notifications to work on GAE. To test whether you're using the correct key/cert file, you can use apps like <a href="https://github.com/noodlewerk/NWPusher" rel="nofollow">Pusher<...
1
2016-06-18T00:42:26Z
[ "python", "ios", "google-app-engine", "ssl", "apple-push-notifications" ]
iOS Push Notifications (APNs) over GAE, SSL Handshake Failure
37,892,165
<p>I am attempting to show proof of concept for iOS Push Notifications from a Google AppEngine application instance using this RPC handler...</p> <pre><code>PAYLOAD = {'aps': {'alert':'Push!','sound':'default'}} TOKEN = '[...]' class APNsTest(BaseRPCHandler): def get(self, context, name): self._call_method(co...
3
2016-06-18T00:36:16Z
37,915,859
<p>Also, from experimenting, I've found out that SSL related errors on App Engine usually go away when I apply the built-in 3rd party ssl lib:</p> <pre><code>libraries: - name: ssl version: latest </code></pre> <p>or:</p> <pre><code>libraries: - name: ssl version: "2.7" </code></pre>
0
2016-06-20T06:29:20Z
[ "python", "ios", "google-app-engine", "ssl", "apple-push-notifications" ]
iOS Push Notifications (APNs) over GAE, SSL Handshake Failure
37,892,165
<p>I am attempting to show proof of concept for iOS Push Notifications from a Google AppEngine application instance using this RPC handler...</p> <pre><code>PAYLOAD = {'aps': {'alert':'Push!','sound':'default'}} TOKEN = '[...]' class APNsTest(BaseRPCHandler): def get(self, context, name): self._call_method(co...
3
2016-06-18T00:36:16Z
38,023,495
<p>The appropriate support files start with <a href="https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html#//apple_ref/doc/uid/TP40012582-CH26-SW11" rel="nofollow">Creating a Universal Push Notification Client SSL Certificate</a> as a <stro...
0
2016-06-24T23:33:40Z
[ "python", "ios", "google-app-engine", "ssl", "apple-push-notifications" ]
reading text file to get the output in <levelnumber> <tag> <argument>
37,892,206
<p>I am reading data from text file. the data in the file has a structure</p> <pre><code>&lt;level number&gt; &lt;tag&gt; &lt;argument&gt; 0 @I5@ INDI 1 NAME Rosy /Huleknberg/ 2 GIVN Rosy 2 SURN Huleknberg 2 _MARNM Vettle 1 SEX F 1 BIRT 2 DATE 15 SEP 1928 1 DEAT Y 2 DATE 10 MAR 2010 1 FAMS @F3@ 0 @I6@ INDI...
0
2016-06-18T00:44:51Z
37,892,252
<p>The problem isn't described clearly, but I hope this will help:</p> <p>You should use <code>line.split()</code> method instead of <code>line.strip()</code></p> <pre><code>testfile = open('test.dat') for line in gedcom_file: # I suppose that data is a list data += line.split() </code></pre> <p>And remember...
0
2016-06-18T00:52:32Z
[ "python" ]
reading text file to get the output in <levelnumber> <tag> <argument>
37,892,206
<p>I am reading data from text file. the data in the file has a structure</p> <pre><code>&lt;level number&gt; &lt;tag&gt; &lt;argument&gt; 0 @I5@ INDI 1 NAME Rosy /Huleknberg/ 2 GIVN Rosy 2 SURN Huleknberg 2 _MARNM Vettle 1 SEX F 1 BIRT 2 DATE 15 SEP 1928 1 DEAT Y 2 DATE 10 MAR 2010 1 FAMS @F3@ 0 @I6@ INDI...
0
2016-06-18T00:44:51Z
37,892,428
<p><strong>Part 1. Parsing the file</strong></p> <p>This part of your code isn't doing what you intended it to do:</p> <blockquote> <pre><code>lines = line.strip() a = lines[:1] b = lines[1] c = lines[2:] </code></pre> </blockquote> <p><code>lines</code> is a string. So <code>lines[:1]</code> is the first character...
0
2016-06-18T01:25:41Z
[ "python" ]
Python inheritance, method overloading, and decorating
37,892,219
<p>I have a class B that inherits from A :</p> <pre><code>class A(): def do_something(self, x): """Prints x.""" print(x) class B(A): def something_else(self, x): print("This isn't the same.") </code></pre> <p>I'd like to achieve a few things :</p> <ul> <li>I'd like for <code>B.do_som...
1
2016-06-18T00:47:39Z
37,892,275
<p>Yes, you can use <code>functools.wraps</code> to copy the function name and docstring. You can return an instance of the current class using <code>self.__class__</code></p> <pre><code>class A(object): def func(self): return self.__class__() class B(A): @functools.wraps(A.func) def func(self)...
2
2016-06-18T00:56:04Z
[ "python", "inheritance" ]
Python inheritance, method overloading, and decorating
37,892,219
<p>I have a class B that inherits from A :</p> <pre><code>class A(): def do_something(self, x): """Prints x.""" print(x) class B(A): def something_else(self, x): print("This isn't the same.") </code></pre> <p>I'd like to achieve a few things :</p> <ul> <li>I'd like for <code>B.do_som...
1
2016-06-18T00:47:39Z
37,897,816
<blockquote> <p>Let's say there are some methods of A that return an instance of A. If I call those methods from B, I'd like them to return an instance of B. So far, I'm overloading each function manually.</p> </blockquote> <p>Use a classmethod.</p> <pre><code>class A(object): @classmethod def f(cls): ...
-1
2016-06-18T14:02:04Z
[ "python", "inheritance" ]
How can I transfer a fixed_seed from main.py module to other modules?
37,892,221
<p>I have been working on a model which has many processes using a random number generator. The first time, I used to call <code>import random</code> in every module where it was necessary to use random generated numbers. I used this like <code>random.Random.seed(1)</code> and as it is enough to run the model two diffe...
1
2016-06-18T00:48:27Z
37,892,628
<p>It looks like you don't understand where a <code>parser</code> gets its arguments from, and what happens when you do a parse.</p> <p>A parser is not a state machine, so it does not hold information about what it parsed or pass it on to some other parser.</p> <p>When you call a script, e.g.</p> <pre><code>$ python...
2
2016-06-18T02:12:46Z
[ "python", "random", "arguments", "argparse", "sys" ]
Python uploading image/file with selenium webdriver
37,892,278
<p>The folowing is a snip of some crowdfire.com HTML code, where im trying to upload a file in the input class =...</p> <pre><code>&lt;div id="ember1089" class="ember-view"&gt; &lt;div id="ember1090" class="action__addImage pointer ember-view tooltipstered"&gt; &lt;div data-ember-action="1091"&gt; ...
1
2016-06-18T00:56:20Z
37,892,421
<p>I suspect you need to <em>make the <code>input</code> visible first</em>:</p> <pre><code>image = driver.find_element_by_css_selector('#ember1089 input') driver.execute_script("arguments[0].style.display = 'block';", image); image.send_keys('C:\Users\Brian\Desktop\Empire_fort\Bots\GetPICtures\Empire.jpg') </code></...
0
2016-06-18T01:23:57Z
[ "python", "selenium", "firefox", "selenium-webdriver", "webautomation" ]
Possible causes for error while saving file in python while running on nginx?
37,892,301
<p>I have a .py script that saves a base64 file to a png file</p> <pre><code># SAVE BASE64 STRING TO PNG IMAGE timestr = time.strftime("%Y%m%d%H%M%S") filename = "/user_score/"+self.user.username+timestr+".png" saved_file = MEDIA_ROOT+"/"+filename fh = open(saved_file, "wb") fh.write(imgbase64.decode('base64')) fh.clo...
0
2016-06-18T01:00:51Z
38,032,396
<p>This was solved by a comment by <a href="http://stackoverflow.com/users/469111/ohrstrom">ohrstrom</a>, who linked to this answer: <a href="http://serverfault.com/questions/564464/nginx-request-line-too-large/564468#564468">http://serverfault.com/questions/564464/nginx-request-line-too-large/564468#564468</a></p> <p...
0
2016-06-25T19:54:01Z
[ "python", "django", "nginx" ]
Create Numpy Array Representing a Geometric Shape
37,892,357
<p>As the title suggests, how would one create a numpy array of 3D coordinates of a geometric shape? </p> <p>Currently, I have the easiest shape already figured out:</p> <pre><code>latva = 6 latvb = 6 latvc = 6 latdiv = 20 latvadiv = latva / latdiv latvbdiv = latvb / latdiv latvcdiv = latvc / latdiv lol = np.zeros((l...
0
2016-06-18T01:12:20Z
37,894,155
<p>Because you already have convenient method to generate points in square or cube, the simplest way to make rhombus, parallelogram for 2D case and parallelepiped for 3D case is to apply affine transform to calculate new point coordinates.</p> <p>For example, to make rhombus, you can find matrix as combination of tran...
0
2016-06-18T06:51:09Z
[ "python", "arrays", "numpy", "geometry" ]
Django - variables in include file not recognized
37,892,451
<p>I am using djano 1.8.1 and python 2.7.</p> <p>On two of my template pages I have the same set of variables.</p> <p>So I decided to create an <code>{% include %}</code> page that holds these variables and then add the <code>{% include %}</code> tag on the required pages to call the variables.</p> <p>However, when ...
0
2016-06-18T01:31:25Z
37,892,958
<p>The result of the <code>{% include %}</code> tag is html, which means that you can't define variables (or blocks) in an included template.</p>
2
2016-06-18T03:32:54Z
[ "python", "django", "variables", "django-templates", "include" ]
Python C extension causes stat ENOENT
37,892,635
<p>I am attempting to implement a C extension in Python. The extension works, but as soon as the module is imported, <code>errno</code> is set to <code>ENOENT</code> (2). </p> <p>simple.c</p> <pre><code>#include &lt;Python.h&gt; #include &lt;errno.h&gt; static PyMethodDef KeypadMethods[] = { {NULL, NULL, 0, NULL...
0
2016-06-18T02:17:00Z
37,892,681
<p>A <em>lot</em> of code sets <code>errno</code> pre-emptively before performing an operation since multiple code paths may result in the same error being returned. For this reason the value in <code>errno</code> should be <em>ignored</em> unless the code <em>explicitly</em> returns an error result.</p>
1
2016-06-18T02:26:39Z
[ "python", "python-c-extension" ]
Python Selenium how extract text after element
37,892,691
<p>Here is the HTML code that I am trying to extract the text from</p> <pre><code>&lt;fieldset&gt; &lt;div class="grid-3-12 form-no-lbl"&gt; &lt;label class="form-lbl"&gt;CNPJ:&lt;/label&gt;011234560083 &lt;/div&gt; &lt;div class="grid-3-12 form-no-lbl"&gt; &lt;label class="form-lbl...
1
2016-06-18T02:29:03Z
37,892,746
<p>It is a rather common problem in Selenium. Just because <em>you cannot directly match the text nodes with <code>find_element_by_*</code> commands.</em></p> <p>In your case, I assume you know the <code>LIQ</code>, <code>ESTADO</code> etc labels beforehand and need to get a value by the label. </p> <p>The idea would...
0
2016-06-18T02:39:30Z
[ "python", "selenium", "selenium-webdriver" ]