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
listlengths
1
5
Catching the same expection in every method of a class
38,332,356
<p>I, a beginner, am working on a simple card-based GUI. written in Python. There is a base class that, among other things, consists a vocabulary of all the cards, like <code>_cards = {'card1_ID': card1, 'card2_ID': card2}</code>. The cards on the GUI are referenced by their unique IDs. </p> <p>As I plan to make the c...
4
2016-07-12T14:54:40Z
38,332,715
<p>You can always use a decorator function to get what you want. <a href="http://thecodeship.com/patterns/guide-to-python-function-decorators/" rel="nofollow">This link</a> is an excellent tutorial to learn what decorators are and how to use them. I'll give an example solution using decorators in your case. </p> <p>Ba...
1
2016-07-12T15:08:10Z
[ "python", "python-3.x", "exception", "exception-handling" ]
pandas str.extractall on complete words
38,332,394
<p>I have a column of tweets. I want to get a list of all mentions inside the tweet using the regex <code>'\@(\w+)'</code>.<br> I tried using <code>df.Tweets.str.extractall('\@(\w+)')</code> but it doesn't succeed with matching the entire word as it wants (my guess) to separate each word to many columns. I get the foll...
-1
2016-07-12T14:56:31Z
38,333,015
<p>Apparently pandas looks to separate groups to columns so the solution is to wrap all the regex also as a group.<br> <code>df.Tweets.str.extractall('(\@(\w+))')</code></p> <p>difference being a wrapping parenthesis inside the string.</p>
0
2016-07-12T15:21:56Z
[ "python", "regex", "pandas" ]
Convert numpy elements to numpy dtypes
38,332,556
<p>Is there a convenient way to convert the elements of a numpy array from arbitrary and unknown native python types to their equivalent numpy types? I could check the type of each element and convert each type individually, but I was hoping there might be a more convenient method.</p> <p>I got python types in the new...
0
2016-07-12T15:01:39Z
38,333,960
<p>You can use the numpy routine <code>astype()</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arr = np.array([1.2, 3.4, 5.6]) &gt;&gt;&gt; arr = arr.astype(np.int) &gt;&gt;&gt; print(arr) [1 2 3] </code></pre>
0
2016-07-12T16:05:05Z
[ "python", "numpy" ]
Convert numpy elements to numpy dtypes
38,332,556
<p>Is there a convenient way to convert the elements of a numpy array from arbitrary and unknown native python types to their equivalent numpy types? I could check the type of each element and convert each type individually, but I was hoping there might be a more convenient method.</p> <p>I got python types in the new...
0
2016-07-12T15:01:39Z
38,334,033
<p>The values are stored in the <code>myattr</code> attribute so I think you will need to specify this attribute explicitly. This should work</p> <pre><code>new_obj_array = np.frompyfunc(lambda x : np.int32(x.myattr), 1, 1)(obj_array) </code></pre>
0
2016-07-12T16:08:41Z
[ "python", "numpy" ]
Convert numpy elements to numpy dtypes
38,332,556
<p>Is there a convenient way to convert the elements of a numpy array from arbitrary and unknown native python types to their equivalent numpy types? I could check the type of each element and convert each type individually, but I was hoping there might be a more convenient method.</p> <p>I got python types in the new...
0
2016-07-12T15:01:39Z
38,335,229
<p>If I add to your code a <code>__repr__</code> method and some prints:</p> <pre><code>import numpy as np from operator import attrgetter class myobj(): def __init__(self, value): self.myattr = value def __repr__(self): return self.myattr.__repr__() obj_array = np.empty((3,3), dtype='object'...
0
2016-07-12T17:15:26Z
[ "python", "numpy" ]
python cgi (without flask) - can't get out of header error
38,332,579
<p>Saw the advice from existing posts and did:</p> <p>(1) Took care of "<code>SyntaxError: EOF while scanning triple-quoted string literal</code>" by putting</p> <p>(2) Supposedly took care of bad header with "<code>print "Content-type: text/html\n\n"</code>"</p> <p>But still.</p> <pre><code>[Tue Jul 12 14:55:59 20...
0
2016-07-12T15:02:26Z
38,333,136
<p>Thanks to "Daniel Roseman" Moved a command below header. I thought backbone codes that aren't directly html don't belong below.</p> <pre><code>import subprocess form = cgi.FieldStorage() from subprocess import * message = form.getvalue("message", "(no message)") print "Content-type: text/html\n\n" print os.enviro...
0
2016-07-12T15:27:54Z
[ "python", "apache2", "cgi" ]
Redis wildcard keys on get
38,332,625
<p>I am working on a python project using redis, after a few researches I didn't find anything that explain how to make a get() on a string containing a wildcard '*'.</p> <p>So I have a few keys :</p> <pre><code>example.first example.second </code></pre> <p>I would like to get the keys / values of example.first and ...
0
2016-07-12T15:04:27Z
38,332,854
<p>After reading deeper the documentation, I found this :</p> <pre><code>mymap = r_server.keys(pattern='example.*') </code></pre> <p>If that can help anyone !</p>
0
2016-07-12T15:14:56Z
[ "python", "redis", "redis-py" ]
Plot the 2D FFT of an image
38,332,642
<p>I'm trying to plot the 2D FFT of an image:</p> <pre><code>from scipy import fftpack, ndimage import matplotlib.pyplot as plt image = ndimage.imread('image2.jpg', flatten=True) # flatten=True gives a greyscale image fft2 = fftpack.fft2(image) plt.imshow(fft2) plt.show() </code></pre> <p>But I get <code>TypeEr...
1
2016-07-12T15:05:01Z
38,333,442
<p>The result of any fft is generally composed of complex numbers. That is why you can't plot it this way. Depending on what you're looking for you can start with looking at the absolute value </p> <pre><code>plt.imshow(abs(fft2)) </code></pre>
2
2016-07-12T15:42:21Z
[ "python", "matplotlib", "scipy", "fft" ]
Split Columns with ' ' and Drop One of the New Columns
38,332,781
<p>I have a csv file like this:</p> <pre><code>"NoDemande;"NoUsager";"Sens";"IdVehicule";"NoConducteur";"NoAdresse";"Fait";"aPaye";"MethodePaiement";"ArgentPercu";"HeurePrevue";"HeureDebutTrajet";"HeureArriveeSurSite";"HeureEffective" 0003;"2021";"+";"157Véh";"0002";"5712";"1";"";"";"";"07/07/2015 06:30:04";"07/0...
0
2016-07-12T15:11:28Z
38,333,842
<pre><code>import io import pandas as pd raw_df = io.StringIO("""\ HeurePrevue HeureDebutTrajet HeureArriveeSurSite HeureEffective 06/07/2015 05:30:04 06/07/2015 16:54:31 06/07/2015 16:54:35 06/07/2015 16:54:38 06/07/2015 06:10:04 06/07/2015 05:38:39 06/07/2015 06:29:51 06/07/2015 06:30:06 06/07...
0
2016-07-12T15:59:11Z
[ "python", "pandas", "time", "split" ]
Restrict each user to only vote once (Polls, django, python)
38,332,868
<p>I found an similar question <a href="http://stackoverflow.com/questions/18880152/allow-a-user-to-vote-only-once-django">here</a>, but unlike there and unlike in django official tutorial , I don't have a separate Choice class. How can I restrict every user to vote just one? What should I change in my code?</p> <p>my...
0
2016-07-12T15:15:37Z
38,333,089
<p>It looks like you have forgotten to create the <code>voter</code> instance after the user has voted.</p> <pre><code>def law_yes_vote(request, law_id): if Voter.objects.filter(law_id=law_id, user_id=request.user.id).exists(): return render(request, 'law_detail.html', { 'law': p, ...
1
2016-07-12T15:25:46Z
[ "python", "django" ]
Numpy linspace unexpected output
38,332,917
<p>I am running the code below to build a one-dimensional array for each z and t. At the present moment, I am trying to make their sizes equivalent so that they each have a length of 501. </p> <pre><code>import numpy as np #constants &amp; parameters omega = 1. eps = 1. c = 3.*(10.**8.) hbar = 1. eta = 0.01 nn = 1...
0
2016-07-12T15:17:39Z
38,333,237
<p>This is related to float arithmetic inaccuracy. It so happens that the formula for <code>intervalz</code> yields <code>500.99999999999994</code>. This is just floating accuracy issue you can find all over SO. The <code>np.linspace</code> command then takes this number as 500 and not as 501. </p> <p>Since <code>lins...
0
2016-07-12T15:32:41Z
[ "python", "arrays", "python-2.7", "numpy" ]
Numpy linspace unexpected output
38,332,917
<p>I am running the code below to build a one-dimensional array for each z and t. At the present moment, I am trying to make their sizes equivalent so that they each have a length of 501. </p> <pre><code>import numpy as np #constants &amp; parameters omega = 1. eps = 1. c = 3.*(10.**8.) hbar = 1. eta = 0.01 nn = 1...
0
2016-07-12T15:17:39Z
38,333,436
<p>It is a problem of rounding. If you try to subtract 501 from intervalz you will find a very small negative number, -5.68e-14; linspace just takes the integer part of it, that is 500, and provides a 500-long list.</p> <p>Notice two other problems with your code: </p> <ol> <li><code>dt</code> does not provide the co...
0
2016-07-12T15:42:08Z
[ "python", "arrays", "python-2.7", "numpy" ]
Python data error: ValueError: invalid literal for int() with base 10: '42152129.0'
38,332,932
<p>I am working on a simple data science project with Python. However, I am getting an error which is the following:</p> <p>ValueError: could not convert string to float:</p> <p>Here is what my code looks like:</p> <pre><code>import matplotlib.pyplot as plt import csv from datetime import datetime filename = 'USAI...
1
2016-07-12T15:18:22Z
38,332,983
<p>The first failure is because you passed a string with <code>.</code> in it to <code>int()</code>; you can't convert that to an integer because there is a decimal portion.</p> <p>The second failure is due to a <em>different</em> <code>row[1]</code> string value; one that is empty.</p> <p>You could test for that:</p...
4
2016-07-12T15:20:21Z
[ "python", "csv", "pandas", "matplotlib", "data-science" ]
Python data error: ValueError: invalid literal for int() with base 10: '42152129.0'
38,332,932
<p>I am working on a simple data science project with Python. However, I am getting an error which is the following:</p> <p>ValueError: could not convert string to float:</p> <p>Here is what my code looks like:</p> <pre><code>import matplotlib.pyplot as plt import csv from datetime import datetime filename = 'USAI...
1
2016-07-12T15:18:22Z
38,332,993
<p>Some of the entries in <code>row[1]</code> are empty so you probably want to check for those before trying to <em>cast</em>. Pass a default value of, say <code>0</code>, if the entry is blank.</p> <p>Then you should consider using <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal...
1
2016-07-12T15:20:58Z
[ "python", "csv", "pandas", "matplotlib", "data-science" ]
Adafruit BLE python library can't list descriptors
38,333,072
<p>I'm trying to use BLE library for python to communicate with one Nordic nrf51844 chipset. Because one characteristic is notification enabled, I need to enable notification from client side by setting the descriptor Client Characteristic Configuration to 0x0001. But I failed to get the descriptor with the call "chara...
0
2016-07-12T15:24:52Z
38,389,279
<p>Finally I figured out by checking the API of IOS to set notification. It should be set by calling setNotify for characteristic instead of writeValue for descriptor. And for the descriptor stuff, it shows we need to wait for some time before all descriptors are discovered and returned. Might be the issue implemented ...
0
2016-07-15T06:31:21Z
[ "python", "bluetooth-lowenergy", "adafruit" ]
to_latex() does not feature to_string()'s justify parameter
38,333,157
<p>From <code>to_string()</code>:</p> <blockquote> <p>justify : {‘left’, ‘right’}, default None Left or right-justify the column labels. If None uses the option from the > print configuration (controlled by set_option), ‘right’ out of the box.</p> </blockquote> <p><a href="http://pandas.pydata.org/pan...
0
2016-07-12T15:28:47Z
38,333,484
<p>Use the <code>column_format</code> argument.</p> <pre><code>import io import pandas as pd raw_df = io.StringIO("""\ id1 id2 weights 0 a 2a 144.0 1 a 2b 52.5 2 b 2a 2.0 3 b 2e 1.0 """) df = pd.read_csv(raw_df, delim_whitespace=True) print(df.to_latex()) # Output: # # \begin{tabu...
2
2016-07-12T15:44:18Z
[ "python", "pandas" ]
Tkinter (Python 3.5): TypeError when calling `.configure` on a label object
38,333,226
<p>I have a <code>label</code> object that needs to display a variety of images. Based on my research, the following script (below) should successfully update the image displayed in my <code>label</code> object. However, when I call <code>self.ImageViewer.configure(image=self.imgToDisp)</code>, I get a TypeError (seen ...
1
2016-07-12T15:32:15Z
38,334,144
<p>You need to change <code>self.imgToDisp = PhotoImage(im)</code> to <code>self.imgToDisp = ImageTk.PhotoImage(im)</code></p> <p>Of course, you must add <code>ImageTk</code> to your import statements. I think you already did: <code>from PIL import Image</code>. If So, modify it to: <code>from PIL import Image, ImageT...
2
2016-07-12T16:15:06Z
[ "python", "python-3.x", "tkinter" ]
How to get the condensed form of pairwise distances directly?
38,333,332
<p>I have a very large scipy sparse csr matrix. It is a 100,000x2,000,000 dimensional matrix. Let's call it <code>X</code>. Each row is a sample vector in a 2,000,000 dimensional space.</p> <p>I need to calculate the cosine distances between each pair of samples very efficiently. I have been using <code>sklearn pairw...
0
2016-07-12T15:37:14Z
38,364,226
<p>I dug into the code for both versions, and think I understand what both are doing.</p> <p>Start with a small simple <code>X</code> (dense):</p> <pre><code>X = np.arange(9.).reshape(3,3) </code></pre> <p><code>pdist</code> cosine does:</p> <pre><code>norms = _row_norms(X) _distance_wrap.pdist_cosine_wrap(_convert...
1
2016-07-14T01:41:55Z
[ "python", "scipy", "scikit-learn", "cosine-similarity", "pdist" ]
Construct a Tree with list of Objects in Python
38,333,485
<p>I created a class that is formatted as follows:</p> <pre><code>class PathStructure(object): def __init__(self, Description, ID, Parent): self.Description = Description self.ID = ID self.Parent = Parent self.Children = [] </code></pre> <p>Where Description, ID and Parent are stri...
-2
2016-07-12T15:44:20Z
38,335,607
<p>I was able to get close to where I want to be with the following:</p> <pre><code>full = collections.defaultdict(dict) for item in pathstructs: name = item.Description ident = item.ID perent = item.Parent final = full[ident] if parent: full[parent][ident] = final else: root =...
0
2016-07-12T17:37:29Z
[ "python", "object", "tree" ]
Python: two lines in one
38,333,500
<p>I'm "Learning Python The Hard Way!"</p> <p>There is learning drill in exercise 17:</p> <p># we could do these two on one line, how?</p> <pre><code>in_file = open(from_file) indata = in_file.read() </code></pre> <p>REALLY Stuck... Please, help.</p>
-6
2016-07-12T15:44:57Z
38,333,534
<p>indata = open(from_file).read()</p>
0
2016-07-12T15:46:22Z
[ "python" ]
Python: two lines in one
38,333,500
<p>I'm "Learning Python The Hard Way!"</p> <p>There is learning drill in exercise 17:</p> <p># we could do these two on one line, how?</p> <pre><code>in_file = open(from_file) indata = in_file.read() </code></pre> <p>REALLY Stuck... Please, help.</p>
-6
2016-07-12T15:44:57Z
38,334,290
<p>Another option is to use the python "with" statement.</p> <p>By simply calling the open() and read() methods without any try/except clause, the code is not taking care of exceptions like file is not present or could not be read - like file permissions. Also you have to remember to close() once you are done with rea...
0
2016-07-12T16:22:39Z
[ "python" ]
Couple the data in all possible combinations
38,333,533
<p>I have data in column in two columns like this</p> <pre><code>Id Value 1 a 2 f 1 c 1 h 2 a </code></pre> <p>and I'd like couple the data of the 'Value' column in all possible combinations based on the same Id such as</p> <pre><code>(a,c) (a,h) (c,h) (f,a) </code></pre> <p>Is there any R or Python or V...
0
2016-07-12T15:46:16Z
38,333,598
<p>Using <code>R</code> you could try:</p> <pre><code>library(purrr) df %&gt;% split(.$Id) %&gt;% map(~ t(combn(.$Value, 2))) </code></pre> <p>Which gives:</p> <pre><code>#$`1` # [,1] [,2] #[1,] "a" "c" #[2,] "a" "h" #[3,] "c" "h" # #$`2` # [,1] [,2] #[1,] f a #Levels: a c f h </code></pre>
2
2016-07-12T15:49:00Z
[ "python", "vba", "python-3.x", "openrefine" ]
Couple the data in all possible combinations
38,333,533
<p>I have data in column in two columns like this</p> <pre><code>Id Value 1 a 2 f 1 c 1 h 2 a </code></pre> <p>and I'd like couple the data of the 'Value' column in all possible combinations based on the same Id such as</p> <pre><code>(a,c) (a,h) (c,h) (f,a) </code></pre> <p>Is there any R or Python or V...
0
2016-07-12T15:46:16Z
38,333,957
<p>To return a character matrix with these combinations using base R, try</p> <pre><code>do.call(rbind, t(sapply(split(df, df$Id), function(i) t(combn(i$Value, 2))))) [,1] [,2] [1,] "a" "c" [2,] "a" "h" [3,] "c" "h" [4,] "f" "a" </code></pre> <p>Each row is a desired combination.</p> <p>To break this dow...
3
2016-07-12T16:05:03Z
[ "python", "vba", "python-3.x", "openrefine" ]
Couple the data in all possible combinations
38,333,533
<p>I have data in column in two columns like this</p> <pre><code>Id Value 1 a 2 f 1 c 1 h 2 a </code></pre> <p>and I'd like couple the data of the 'Value' column in all possible combinations based on the same Id such as</p> <pre><code>(a,c) (a,h) (c,h) (f,a) </code></pre> <p>Is there any R or Python or V...
0
2016-07-12T15:46:16Z
38,334,519
<p>Just another way (possibly slightly faster as it exploits the fact that you're looking for all <em>pairs</em>, and avoids <code>combn</code> and <code>t</code>):</p> <pre><code>require(data.table) dt[, .( c1 = rep(Value, (.N:1)-1L), c2 = rep(Value, (1:.N)-1L) ), by=Id] # Id c1 c2 # 1: 1 a c # 2: 1 a h # 3:...
2
2016-07-12T16:33:40Z
[ "python", "vba", "python-3.x", "openrefine" ]
How to implement an interruptible time.sleep in Tornado?
38,333,579
<p>I am writing a process (called the <em>requesting process</em>) which will send HTTP requests periodically, but can be interrupted by another thread/process (called the <em>main process</em>) at any time. Initially I was using a thread pool for the requests with a <code>multiprocessing.Event</code> object to wait fo...
3
2016-07-12T15:48:04Z
38,333,874
<p>You don't need Toro anymore. Tornado 4.2 and later include all Toro's features.</p> <p>Try something like this, with a Condition instead of an Event:</p> <pre><code>import datetime import logging from tornado import gen, options from tornado.ioloop import IOLoop from tornado.locks import Condition condition = Co...
2
2016-07-12T16:00:55Z
[ "python", "python-3.x", "asynchronous", "concurrency", "tornado" ]
Search for a partial string match in a data frame column from a list - Pandas - Python
38,333,582
<p>I have a list:</p> <pre><code>things = ['A1','B2','C3'] </code></pre> <p>I have a pandas data frame with a column containing values separated by a semicolon - some of the rows will contain matches with one of the items in the list above (it won't be a perfect match since it has other parts of a string in the colum...
1
2016-07-12T15:48:22Z
38,333,642
<p>You can avoid the loop by joining your list of words to create a regex and use <code>str.contains</code>:</p> <pre><code>pat = '|'.join(thing) for_new_df = df[df['COLUMN'].str.contains(pat)] </code></pre> <p>should just work</p> <p>So the regex pattern becomes: <code>'A1|B2|C3'</code> and this will match anywhere...
2
2016-07-12T15:50:46Z
[ "python", "pandas" ]
Search for a partial string match in a data frame column from a list - Pandas - Python
38,333,582
<p>I have a list:</p> <pre><code>things = ['A1','B2','C3'] </code></pre> <p>I have a pandas data frame with a column containing values separated by a semicolon - some of the rows will contain matches with one of the items in the list above (it won't be a perfect match since it has other parts of a string in the colum...
1
2016-07-12T15:48:22Z
38,334,574
<p>Pandas is actually amazing but I don't find it very easy to use. However it does have many functions designed to make life easy, including tools for searching through huge data frames.</p> <p>Though it may not be a full solution to your problem, this may help set you off on the right foot. I have assumed that you...
1
2016-07-12T16:36:38Z
[ "python", "pandas" ]
Launch python script with abaqus command
38,333,601
<p>I have a command file (.cmd) which I use to launch Abaqus command line windows. Then, I use the command 'abaqus python test.py' to launch python command inside Abaqus. </p> <p>Now, I would like to use a python script to do that. I try something like this but doesn't work. Someone know the trick ?</p> <p>Thanks !!<...
0
2016-07-12T15:49:08Z
38,352,839
<h2>Using .cmd-file:</h2> <p>This way might work with cmd file:</p> <pre><code>abaqusPath = "C:\\Abaqus\\script\\abaqus.cmd /C" args = AbaqusPath + "abaqus python test.py" subprocess.call(args) </code></pre> <p>Flag /C is needed to run command and then terminate.</p> <h2>Easiest way:</h2> <p>Just add the folder wi...
1
2016-07-13T13:15:38Z
[ "python", "abaqus" ]
Launch python script with abaqus command
38,333,601
<p>I have a command file (.cmd) which I use to launch Abaqus command line windows. Then, I use the command 'abaqus python test.py' to launch python command inside Abaqus. </p> <p>Now, I would like to use a python script to do that. I try something like this but doesn't work. Someone know the trick ?</p> <p>Thanks !!<...
0
2016-07-12T15:49:08Z
38,352,973
<p>I've never had any success using just string arguments for subprocess functions.</p> <p>I would try it this way:</p> <pre><code>import subprocess abaqus_path = r"C:\Abaqus\script\abaqus.cmd" subprocess.call([abaqus_path, '-abaqus', 'python', 'test.py']) </code></pre>
1
2016-07-13T13:20:54Z
[ "python", "abaqus" ]
Calculating Length of Sequences from .PBS File
38,333,655
<p>I am new here. I am looking for help in a bioinformatics type task I have. The task was to calculate the total length of all the sequences in a .pbs file. </p> <p>The file when opened, displays something like :</p> <p>The Length is 102 </p> <p>The Length is 1100 </p> <p>The Length is 101</p> <p>The Length is 11...
-2
2016-07-12T15:51:11Z
38,333,795
<p><code>"The Length is "</code> has 14 characters so <code>line[14:]</code> will give you the substring corresponding to the number you are after (starting after the 14th character), you then just have to convert it to <code>int</code> with <code>int(line[14:])</code> before adding to your total: <code>total += int(li...
-1
2016-07-12T15:56:46Z
[ "python", "bioinformatics" ]
Calculating Length of Sequences from .PBS File
38,333,655
<p>I am new here. I am looking for help in a bioinformatics type task I have. The task was to calculate the total length of all the sequences in a .pbs file. </p> <p>The file when opened, displays something like :</p> <p>The Length is 102 </p> <p>The Length is 1100 </p> <p>The Length is 101</p> <p>The Length is 11...
-2
2016-07-12T15:51:11Z
38,334,060
<ol> <li>You need to parse your input to get the data you want to work with.<br/> a. x.replace('The Length is ','') - this removes the unwanted text.<br/> b. int(x.replace('The Length is ','')) - convert digit characters to<br/> an integer<br/></li> <li>Add to a total: total += int(x.replace('The Length is ',''))...
-1
2016-07-12T16:10:18Z
[ "python", "bioinformatics" ]
gspread update_cell very slow
38,333,715
<p>I have two google spreadsheets:</p> <p>QC- many columns, I want to check if a value from column 4 appears in the second spreadsheet lastEdited_PEID; if it does, it would put 'Bingo!' in column 14 of the same row where the value was found</p> <p>lastEdited- one column, long spreadsheets of values</p> <p>I achieve ...
2
2016-07-12T15:54:17Z
38,421,216
<p>Since gspread is a wrapper around the Google Sheet's REST API each operation you perform on a spreadsheet renders to an HTTP request to the API. Most of the time this is the slowest part of the code. If you want to improve performance you need to figure out how to reduce the number of interactions with the API.</p> ...
2
2016-07-17T12:31:02Z
[ "python", "python-3.x", "google-spreadsheet", "gspread" ]
Does Python have a particular term for slicing a list element?
38,333,745
<pre><code>g = ["01", "05", "95", "99"] x = g[0][:1] print x </code></pre> <p>I was coding strings and slices, like above, and I was wondering if the double brackets had a particular Pythonic name (manly to differentiate the two sets of parenthesis)? Or is it just called a sliced element?</p>
0
2016-07-12T15:54:59Z
38,333,843
<p>There's nothing special about this. <code>g[0]</code> returns an item that is itself sliceable; it's just short for</p> <pre><code>g1 = g[0] x = g1[:1] </code></pre> <p>or</p> <pre><code>x = g.__getitem__(0).__getslice__(None, 1) </code></pre> <p>or</p> <pre><code>x = g.__getitem(0).__getitem__(slice(None, 1)) ...
0
2016-07-12T15:59:12Z
[ "python", "slice" ]
leetcode twoSum: order of elements in the result list
38,333,765
<p>I just started to solve the problems in leetcode with python. When I solve the problem of two sum: <a href="https://leetcode.com/problems/two-sum/" rel="nofollow">Two Sum of LeetCode</a>. I found the order of the result element in my list are reversed comparing to the correct answer. My code is below:</p> <pre><cod...
0
2016-07-12T15:55:32Z
38,335,901
<p>You are supposed to print the two indices in the array whose value sum is target value. In the given case of [3,2,4], as you are looping on all three values and comparing in all values of the dict always, you can break the loop in first occurrence of solution. </p> <pre><code>for key in nums: rem = target - ...
0
2016-07-12T17:55:07Z
[ "python" ]
Seaching a list for more than one string in python
38,333,848
<p>I wrote the below function to return True if it detects the string 'Device' in a list</p> <pre><code>def data_filter2(inner_list): return any(['Device' in str(x) for x in inner_list]) </code></pre> <p>is there a way to search the list for more than one string and return True it it finds either one?</p> <p>I tr...
0
2016-07-12T15:59:37Z
38,333,912
<p>You could use a binary operator <code>or</code> or <code>and</code> depending on what you intend, but slightly different from how you've done it:</p> <pre><code>def data_filter2(inner_list): return any('Device' in str(x) or 'Drug' in str(x) for x in inner_list) </code></pre> <p>You could use a generator express...
1
2016-07-12T16:02:21Z
[ "python", "list" ]
Seaching a list for more than one string in python
38,333,848
<p>I wrote the below function to return True if it detects the string 'Device' in a list</p> <pre><code>def data_filter2(inner_list): return any(['Device' in str(x) for x in inner_list]) </code></pre> <p>is there a way to search the list for more than one string and return True it it finds either one?</p> <p>I tr...
0
2016-07-12T15:59:37Z
38,333,989
<p>What if you reverse the logic?</p> <pre><code>def data_filter2(inner_list): return any([str(x) in ['Device', 'Drug'] for x in inner_list]) </code></pre> <p>This provides a framework that can "accept" more items to check for. Chaining <code>or</code> is not very pythonic to my eyes.</p> <p>What is interesting t...
1
2016-07-12T16:06:25Z
[ "python", "list" ]
Seaching a list for more than one string in python
38,333,848
<p>I wrote the below function to return True if it detects the string 'Device' in a list</p> <pre><code>def data_filter2(inner_list): return any(['Device' in str(x) for x in inner_list]) </code></pre> <p>is there a way to search the list for more than one string and return True it it finds either one?</p> <p>I tr...
0
2016-07-12T15:59:37Z
38,334,112
<p>The solutions using <code>any</code> and comprenhensions are nice. Another alternative would be to use set intersection.</p> <pre><code>In [30]: bool(set(['aaa', 'foo']) &amp; set(['foo'])) Out[30]: True In [31]: bool(set(['aaa', 'foo']) &amp; set(['bar'])) Out[31]: False </code></pre>
1
2016-07-12T16:13:26Z
[ "python", "list" ]
Seaching a list for more than one string in python
38,333,848
<p>I wrote the below function to return True if it detects the string 'Device' in a list</p> <pre><code>def data_filter2(inner_list): return any(['Device' in str(x) for x in inner_list]) </code></pre> <p>is there a way to search the list for more than one string and return True it it finds either one?</p> <p>I tr...
0
2016-07-12T15:59:37Z
38,334,277
<p>You can do it in one line like so:</p> <pre><code>def data_filter2(inner_list): return any([x in y for x in ['Device', 'Drug'] for y in inner_list]) </code></pre>
0
2016-07-12T16:22:02Z
[ "python", "list" ]
how skip lines in several files using one function?
38,333,889
<p>I need some help. I have four different files to which I would like to open and only read the files while skipping the headers for each individual file into a function. This is what I got so far but i'm not even sure how to move forward from here: </p> <pre><code>import csv particle_counter = file('C:/Users/Deskto...
-1
2016-07-12T16:01:26Z
38,334,504
<p>You could have a function like this:</p> <pre><code>def skipline(readerlist): for reader in readerlist: next(reader) </code></pre> <p>And call it like this:</p> <pre><code>skipline([reader1, reader2, reader3, reader4]) </code></pre> <p>Although really, I think it would be just fine to do without a fu...
1
2016-07-12T16:33:03Z
[ "python", "csv", "header" ]
Python Selenium Clicking All Elements on a Menu
38,333,952
<p>I'm trying to click all elements on the navigation menu of python.org. My code runs without any errors, but only the "community" element is clicked. Here is my code:</p> <pre><code>driver = webdriver.Chrome("/Users/drao/Documents/chromedriver") driver.get("http://www.python.org") driver.maximize_window() #finds al...
0
2016-07-12T16:04:41Z
38,334,131
<p>try grabbing all the elements using the following selector:</p> <pre><code>all_elems = driver.find_elements_by_css_selector('nav.python-navigation ul.navigation li') </code></pre> <p>Keep in mind that everytime you click on one of those elements, the entire page reloads, and you might run into StaleElementExceptio...
0
2016-07-12T16:14:32Z
[ "python", "html", "selenium", "pycharm" ]
Python Selenium Clicking All Elements on a Menu
38,333,952
<p>I'm trying to click all elements on the navigation menu of python.org. My code runs without any errors, but only the "community" element is clicked. Here is my code:</p> <pre><code>driver = webdriver.Chrome("/Users/drao/Documents/chromedriver") driver.get("http://www.python.org") driver.maximize_window() #finds al...
0
2016-07-12T16:04:41Z
38,334,410
<p>There is only one element with the ID <code>mainnav</code>, so your code is technically working correctly. It grabs the one element and clicks it, then exits. I guess the click falls down to the first clickable element in the DOM.</p> <p>To get all the clickable tabs you'll need to use a different approach. Here is...
0
2016-07-12T16:27:58Z
[ "python", "html", "selenium", "pycharm" ]
Converting object to datetime format in python
38,333,954
<p>Below is the first row of my csv DateTime column:</p> <p>Mon Nov 02 20:37:10 GMT+00:00 2015</p> <p>The DateTime column is currently an object and I want to convert it to datetime format so that I can get the date to appear as 2015-11-02 and I will create a separate column for the time.</p> <p>The code I am using ...
2
2016-07-12T16:04:45Z
38,334,031
<p>Use <code>pd.to_datetime()</code>:</p> <pre><code>df['DateTime'] = pd.to_datetime(df['DateTime']) </code></pre> <p>For example,</p> <pre><code>pd.to_datetime('Mon Nov 02 20:37:10 GMT+00:00 2015') </code></pre> <p>produces <code>Timestamp('2015-11-02 20:37:10')</code>.</p>
2
2016-07-12T16:08:38Z
[ "python", "datetime", "pandas" ]
python/django - why I can't call other function(in another file) in views.py
38,333,994
<p>I want to call <code>generate_pic</code> from my views.py with some pass-in parameters</p> <p>In views.py I have:</p> <pre><code>def msa_result(request, measurement_id): try: print measurement_id _measurement = UserMeasurements.objects.get(measurement_id=measurement_id) import MySQLdb ...
1
2016-07-12T16:06:37Z
38,334,303
<p>Where you pass the dict into the function you have to prepend <code>**</code> to pass it in as kwargs.</p> <pre><code>result = generate_pic(db, **processing_dict) </code></pre>
2
2016-07-12T16:23:20Z
[ "python", "django" ]
Conditional Regex: if A and B, choose B
38,334,063
<p>I need to extract IDs from a string of the following format: <code>Name ID</code>, where the two are separated by white space.</p> <p><em>Example</em>: </p> <pre><code>'Riverside 456' </code></pre> <p>Sometimes, the ID is followed by the letter <code>A</code> or <code>B</code> (separated by white space):</p> ...
1
2016-07-12T16:10:42Z
38,334,126
<p>Your <code>(\d{1,3})|(\d{1,3}\s[AB])</code> will always match the first branch as in an NFA regex, if the alternation group is not anchored on either side, the first branch that matches "wins", and the rest of the branches to the right are not tested against.</p> <p>You can use an optional group:</p> <pre><code>\d...
2
2016-07-12T16:14:16Z
[ "python", "regex", "string" ]
Conditional Regex: if A and B, choose B
38,334,063
<p>I need to extract IDs from a string of the following format: <code>Name ID</code>, where the two are separated by white space.</p> <p><em>Example</em>: </p> <pre><code>'Riverside 456' </code></pre> <p>Sometimes, the ID is followed by the letter <code>A</code> or <code>B</code> (separated by white space):</p> ...
1
2016-07-12T16:10:42Z
38,334,127
<p>If you have an optional part that you might want to include, but not necessarily need, you could just use an "at most one time" quantifier:</p> <pre><code>Riverside (\d{1,3}(?: [AB])?) </code></pre> <p>The <code>?:</code> marks groups as "not-capturing", so they won't be returned. And the <code>?</code> tells it t...
2
2016-07-12T16:14:17Z
[ "python", "regex", "string" ]
Conditional Regex: if A and B, choose B
38,334,063
<p>I need to extract IDs from a string of the following format: <code>Name ID</code>, where the two are separated by white space.</p> <p><em>Example</em>: </p> <pre><code>'Riverside 456' </code></pre> <p>Sometimes, the ID is followed by the letter <code>A</code> or <code>B</code> (separated by white space):</p> ...
1
2016-07-12T16:10:42Z
38,334,310
<pre><code>import re pattern = re.compile(r'(\d{1,3}\s?[AB]?)$') print(pattern.search('Riverside 456').group(0)) # =&gt; '456' print(pattern.search('Riverside 456 A').group(0)) # =&gt; '456 A' </code></pre>
0
2016-07-12T16:23:53Z
[ "python", "regex", "string" ]
Conditional Regex: if A and B, choose B
38,334,063
<p>I need to extract IDs from a string of the following format: <code>Name ID</code>, where the two are separated by white space.</p> <p><em>Example</em>: </p> <pre><code>'Riverside 456' </code></pre> <p>Sometimes, the ID is followed by the letter <code>A</code> or <code>B</code> (separated by white space):</p> ...
1
2016-07-12T16:10:42Z
38,334,508
<p>You could use alternation</p> <pre><code>p = re.compile('''(\d{1,3}\s[AB]|\d{1,3})$''') </code></pre> <p>NB <code>$</code> or maybe <code>\s</code> at the end (outside the group) is important, otherwise it will capture both <code>123 C</code> and <code>1234</code> as <code>123</code> rather than fail to match.</p>...
0
2016-07-12T16:33:19Z
[ "python", "regex", "string" ]
Conditional Regex: if A and B, choose B
38,334,063
<p>I need to extract IDs from a string of the following format: <code>Name ID</code>, where the two are separated by white space.</p> <p><em>Example</em>: </p> <pre><code>'Riverside 456' </code></pre> <p>Sometimes, the ID is followed by the letter <code>A</code> or <code>B</code> (separated by white space):</p> ...
1
2016-07-12T16:10:42Z
38,334,593
<p>Try just reversing the order of the statements to have the more specific one first. I.e.:</p> <pre><code> (\d{1,3}\s[AB]) | (\d{1,3}) </code></pre>
3
2016-07-12T16:37:16Z
[ "python", "regex", "string" ]
How to concatenate strings in a tuple?
38,334,230
<pre><code>input:[("xyz",100),("tao",90),("quinee",100)] </code></pre> <p>when the <strong>numbers are equal</strong> the strings are to be concatenated into a single list.</p> <pre><code> output:[(["xyz","quinee"],100),(["tao"],90)] </code></pre>
-3
2016-07-12T16:19:19Z
38,334,306
<p><a href="https://docs.python.org/2.7/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> can do that.</p> <pre><code>from itertools import groupby def key(x): return x[1] input=[("xyz",100),("tao",90),("quinee",100)] output = [ (list(string for string,index in group),i...
1
2016-07-12T16:23:32Z
[ "python", "string", "list", "tuples" ]
How to concatenate strings in a tuple?
38,334,230
<pre><code>input:[("xyz",100),("tao",90),("quinee",100)] </code></pre> <p>when the <strong>numbers are equal</strong> the strings are to be concatenated into a single list.</p> <pre><code> output:[(["xyz","quinee"],100),(["tao"],90)] </code></pre>
-3
2016-07-12T16:19:19Z
38,334,322
<p>You can use a <code>defaultdict</code>:</p> <pre><code>from collections import defaultdict l = [("xyz",100),("tao",90),("quinee",100)] d = defaultdict(list) for i in l: d[i[1]].append(i[0]) r = [(j, i) for i, j in d.items()] print(r) # [(['tao'], 90), (['xyz', 'quinee'], 100)] </code></pre>
1
2016-07-12T16:24:18Z
[ "python", "string", "list", "tuples" ]
How to concatenate strings in a tuple?
38,334,230
<pre><code>input:[("xyz",100),("tao",90),("quinee",100)] </code></pre> <p>when the <strong>numbers are equal</strong> the strings are to be concatenated into a single list.</p> <pre><code> output:[(["xyz","quinee"],100),(["tao"],90)] </code></pre>
-3
2016-07-12T16:19:19Z
38,334,358
<p>Try using a defaultdict, that defaults its value to a list:</p> <pre><code>from collections import defaultdict def concat(lst): d = defaultdict(list) for k, v in lst: d[v].append(k) return [(v, k) for k, v in d.items()] </code></pre>
1
2016-07-12T16:25:57Z
[ "python", "string", "list", "tuples" ]
looping string in python
38,334,237
<p>I need to do the same analysis on 2000 data files which has a name like abc_0.dat, abc_1.dat .... abc_1999.dat. I wonder is there anyway to make a loop for this kind of problem in python. Here is the script I was working on. </p> <pre><code>from scipy import stats import numpy as np import scipy as sp import matplo...
1
2016-07-12T16:19:47Z
38,334,402
<p>Your question is really badly phrased, but if i get the gist of what you're saying, here's a better way.</p> <p>(Ensure all the files are in the same directory).</p> <pre><code>import glob directory = 'path/to/directory' + '*.dat' files = glob.glob(directory) for currFile in files: function1(currFile) fu...
0
2016-07-12T16:27:34Z
[ "python", "string", "loops" ]
looping string in python
38,334,237
<p>I need to do the same analysis on 2000 data files which has a name like abc_0.dat, abc_1.dat .... abc_1999.dat. I wonder is there anyway to make a loop for this kind of problem in python. Here is the script I was working on. </p> <pre><code>from scipy import stats import numpy as np import scipy as sp import matplo...
1
2016-07-12T16:19:47Z
38,342,212
<p>I have solved the problem with for loop and combining string. </p> <pre><code>for x in xrange (0,2000): gps_time = 932170000 + x*1000 a_file =str(int(gps_time)) + ".0-" + str(x) + ".dat" b_file =str(int(gps_time)) + ".0.dat" </code></pre>
0
2016-07-13T03:27:47Z
[ "python", "string", "loops" ]
How should I receive first string from columns in dataframe using pandas?
38,334,293
<p>emp.csv</p> <pre><code>import pandas as pd import io temp=u"""index empno ename job mgr hiredate sal comm deptno 0, 7839, KING, PRESIDENT, 0, 1981-11-17, 5000, 0, 10 1, 7698, BLAKE, MANAGER, 7839, 1981-05-01, 2850, 0, 30 2, 7782, CLARK, MANAGER, 7839, 1981-05-09, 2450...
2
2016-07-12T16:22:54Z
38,334,769
<p>You can try this code:</p> <pre><code>emp['firstEname'] = emp['ename'].apply(lambda x: x[0]) </code></pre> <p>It will create another column called <code>firstEname</code>, and fill it with the first character of each <code>ename</code> occurrence.</p> <p>Output for <code>emp['firstEname']</code>:</p> <pre><code>...
2
2016-07-12T16:46:58Z
[ "python" ]
Reversing 'one-hot' encoding in Pandas
38,334,296
<p><strong>Problem statement</strong> I want to go from this data frame which is basically one hot encoded. </p> <pre><code> In [2]: pd.DataFrame({"monkey":[0,1,0],"rabbit":[1,0,0],"fox":[0,0,1]}) Out[2]: fox monkey rabbit 0 0 0 1 1 0 1 0 2 1 0 0 ...
3
2016-07-12T16:23:02Z
38,334,528
<p><strong>UPDATE:</strong> i think <a href="http://stackoverflow.com/questions/38334296/reversing-one-hot-encoding-in-pandas/38334528?noredirect=1#comment64090931_38334528">ayhan</a> is right and it should be:</p> <pre><code>df.idxmax(axis=1) </code></pre> <p>Demo:</p> <pre><code>In [40]: s = pd.Series(['dog', 'cat...
5
2016-07-12T16:33:52Z
[ "python", "pandas", "numpy", "dataframe" ]
Reversing 'one-hot' encoding in Pandas
38,334,296
<p><strong>Problem statement</strong> I want to go from this data frame which is basically one hot encoded. </p> <pre><code> In [2]: pd.DataFrame({"monkey":[0,1,0],"rabbit":[1,0,0],"fox":[0,0,1]}) Out[2]: fox monkey rabbit 0 0 0 1 1 0 1 0 2 1 0 0 ...
3
2016-07-12T16:23:02Z
38,334,644
<p>I'd do:</p> <pre><code>cols = df.columns.to_series().values pd.DataFrame(np.repeat(cols[None, :], len(df), 0)[df.astype(bool).values], df.index[df.any(1)]) </code></pre> <p><a href="http://i.stack.imgur.com/wTOlb.png" rel="nofollow"><img src="http://i.stack.imgur.com/wTOlb.png" alt="enter image description here"><...
2
2016-07-12T16:39:57Z
[ "python", "pandas", "numpy", "dataframe" ]
Reversing 'one-hot' encoding in Pandas
38,334,296
<p><strong>Problem statement</strong> I want to go from this data frame which is basically one hot encoded. </p> <pre><code> In [2]: pd.DataFrame({"monkey":[0,1,0],"rabbit":[1,0,0],"fox":[0,0,1]}) Out[2]: fox monkey rabbit 0 0 0 1 1 0 1 0 2 1 0 0 ...
3
2016-07-12T16:23:02Z
38,334,689
<p>I would use apply to decode the columns:</p> <pre><code>In [2]: animals = pd.DataFrame({"monkey":[0,1,0,0,0],"rabbit":[1,0,0,0,0],"fox":[0,0,1,0,0]}) In [3]: def get_animal(row): ...: for c in animals.columns: ...: if row[c]==1: ...: return c In [4]: animals.apply(get_animal, axis...
2
2016-07-12T16:42:16Z
[ "python", "pandas", "numpy", "dataframe" ]
Reversing 'one-hot' encoding in Pandas
38,334,296
<p><strong>Problem statement</strong> I want to go from this data frame which is basically one hot encoded. </p> <pre><code> In [2]: pd.DataFrame({"monkey":[0,1,0],"rabbit":[1,0,0],"fox":[0,0,1]}) Out[2]: fox monkey rabbit 0 0 0 1 1 0 1 0 2 1 0 0 ...
3
2016-07-12T16:23:02Z
38,334,801
<p>Try this: </p> <pre><code>df = pd.DataFrame({"monkey":[0,1,0,1,0],"rabbit":[1,0,0,0,0],"fox":[0,0,1,0,0], "cat":[0,0,0,0,1]}) df cat fox monkey rabbit 0 0 0 0 1 1 0 0 1 0 2 0 1 0 0 3 0 0 1 0 4 1 0 0 0 pd.DataFrame([x ...
2
2016-07-12T16:48:45Z
[ "python", "pandas", "numpy", "dataframe" ]
Inheritance best practice to share code when method parameters are different?
38,334,374
<p>I have a <code>AWS Redshift</code> wrapper class that automates similar types of loads from <code>S3</code> for me, and I have recently adapted it to work for <code>Spark</code> jobs, which don't require a manifest, and instead need a slightly different <code>COPY</code> statement. Other than this one method, all o...
2
2016-07-12T16:26:38Z
38,335,259
<p>Define <code>RedshiftLoader._copy_to_db</code> as:</p> <pre><code>def _copy_to_db(self, database_credentials, copy_from, manifest): """ Copies data from a file on S3 to a Redshift table. Data must be properly formatted and in the right order, etc... :param database_credentials: A d...
1
2016-07-12T17:17:19Z
[ "python", "oop", "inheritance" ]
Site made with mod_wsgi-express takes too long to respond
38,334,503
<p>I made a Web API using flask and I'm deploying it using mod_wsgi-express. I'm having a trouble where I can connect very easily to the website if I'm connected to the same server. However, when I try to connect to the website from outside. The site takes too long to respond and nothing is mentioned in the error log f...
1
2016-07-12T16:33:02Z
38,377,001
<p>I checked port 8000 using a port knocking website such as this one <a href="http://www.canyouseeme.org/" rel="nofollow">http://www.canyouseeme.org/</a></p> <p>I found out that the port was closed. The only open port was port 80 and 22. The server I'm working on apparently has a firewall that I do not have access to...
0
2016-07-14T14:31:56Z
[ "python", "apache", "ubuntu", "mod-wsgi", "iptables" ]
OpenOPC Gateway Running use Client in OsX or Linux
38,334,505
<p>I use the <code>OpenOPC</code> library for <code>python</code> <a href="https://sourceforge.net/projects/openopc/" rel="nofollow">https://sourceforge.net/projects/openopc/</a> in gateway mode... Gateway runs on Windows and the client should run on <code>Linux</code>.</p> <p>This usecase is also forseen by the Libra...
1
2016-07-12T16:33:13Z
38,336,447
<p>The problem is fixed... It was just a programming mistake:</p> <p>I ran:</p> <pre><code> opc.client('ipaddress') </code></pre> <p>but in to use the gateway service it has to be:</p> <pre><code>opc.open_client('ipaddress') </code></pre>
0
2016-07-12T18:30:09Z
[ "python", "opc" ]
Why it happens - RelatedObjectDoesNotExist error caused by Model.clean()?
38,334,545
<p>I have a clean method that gives me RelatedObjectDoesNotExist error in my model file </p> <pre><code>@with_author class BOMVersion(models.Model): version = IntegerVersionField( ) name = models.CharField(max_length=200,null=True, blank=True) description = models.TextField(null=True, blank=True) ma...
0
2016-07-12T16:34:39Z
38,341,640
<p>When you call <code>is_valid()</code> on the form it's calling the model's clean method. Since you're only assigning material after calling <code>is_valid()</code>, when <code>self.material</code> is called, <code>self.material</code> is not associated with any <code>Material</code>object.</p> <p>Instead of checkin...
0
2016-07-13T02:20:31Z
[ "python", "django" ]
Retrieve environment variables from popen
38,334,564
<p>I am working on converting an older system of batch files to python. I have encountered a batch file that sets the environment variables for the batch file that called it. Those values are then used again in future calls to batch files. My environment variables seem to go down the flow of calls but I am unable to br...
1
2016-07-12T16:36:17Z
38,338,451
<p>It's generally not possible for a child process to set parent environment variables, unless you want to go down a mildly evil path of creating a remote thread in the parent process and using that thread to set variables on your behalf.</p> <p>It's much easier to have the python script write a temp file that contain...
1
2016-07-12T20:35:47Z
[ "python", "windows", "python-3.x", "batch-file", "popen" ]
(Python) How to get full frame in openCV and convert it to string?
38,334,584
<p>I try to send frame-data from webcamera trough websocket, but frames looks like similar to this:</p> <pre><code>[[1 2 3] [3 2 1] [2 3 4] ... [2 3 4] [2 2 2] [1 1 1]] </code></pre> <p>This is numpy matrix. How get full frame without this three dots?</p>
1
2016-07-12T16:36:55Z
38,334,795
<pre><code>import numpy as np np.set_printoptions(threshold='nan') </code></pre>
0
2016-07-12T16:48:33Z
[ "python", "opencv", "numpy" ]
(Python) How to get full frame in openCV and convert it to string?
38,334,584
<p>I try to send frame-data from webcamera trough websocket, but frames looks like similar to this:</p> <pre><code>[[1 2 3] [3 2 1] [2 3 4] ... [2 3 4] [2 2 2] [1 1 1]] </code></pre> <p>This is numpy matrix. How get full frame without this three dots?</p>
1
2016-07-12T16:36:55Z
38,334,809
<p>Okay, so the solution to this lies in how numpy arrays are formatted and printed. Before printing the image array, all you have to do is:</p> <pre><code>import numpy as np np.set_printoptions(threshold=np.inf) </code></pre> <p>and then simply do the following</p> <pre><code>print img </code></pre>
0
2016-07-12T16:49:23Z
[ "python", "opencv", "numpy" ]
Kaitai Struct: calculated instances with a condition
38,334,665
<p>I'm trying to get Kaitai Struct to reverse engineer a binary structure. <code>seq</code> fields work as intended, but <code>instances</code> don't seem to work as I want them to.</p> <p>My binary format includes a header with a list of constants that I parse as <code>header</code> field with <code>consts</code> arr...
4
2016-07-12T16:41:07Z
38,349,896
<p>Yeah, I guess it should be considered a bug. At the very least, compiler should either allow to use <code>if</code> in value instances and process it properly, or disallow <code>if</code> and issue an error message.</p> <p>Thinking of it, I see no reason why <code>if</code> is allowed for regular <code>instances</c...
1
2016-07-13T11:05:31Z
[ "python", "data-structures", "reverse-engineering", "kaitai-struct" ]
Python/BeautifulSoup with JavaScript source
38,334,715
<p>First of all, I am new to Python and BeautifulSoup. So forgive me if I am using the wrong terminology.</p> <p>I am encountering an issue where when I inspect the element, I was able to find it, but when I go to 'view source', it wasn't there, and it seems that data was pulled via javascript and thus it may be dynam...
1
2016-07-12T16:43:42Z
38,338,730
<p>You can do it all without selenium, once you visit each apartment url the data is retrieved from an ajax call to an api, all we need is the <em>city-id</em>:</p> <pre><code>from bs4 import BeautifulSoup from urllib.parse import urljoin root = "http://www.homestead.ca" data = {'keyword': 'false', 'max_bed': '100',...
0
2016-07-12T20:55:51Z
[ "javascript", "python", "beautifulsoup" ]
Python - Updating dictionary values after a .count() function while iterating
38,334,791
<p>I'm having a problem with counting letters in a string and then updating this value to a dictionary.</p> <p>I am iterating through a dictionary of alphabet letters and using the .count() function at each pair to compare to a sentence. The count is working and returns the number you would expect (in this case xval),...
1
2016-07-12T16:48:18Z
38,334,929
<p>You are printing <code>k</code> and <code>v</code> which do not reflect the updated dictionary. </p> <pre><code>import string type = ("cat sat on the mat").lower() dic = dict.fromkeys(string.ascii_lowercase, 0) print(dic) for k in dic: xval = type.count(k) print(xval) dic[k] = xval print k, ":",...
1
2016-07-12T16:57:19Z
[ "python", "dictionary", "count", "updates" ]
Rolling averages on groups
38,334,832
<p>I've got a Series of the form:</p> <pre><code>Contract Date 196012 1960-01-05 110.70 1960-01-07 110.70 1960-01-08 110.40 1960-01-11 110.00 1960-01-12 109.60 1960-01-13 109.70 1960-01-14 109.50 1960-01-15 109.60 ...
3
2016-07-12T16:51:25Z
38,335,063
<p>You want to <code>groupby(level=0)</code> then <code>rolling(n).mean()</code></p> <pre><code>s.groupby(level=0).rolling(10).mean() </code></pre>
3
2016-07-12T17:04:39Z
[ "python", "pandas" ]
Rolling averages on groups
38,334,832
<p>I've got a Series of the form:</p> <pre><code>Contract Date 196012 1960-01-05 110.70 1960-01-07 110.70 1960-01-08 110.40 1960-01-11 110.00 1960-01-12 109.60 1960-01-13 109.70 1960-01-14 109.50 1960-01-15 109.60 ...
3
2016-07-12T16:51:25Z
38,335,372
<p>If you want the rolling mean to be a new column in the same dataframe:</p> <p><code>df['rolling_mean'] = df.groupby(level=0).rolling(window_size).mean().values</code></p>
1
2016-07-12T17:24:59Z
[ "python", "pandas" ]
Python dataframe check if a value in a column dataframe is within a range of values reported in another dataframe
38,334,845
<p>Apology if the problemis trivial but as a python newby I wasn't able to find the right solution.</p> <p>I have two dataframes and I need to add a column to the first dataframe that is true if a certain value of the first dataframe is between two values of the second dataframe otherwise false.</p> <p>for example:</...
1
2016-07-12T16:52:31Z
38,334,982
<pre><code>first_df['output'] = (second_df.code2_start &lt;= first_df.code2) &amp; (second_df.code2_end &lt;= first_df.code2) </code></pre> <p>This works because when you do something like: <code>second_df.code2_start &lt;= first_df.code2</code></p> <p>You get a boolean Series. If you then perform a logical AND on t...
0
2016-07-12T16:59:54Z
[ "python", "function", "dataframe", "multiple-columns", "matching" ]
Having trouble pausing animation with code based on example
38,334,877
<p>I want to animate some data, and I have been following the example from another stack question <a href="http://stackoverflow.com/questions/16732379/stop-start-pause-in-python-matplotlib-animation">here</a> to enable pausing. However, I am doing something a little different. In that example, they are using the sine f...
2
2016-07-12T16:54:35Z
38,335,174
<p>The argument passed to <code>animate</code> is a frame number. However, this number increments whether or not the animation is paused.</p> <p>So instead, introduce your own global variable, <code>frame</code>, which records the true frame number and which only increments when the animation is not paused:</p> <pre>...
1
2016-07-12T17:11:42Z
[ "python", "animation", "matplotlib", "event-handling" ]
Is there a way to force a Python program to run in version 2.7?
38,334,883
<h2>Background</h2> <p>I have some Python scripts which use libraries only available to Python 2.7 and so I want to be able to run those in Python version 2.7.</p> <p>I was thinking that it would be great if I could put some code at the top of my Python file which would detect if it was being run in Python 3 and if s...
2
2016-07-12T16:54:52Z
38,334,914
<p>Nope, this isn't possible for the simple reason that a user could have python3.x installed and not have python2.x installed.</p> <p>If you <em>know</em> that they have python2.7 installed, then you can use something like your work-around above, however, in that case, you'll have to make sure that you can support bo...
3
2016-07-12T16:56:36Z
[ "python", "python-2.7", "python-3.x" ]
Is there a way to force a Python program to run in version 2.7?
38,334,883
<h2>Background</h2> <p>I have some Python scripts which use libraries only available to Python 2.7 and so I want to be able to run those in Python version 2.7.</p> <p>I was thinking that it would be great if I could put some code at the top of my Python file which would detect if it was being run in Python 3 and if s...
2
2016-07-12T16:54:52Z
38,334,934
<p>You can try adding the python2.7 shebang line at the top of your script:</p> <pre><code>#!/usr/bin/env python2.7 </code></pre> <p>Make sure it is in your path though, and this should work.</p>
3
2016-07-12T16:57:41Z
[ "python", "python-2.7", "python-3.x" ]
Is there a way to force a Python program to run in version 2.7?
38,334,883
<h2>Background</h2> <p>I have some Python scripts which use libraries only available to Python 2.7 and so I want to be able to run those in Python version 2.7.</p> <p>I was thinking that it would be great if I could put some code at the top of my Python file which would detect if it was being run in Python 3 and if s...
2
2016-07-12T16:54:52Z
38,334,947
<p>I would advise against this for reasons raised by mgilson. However you can check the python version with:</p> <pre><code>import sys sys.version_info[0] </code></pre> <p>In case you still want to do this.</p>
0
2016-07-12T16:58:32Z
[ "python", "python-2.7", "python-3.x" ]
Is there a way to force a Python program to run in version 2.7?
38,334,883
<h2>Background</h2> <p>I have some Python scripts which use libraries only available to Python 2.7 and so I want to be able to run those in Python version 2.7.</p> <p>I was thinking that it would be great if I could put some code at the top of my Python file which would detect if it was being run in Python 3 and if s...
2
2016-07-12T16:54:52Z
38,338,484
<p>If you are on Linux(not sure about other OS'), when running the python script with .py at the end obviously. You can change the symbolic link of the .py from 2.x to 3.x or whatever(so when you use .py it will use the version you want). So as root:</p> <pre><code>ln -sf /bin/*wherever python 3.x is stored* /bin/*wh...
0
2016-07-12T20:38:07Z
[ "python", "python-2.7", "python-3.x" ]
Python: Check if a key in a dictionary is contained in a string
38,334,937
<p>Assuming I've a dictionary,</p> <pre><code>mydict = { "short bread": "bread", "black bread": "bread", "banana cake": "cake", "wheat bread": "bread" } </code></pre> <p>Given the string <code>"wheat bread breakfast today"</code> I want to check if any key in my dictionary is conta...
2
2016-07-12T16:57:52Z
38,334,997
<p>Just loop through the keys and check each one.</p> <pre><code>for key in mydict: if key in mystring: print(mydict[key]) </code></pre> <p>If you want to do it in a list comprehension, just check the key on each iteration.</p> <pre><code>[val for key,val in mydict.items() if key in mystring] </code></p...
5
2016-07-12T17:00:43Z
[ "python", "list", "dictionary" ]
Python: Check if a key in a dictionary is contained in a string
38,334,937
<p>Assuming I've a dictionary,</p> <pre><code>mydict = { "short bread": "bread", "black bread": "bread", "banana cake": "cake", "wheat bread": "bread" } </code></pre> <p>Given the string <code>"wheat bread breakfast today"</code> I want to check if any key in my dictionary is conta...
2
2016-07-12T16:57:52Z
38,335,003
<pre><code>mydict = { "short bread": "bread", "black bread": "bread", "banana cake": "cake", "wheat bread": "bread" } s = "wheat bread breakfast today" for key in mydict: if key in s: print mydict[key] </code></pre>
1
2016-07-12T17:01:06Z
[ "python", "list", "dictionary" ]
Adding multiple fields to Django Model Admin readonly fields dynamically
38,334,958
<p>I have a use case where I need to retrieve status information for each row in the Django model admin list view. </p> <p>I can retrieve data using code like:</p> <pre><code>def blah(admin.ModelAdmin): @staticmethod def status(instance): return Blah(instance).get_info()['status'] readonly_fields ...
2
2016-07-12T16:58:48Z
38,335,653
<p>I think you may use a class decorator.</p> <pre><code>def get_blah_info(field): return staticmethod(lambda x: Blah(x).get_info()[field]) def blah_decorator(*fields): def wrapper(cls): for field in fields: setattr(cls, field, get_blah_info(field)) cls.readonly_fields.append(f...
1
2016-07-12T17:40:09Z
[ "python", "django", "django-admin" ]
How to drop rows in an H2OFrame?
38,335,068
<p>I've worked in the h2o R package for quite a while, now, but have recently had to move to the python package.</p> <p>For the most part, an <code>H2OFrame</code> is designed to work like a pandas <code>DataFrame</code> object. However, there are several hurdles I haven't managed to get over... in Pandas, if I want t...
1
2016-07-12T17:05:08Z
38,341,393
<p>Currently, the <code>H2OFrame.drop</code> method does not support this, but we have added a <a href="https://0xdata.atlassian.net/browse/PUBDEV-3132" rel="nofollow">ticket</a> to add support for dropping multiple rows (and multiple columns).</p> <p>In the meantime, you can subset rows by an index:</p> <pre><code>i...
2
2016-07-13T01:46:34Z
[ "python", "h2o" ]
Apply a function to the 0-dimension of an ndarray
38,335,116
<h2>Problem</h2> <ul> <li><p>I have an <code>ndarray</code>, defined by <code>arr</code> that is an <code>n</code>-dimensional cube with length <code>m</code> in each dimension.</p></li> <li><p>I want to act a function, <code>func</code>, by slicing along the dimension <code>n=0</code> and taking each <code>n-1</code>...
4
2016-07-12T17:08:20Z
38,336,598
<p>Given that <code>arr</code> is 4d, and your <code>fn</code> works on 3d arrays, </p> <pre><code>np.asarray(map(func, arr)) </code></pre> <p>looks perfectly reasonable. I'd use the list comprehension form, but that's a matter of programming style</p> <pre><code>np.asarray([func(i) for i in arr]) </code></pre> <p...
1
2016-07-12T18:41:19Z
[ "python", "function", "numpy", "multidimensional-array", "vectorization" ]
Sleep in tkinter (python2)
38,335,168
<p>I search to make a sleep in a while loop, in an tkinter's canvas. In Python2 The aim is to have a randomly moving point, refreshed every X seconds (then .I'll be able a bigger script to make what I want precisely), without any external user input.</p> <p>For now, I made this :</p> <pre><code>import Tkinter, time ...
0
2016-07-12T17:11:31Z
38,335,326
<p><code>sleep</code> does not mix well with Tkinter because it makes the event loop halt, which in turn makes the window lock up and become unresponsive to user input. The usual way to make something happen every X seconds is to put the <code>after</code> call inside the very function you're passing to <code>after</co...
1
2016-07-12T17:21:55Z
[ "python", "tkinter" ]
Is there a way to modify the python code for inception-v3 in TensorFlow?
38,335,169
<p>Right now I'm using inception-v3 based on the tutorial provided by google. TO retrain and test it I use the command:</p> <pre><code>bazel build tensorflow/examples/label_image:label_image &amp;&amp; \ bazel-bin/tensorflow/examples/label_image/label_image \ --graph=/tmp/output_graph.pb --labels=/tmp/output_labels.tx...
0
2016-07-12T17:11:31Z
38,338,733
<p>That model is unfortunately written in C++.</p> <p>But there's a very nice inception implementation in the <code>tensorflow/models</code> repo here: <a href="https://github.com/tensorflow/models/tree/master/inception" rel="nofollow">https://github.com/tensorflow/models/tree/master/inception</a></p> <p>It also incl...
0
2016-07-12T20:55:57Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
spyne - How to get a wrapping element surrounding a complex type
38,335,189
<p>I want to recreate the following wsdl type definition</p> <pre><code>&lt;!-- Existent non spyne specification --&gt; &lt;s:element name="GetVehiclesResponse"&gt; &lt;s:complexType&gt; &lt;s:sequence&gt; &lt;s:element minOccurs="0" maxOccurs="1" ref="s1:vehiclesResponse"/&gt; &lt;s:elemen...
0
2016-07-12T17:13:04Z
38,348,259
<p>The two notations are equivalent.</p>
0
2016-07-13T09:52:42Z
[ "python", "xml", "spyne" ]
More efficient and general way to prepend text before lines of a file?
38,335,209
<p>I am new to python. In one of task I have to add a character before specific lines.For example, in my text file the</p> <blockquote> <p>Name</p> </blockquote> <p>and </p> <blockquote> <p>Surname</p> </blockquote> <p>are the fixed lines on which I have to either add or delete <code>;</code> based on flag</p>...
0
2016-07-12T17:14:32Z
38,338,981
<p>I poked at it a lot, and borrowed martineau's ideas, and ended up with this:</p> <pre><code>def change_file(filepath, add_comment, trigger_words): def process(line): line_word = line.lstrip(';').split(':')[0] if line_word in trigger_words: if add_comment: line = lin...
0
2016-07-12T21:13:37Z
[ "python", "file", "parsing" ]
Create a relative grid of points from absolute points in an image
38,335,249
<p>Example Target:<br> <a href="http://i.stack.imgur.com/jsfR5.png" rel="nofollow"><img src="http://i.stack.imgur.com/jsfR5.png" alt="enter image description here"></a><br> Source: zone.ni.com</p> <p>From a calibration target like the image above, I have found the center of each circle on the target. I have the center...
1
2016-07-12T17:16:45Z
38,335,703
<p>are you using openCV? in any case the topic you might want to look into is <a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/warp_affine/warp_affine.html" rel="nofollow">Affine Transforms</a> Although the link is python OpenCv specific, the topic itself is not. </p> <p>You can actually complete the...
1
2016-07-12T17:43:37Z
[ "python", "image-processing", "camera-calibration" ]
Python Selenium not loading full page source
38,335,292
<p>The source code from the Selenium web page appears to be incomplete.</p> <pre><code>driver = webdriver.Chrome() driver.get('https://www.youtube2mp3.cc/') vid_name = driver.find_element_by_id('input') vid_name.send_keys('https://www.youtube.com/watch?v=NVbH1BVXywY') driver.find_element_by_id('button').click() el...
2
2016-07-12T17:19:54Z
38,335,495
<p>Have the <code>WebDriverWait</code> wait until the download button has a <code>href</code></p> <pre><code>element = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.XPATH, './/a[@id="download" and @href!=""]')) ) </code></pre>
0
2016-07-12T17:31:05Z
[ "python", "selenium", "web" ]
Python Selenium not loading full page source
38,335,292
<p>The source code from the Selenium web page appears to be incomplete.</p> <pre><code>driver = webdriver.Chrome() driver.get('https://www.youtube2mp3.cc/') vid_name = driver.find_element_by_id('input') vid_name.send_keys('https://www.youtube.com/watch?v=NVbH1BVXywY') driver.find_element_by_id('button').click() el...
2
2016-07-12T17:19:54Z
38,337,334
<pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://www.youtube2mp3.cc/") try: element = WebDriverWait(driver, 1...
0
2016-07-12T19:24:58Z
[ "python", "selenium", "web" ]
How to pass selected parameters to a python constructor
38,335,359
<p>I have an initializer like this:</p> <pre><code>def __init__(self, options=None, rinse=True, algorithm="foo"): if options is not None: self.options = options else: self.create_default() if (rinse==False): #would mean rinse parameter was passed self.options.rinse = rinse if (algorithm...
-4
2016-07-12T17:24:25Z
38,335,468
<p>If you're willing to change your examples to use equals signs instead of colons, your <code>__init__</code> should work fine as-is:</p> <pre><code>a = MyClass() #nothing was passed a = MyClass(rinse= False) #only rinse parameter was passed a = MyClass(algorithm= "bar") #only algorithm parameter was passed a = MyCla...
1
2016-07-12T17:29:21Z
[ "python", "constructor" ]
Beautiul Soup returning strange characters (chinesse)
38,335,378
<p>Using Python3 and BeautifulSoup v4</p> <pre><code>url='http://www.eurobasket2015.org/en/compID_qMRZdYCZI6EoANOrUf9le2.season_2015.roundID_9322.gameID_9323-C-1-1.html' r=requests.get(url) soup = BeautifulSoup(r.content, "html.parser") </code></pre> <p>returns what you would expect</p> <p>however </p> <p>for this ...
1
2016-07-12T17:25:08Z
38,338,352
<p>I can replicate using <code>.content</code>, why it is happening is because of the following meta tag, the charset is set to <code>UTF-16</code>:</p> <pre><code>&lt;META http-equiv="Content-Type" content="text/html; charset=UTF-16"&gt; </code></pre> <p>A workaround is to specify the <em>from_encoding</em> as <em>u...
2
2016-07-12T20:29:59Z
[ "python", "beautifulsoup" ]
Scrapy error: TypeError: __init__() got an unexpected keyword argument 'callback'
38,335,472
<p>I'm trying to scrape a website by extracting all links with "huis" (="house" in Dutch) in them. Following <a href="http://doc.scrapy.org/en/latest/topics/spiders.html" rel="nofollow">http://doc.scrapy.org/en/latest/topics/spiders.html</a>, I'm trying</p> <pre><code>import scrapy from scrapy.spiders import CrawlSpid...
0
2016-07-12T17:29:39Z
38,335,565
<p>Yes, <code>callback</code> is definitely being passed to <code>LinkExtractor</code>. That seems to be the problem, actually, because I don't see <code>callback</code> under the expected parameters for that class in <a href="http://doc.scrapy.org/en/latest/topics/link-extractors.html" rel="nofollow">the documentation...
3
2016-07-12T17:35:35Z
[ "python", "scrapy" ]
py.test : Can multiple markers be applied at the test function level?
38,335,589
<p>I have seen from <a href="http://pytest.org/latest/example/markers.html" rel="nofollow">the pytest docs</a> that we can apply multiple markers at once on the Class or module level. I didn't find documentation for doing it at the test function level. Has anybody done this before with success? </p> <p>I would like t...
1
2016-07-12T17:36:37Z
38,336,381
<p>Haven't tried this myself. However, from a quick look at <a href="https://github.com/pytest-dev/pytest/blob/master/_pytest/mark.py#L205" rel="nofollow">the source</a>, I think class <code>MarkDecorator</code> is what you want. Try:</p> <pre><code>mark_names=["marker1", "marker2", "marker3"] my_marks = pytest.Mark...
1
2016-07-12T18:26:01Z
[ "python", "py.test", "markers" ]
Efficient way to try retrieving data based on set date, and if it doesn't work, shift 1 day earlier
38,335,594
<p>I have a csv file of S&amp;P 500 holdings as of the end of each year for 15 years (i.e. 12/31/1999-12/31/2015). Therefore, the dataframe has 15 columns of holdings. I am trying to write a code that will loop through each column of holdings, take those holdings and gather the price data at multiple points (i.e. curre...
0
2016-07-12T17:36:52Z
38,337,189
<p>Pandas has a business-day index (excludes weekends) <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/timeseries.html</a></p> <pre><code>pd.bdate_range(start, end) </code></pre> <p>You can generate business-days like the example below:<...
0
2016-07-12T19:16:25Z
[ "python", "pandas", "yahoo-finance" ]
Too many indices error coming up in Python
38,335,598
<p>This is my first bash at using python, I am making an array of fathers and children, I have a dataset in a .csv file which I need to go into python so I can later take it over to java script. However the same error message keeps coming which I have put below. Further down is my script. Would be most grateful for any...
0
2016-07-12T17:36:55Z
38,336,728
<p>The too many indices error indicates that input_2d_array is not a two 2d array. genfromtxt() is not returning what you are expecting.</p> <p><a href="http://stackoverflow.com/questions/9534408/numpy-genfromtxt-produces-array-of-what-looks-like-tuples-not-a-2d-array-why">numpy.genfromtxt produces array of what looks...
0
2016-07-12T18:48:35Z
[ "python", "arrays", "numpy", "error-handling" ]
Retrieving json response data and scraping from website with Python
38,335,606
<p>I have a Python script that currently runs as a scheduled task once a week on a server. It essentially fills out a web form (I only fill out the County field), downloads an excel file using Python's <a href="https://pypi.python.org/pypi/selenium" rel="nofollow">selenium</a> module, and geocodes the locations from <...
0
2016-07-12T17:37:28Z
38,372,884
<p>You can use csv writer library of python as I'm mentioning with example.</p> <p>This will give you basic idea of what you should be doing to scrap data(from url, as well as json source). Customize this code with your code and you will have a working solution.</p> <p>The main Problem was with selenium. You can just...
0
2016-07-14T11:23:40Z
[ "python", "python-2.7", "web-scraping" ]
Regex - matching a substring of text to a substring of a pattern
38,335,634
<p>So I'm in a counter-intuitive situation, and I wanted to get some advice. Mostly I'm just doing some string matching, using extracted string as the patterns for my regular expression. While generally I can do this pretty well overall with a fuzzy regex search, on occasion I run into this situation:</p> <p>Let's say...
1
2016-07-12T17:38:55Z
38,338,224
<p>Ouf, took me quite some time to come with this (I'm not a python developer), but this should do the trick:</p> <pre><code>import re sentence = "the quick brown fox jumps over the lazy dog" string = 'quick brown fox jumps over the lazy' string2 = 'and then a quick brown fox jumps onto the cat' count1 = 0 count2 = 0...
0
2016-07-12T20:21:10Z
[ "python", "regex", "string-matching", "fuzzy-search" ]
Accessing data in a Compose PostgreSQL database from Spark as a Service Python notebook on Bluemix
38,335,685
<p>I have data in a postgres database that I am trying to access through Spark as a Service on IBM Bluemix (using a python notebook). Here is my code:</p> <pre><code>from pyspark.sql import SQLContext sqlContext = SQLContext(sc) df = sqlContext.load(source="jdbc",\ url="jdbc:postgresql://[publichost...
0
2016-07-12T17:42:42Z
38,600,751
<p>This happens because the postgresql driver is not installed by default in your spark service instance.</p> <p>You would need to add it first to use it.</p> <pre><code>Change the kernel to Scala from the menu to execute below statement, you only need to execute this once per spark instance and then subsequent use p...
1
2016-07-26T22:14:53Z
[ "python", "postgresql", "ibm-bluemix", "pyspark", "compose" ]
What is the issue with displaying data in this code?
38,335,751
<pre><code>class s(object): def vrod(self): self.name=(input("enter name:")) self.stno=int(input("enter stno:")) self.score=int(input("enter score:")) def dis(self): j=0 while j&lt;3: print("enter name:",self.name,"enter stno:",self.stno,"enter score:",self.s...
-4
2016-07-12T17:46:21Z
38,335,993
<p>There are a couple of issues that need to be addressed:</p> <ol> <li>The <code>st</code> object is created once and then used multiple times in the while loop. This calls the same method of the same object multiple times, so the previous information is lost.</li> <li>The <code>st</code> object is being appended to ...
0
2016-07-12T18:01:41Z
[ "python" ]
cairo/pycairo drawing arcs issue: PI/2 does not draw what expected
38,335,783
<p>I tried to find similar issues, tutorials about drawing arcs and circles and found nothing helpful for this question.</p> <p>I'm playing with cairo and pycairo trying to draw a circle with quadrants.</p> <p>I'm not sure if I'm getting lost in any point, but what I expect to draw, well, is not what I'm drawing at a...
0
2016-07-12T17:48:05Z
38,343,445
<p>I found a solution by myself, but I don't catch why the behavior is not exactly the same for every radian length.</p> <p>If you issue a move_to:</p> <pre><code>ctx.move_to(600,600) </code></pre> <p>Now it renders perfectly. So thanks to all anyway.</p>
0
2016-07-13T05:40:43Z
[ "python", "drawing", "cairo", "pycairo" ]
Best way to share data between node.js and django?
38,335,811
<p>I have a variable in django settings.(eg settings.ALLOW_REDIRECT). I am running some tests (django and node.js tests) and the value of settings.ALLOW_REDIRECT would be changed after some tests.</p> <p>What is the best way to let the node.js tests to access the value of the variable. I thought of using a conf file ...
0
2016-07-12T17:49:56Z
38,336,054
<p>You can pass the value of <code>settings.ALLOW_REDIRECT</code> into your template render call:</p> <pre><code>def myview(request): ... return render(request, 'mytemplate.html', {'allow_redirect': settings.ALLOW_REDIRECT}) </code></pre> <p>And then the template can check the value of <code>allow_redirect</c...
0
2016-07-12T18:05:52Z
[ "javascript", "python", "node.js", "django" ]