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
Run a function for a duration of 5 secs exactly every time using time.time() in python
37,754,054
<p>I have defined a function record which appends value to a list named as lists for a duration of Time.Whenever I call this function for the first time it appends 19 values to lists,but when I call it second time it appends 20 values to lists even though the time parameter that I was using both the times was 1 sec.Is ...
-1
2016-06-10T17:29:28Z
37,754,745
<p>the number of times the list gets appended is almost arbitrary, the exact time it takes to execute is mostly affected by what happens to be running on your computer at the time. For example if you opened your internet browser during the second call that could slow down the exact execution time.</p> <p>On my machin...
0
2016-06-10T18:12:04Z
[ "python", "list", "function", "time", "duration" ]
Run a function for a duration of 5 secs exactly every time using time.time() in python
37,754,054
<p>I have defined a function record which appends value to a list named as lists for a duration of Time.Whenever I call this function for the first time it appends 19 values to lists,but when I call it second time it appends 20 values to lists even though the time parameter that I was using both the times was 1 sec.Is ...
-1
2016-06-10T17:29:28Z
37,755,347
<p>The time it takes to do something is not fixed. It takes as long as it takes. But you need both to be the same, so just make them the same by checking both. This code does the desired amount of work, and then calls time.sleep() until the remaining time block runs out. That's way better than looping and checking ...
0
2016-06-10T18:52:50Z
[ "python", "list", "function", "time", "duration" ]
Python Flask - Processing input obtained from front-end in the back-end
37,754,079
<p>this is more of a question about where to find how I would do this rather than asking how to do this. I'm sure this is well covered, I'm just struggling to articulate the correct term which I could use to Google and find out the answer.</p> <p>Anyway - I have a Python Flask web application. On a web page, there is ...
1
2016-06-10T17:31:09Z
37,756,226
<p>Elsewhere in your code base, either in the same file, or more likely a module or package you could define that complicated task. Lets create a simple module <code>complicated.py</code> in the same directory as your other code, that then defines the complicated task:</p> <pre><code>def do_really_complicated_thing(in...
0
2016-06-10T19:56:33Z
[ "python", "flask", "backend" ]
How to "render" HTML with PyQt5's QWebEngineView
37,754,138
<p>How can I "render" HTML with with PyQt5 v5.6 QWebEngineView?</p> <p>I have previously performed the task with PyQt5 v5.4.1 QWebPage, but it was <a href="http://stackoverflow.com/q/37711921/4117209">suggested </a> to try the newer QWebEngineView.</p> <p>Here's that implementation (it generally works as expected, bu...
1
2016-06-10T17:34:45Z
37,755,811
<p>Quite a bit of discussion on the topic was made in the following thread: <a href="https://riverbankcomputing.com/pipermail/pyqt/2015-January/035324.html" rel="nofollow">https://riverbankcomputing.com/pipermail/pyqt/2015-January/035324.html</a></p> <p>The new QWebEngine interface takes account of the fact that the u...
3
2016-06-10T19:25:55Z
[ "python", "pyqt", "pyqt5" ]
Python/Pandas create zip file from csv
37,754,165
<p>Is anyone can provide example how to create zip file from csv file using Python/Pandas package? Thank you</p>
0
2016-06-10T17:36:21Z
37,754,204
<p>Use </p> <pre><code>df.to_csv('my_file.gz', compression='gzip') </code></pre> <p>From the docs:</p> <blockquote> <p>compression : string, optional a string representing the compression to use in the output file, allowed values are ‘gzip’, ‘bz2’, ‘xz’, only used when the first argument is a filen...
1
2016-06-10T17:38:50Z
[ "python", "csv", "pandas", "zip", "compression" ]
Merge two (or more) identical dictionaries having just one value in common - in Python
37,754,247
<p>I have two (but it could be three or more) dictionaries like this</p> <pre><code>&gt;&gt;&gt; d1 {'address': '', 'cf': 'DRSSFN88A26A459E', 'first_name': 'Stefano', 'last_name': ''} &gt;&gt;&gt; d2 {'address': 'Via Due Giugno, 25', 'cf': 'DRSSFN88A26A459E', 'first_name': '', 'last_name': ''} &gt;&gt;&gt; d3 {'addres...
-1
2016-06-10T17:41:17Z
37,754,369
<p>Just use dictionary comprehension:</p> <pre><code>&gt;&gt;&gt; d = {i:v for q in [d1,d2,d3] for i,v in q.iteritems() if v != ''} &gt;&gt;&gt; d {'first_name': 'Stefano', 'last_name': 'Lauzi', 'cf': 'DRSSFN88A26A459E', 'address': 'Via Due Giugno, 25'} </code></pre> <p>Of course, this won't work if you have differen...
3
2016-06-10T17:48:30Z
[ "python", "dictionary" ]
Merge two (or more) identical dictionaries having just one value in common - in Python
37,754,247
<p>I have two (but it could be three or more) dictionaries like this</p> <pre><code>&gt;&gt;&gt; d1 {'address': '', 'cf': 'DRSSFN88A26A459E', 'first_name': 'Stefano', 'last_name': ''} &gt;&gt;&gt; d2 {'address': 'Via Due Giugno, 25', 'cf': 'DRSSFN88A26A459E', 'first_name': '', 'last_name': ''} &gt;&gt;&gt; d3 {'addres...
-1
2016-06-10T17:41:17Z
37,754,564
<p><code>dict.update</code> updates every key, even if the value was empty.</p> <pre><code>&gt;&gt;&gt; d = {'a':'hi'} &gt;&gt;&gt; d.update({'a':'', 'b':'hello'}) &gt;&gt;&gt; d {'a': '', 'b': 'hello'} </code></pre> <p>you could easily discriminate against empty values with comprehension:</p> <pre><code>def merge_t...
1
2016-06-10T18:01:09Z
[ "python", "dictionary" ]
Python 2.7 3d plotting
37,754,389
<p>I have referred to matplotlib.org and a lot of threads but I can't plot a 3d surface. I am able to plot a 3d scatter but as soon as I try to plot a 3d surface it breaks for a lot of different errors. I fix errors but I get new ones. After fighting with it for a 2 days I believe my understanding of matplotlib 3d surf...
2
2016-06-10T17:49:28Z
37,756,904
<p>Look at this example code for 3d surface: <a href="http://matplotlib.org/examples/mplot3d/surface3d_demo.html" rel="nofollow">http://matplotlib.org/examples/mplot3d/surface3d_demo.html</a></p> <p>First, you have to create two regular mesh grids X and Y (2d arrays) to plot with <code>plot_surface</code>, like here:<...
0
2016-06-10T20:44:26Z
[ "python", "matplotlib", "plot", "3d" ]
403 FORBIDDEN when delete file in django project
37,754,398
<p>Integrated the <a href="https://github.com/sigurdga/django-jquery-file-upload" rel="nofollow">django-jquery-file-upload</a> into my Django project. Upload and view list work now. but cannot delete the file.</p> <p><strong>Details:</strong></p> <p>The file is in /opt/data/myproject/uploads/picture</p> <p>Permissio...
0
2016-06-10T17:49:48Z
37,755,401
<p>I found the reason. My django project renamed the csrftoken, but in js files downloaded, "csrftoken" used. As a result, my program cannot find csrftoken. </p>
0
2016-06-10T18:56:47Z
[ "jquery", "python", "django" ]
TensorFlow: ValueError: setting an array element with a sequence doesn't work even though I'm using numpy arrays
37,754,446
<p>From what I understand, this error is caused by not using numpy arrays in tensorflow. I convert all of my lists to numpy arrays, but it doesn't work.</p> <p>Is the dimensionality wrong? How can I determine what's causing the error?</p> <p>The shapes and dtypes of the relevant arrays are:</p> <pre><code>Shapes and...
0
2016-06-10T17:54:06Z
37,754,851
<p>What's the shape and dtype of <code>fit</code> inputs. I'm wondering specifically about arrays like <code>traininginput</code>, <code>trainingoutput</code></p> <p>I can produce your error message with</p> <pre><code>In [2]: np.array([[1,2,3],[1,2],[]],dtype=float) -------------------------------------------------...
0
2016-06-10T18:19:16Z
[ "python", "arrays", "numpy", "tensorflow" ]
TensorFlow: ValueError: setting an array element with a sequence doesn't work even though I'm using numpy arrays
37,754,446
<p>From what I understand, this error is caused by not using numpy arrays in tensorflow. I convert all of my lists to numpy arrays, but it doesn't work.</p> <p>Is the dimensionality wrong? How can I determine what's causing the error?</p> <p>The shapes and dtypes of the relevant arrays are:</p> <pre><code>Shapes and...
0
2016-06-10T17:54:06Z
37,766,495
<p>It seems that you are feeding an array with inconsistent dimension. Thus the error that is raised. TensorFlow tries to convert you array to numpy array but fail, because inconsistent dimension arrays cannot be turned into numpy ndarray. So it may be an issue related to your data.</p> <p>See: <a href="http://stackov...
0
2016-06-11T17:15:30Z
[ "python", "arrays", "numpy", "tensorflow" ]
What is the most efficient way to create a DataFrame from two unrelated series?
37,754,449
<p>I'm looking at creating a Dataframe that is the combination of two unrelated series.</p> <p>If we take two dataframes: </p> <pre><code>A = ['a','b','c'] B = [1,2,3,4] dfA = pd.DataFrame(A) dfB = pd.DataFrame(B) </code></pre> <p>I'm looking for this output:</p> <pre><code> A B 0 a 1 1 a 2 2 a 3 3 ...
3
2016-06-10T17:54:11Z
37,754,544
<p>One liner approach</p> <pre><code>pd.DataFrame(0, A, B).stack().index.to_series().apply(pd.Series).reset_index(drop=True) </code></pre> <p>Or:</p> <pre><code>pd.MultiIndex.from_product([A, B]).to_series().apply(pd.Series).reset_index(drop=True) </code></pre> <p>From dataframes, assuming the information is in the...
1
2016-06-10T17:59:46Z
[ "python", "numpy", "pandas" ]
What is the most efficient way to create a DataFrame from two unrelated series?
37,754,449
<p>I'm looking at creating a Dataframe that is the combination of two unrelated series.</p> <p>If we take two dataframes: </p> <pre><code>A = ['a','b','c'] B = [1,2,3,4] dfA = pd.DataFrame(A) dfB = pd.DataFrame(B) </code></pre> <p>I'm looking for this output:</p> <pre><code> A B 0 a 1 1 a 2 2 a 3 3 ...
3
2016-06-10T17:54:11Z
37,754,794
<p>You can use <code>np.meshgrid</code>:</p> <pre><code>pd.DataFrame(np.array(np.meshgrid(dfA, dfB, )).T.reshape(-1, 2)) 0 1 0 a 1 1 a 2 2 a 3 3 a 4 4 b 1 5 b 2 6 b 3 7 b 4 8 c 1 9 c 2 10 c 3 11 c 4 </code></pre> <p>to get a roughly <code>~2000x</code> speedup on <code>DataFram...
3
2016-06-10T18:15:01Z
[ "python", "numpy", "pandas" ]
What is the most efficient way to create a DataFrame from two unrelated series?
37,754,449
<p>I'm looking at creating a Dataframe that is the combination of two unrelated series.</p> <p>If we take two dataframes: </p> <pre><code>A = ['a','b','c'] B = [1,2,3,4] dfA = pd.DataFrame(A) dfB = pd.DataFrame(B) </code></pre> <p>I'm looking for this output:</p> <pre><code> A B 0 a 1 1 a 2 2 a 3 3 ...
3
2016-06-10T17:54:11Z
37,754,871
<p>Alternatively</p> <pre><code>a = [1,2,3] b = ['a','b','c'] x,y = zip(*[i for i in zip(np.tile(a,len(a)),np.tile(b,len(a)))]) pd.DataFrame({'x':x,'y':y}) </code></pre> <p>Outputs:</p> <pre><code> x y 0 1 a 1 2 b 2 3 c 3 1 a 4 2 b 5 3 c 6 1 a 7 2 b 8 3 c %%timeit 1000 loops...
2
2016-06-10T18:20:28Z
[ "python", "numpy", "pandas" ]
What is the most efficient way to create a DataFrame from two unrelated series?
37,754,449
<p>I'm looking at creating a Dataframe that is the combination of two unrelated series.</p> <p>If we take two dataframes: </p> <pre><code>A = ['a','b','c'] B = [1,2,3,4] dfA = pd.DataFrame(A) dfB = pd.DataFrame(B) </code></pre> <p>I'm looking for this output:</p> <pre><code> A B 0 a 1 1 a 2 2 a 3 3 ...
3
2016-06-10T17:54:11Z
37,755,303
<p>Using <a href="https://docs.python.org/3.5/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a>:</p> <pre><code>from itertools import product result = pd.DataFrame(list(product(dfA.iloc[:,0], dfB.iloc[:,0]))) </code></pre> <p>Not quite as efficient as <code>np.meshgrid</code...
2
2016-06-10T18:49:15Z
[ "python", "numpy", "pandas" ]
Filter the list of tables that start with a specific name
37,754,607
<p>I get the list of tables in the dataset using the below command. I wonder whether there is a way to filter the tables that start with a name 'Acura' and then store the result in an array? I do not find any filter methods if i try filtering the tables returned. Any help would be appreciated. </p> <pre><code> list = ...
1
2016-06-10T18:03:37Z
37,791,080
<pre><code>[item for item in list if str(item).startswith('test:SF.Acura')] </code></pre>
0
2016-06-13T13:28:50Z
[ "python", "google-bigquery" ]
Write to a masked array in numpy
37,754,609
<p>Let's say I have an array <code>x</code> and a mask for the array <code>mask</code>. I want to use <code>np.copyto</code> to write to <code>x</code> using <code>mask</code>. Is there a way I can do this? Just trying to use <code>copyto</code> doesn't work, I suppose because the masked <code>x</code> is not writeable...
1
2016-06-10T18:03:40Z
37,754,965
<p>As commented index assignment works</p> <pre><code>In [16]: x[mask]=[30,40] In [17]: x Out[17]: array([ 1, 2, 30, 40]) </code></pre> <p>You have to careful when using <code>x[mask]</code>. That is 'advanced indexing', so it creates a copy, not a view of <code>x</code>. With direct assignment that isn't an issu...
2
2016-06-10T18:27:24Z
[ "python", "numpy" ]
Yahoo incorrect username or password?
37,754,615
<p>I created yahoo email via web interface, have enabled pop3 access(set auto), but still get following error:</p> <pre><code>poplib.error_proto: -ERR [AUTH] (#MBR1212) Incorrect username or password. </code></pre> <p>My python script.</p> <pre><code>import poplib oMailBox = poplib.POP3_SSL('pop.mail.yahoo.com', por...
1
2016-06-10T18:04:02Z
37,754,974
<p>Maybe you have not enabled pop for the account? <a href="https://help.yahoo.com/kb/learn-enable-pop-in%C2%A0yahoo-mail-sln22038.html" rel="nofollow">https://help.yahoo.com/kb/learn-enable-pop-in%C2%A0yahoo-mail-sln22038.html</a> or you don't have yahoo-plus account (<a href="http://www.freeemailtutorials.com/yahooMa...
0
2016-06-10T18:27:59Z
[ "python", "yahoo-mail" ]
Yahoo incorrect username or password?
37,754,615
<p>I created yahoo email via web interface, have enabled pop3 access(set auto), but still get following error:</p> <pre><code>poplib.error_proto: -ERR [AUTH] (#MBR1212) Incorrect username or password. </code></pre> <p>My python script.</p> <pre><code>import poplib oMailBox = poplib.POP3_SSL('pop.mail.yahoo.com', por...
1
2016-06-10T18:04:02Z
37,755,081
<p>I just tried using your code on my Yahoo account, and I get the same error, but I also have a secondary email that tells me when unrecognized access happens on that account, in which case I see the below message. </p> <p>Seems though you may have to also disable security on your account as well as enable POP3. </p>...
1
2016-06-10T18:33:34Z
[ "python", "yahoo-mail" ]
Django, How to allow users to download a Python generated file
37,754,700
<p>I am new to Django and have a few questions.</p> <p>I made a python program that requires user input, and a docx file. How do I allow that user to download their generated docx file? I am assuming I am going to have to work with temporary files since the program can not overwrite an existing docx file if there ar...
1
2016-06-10T18:09:27Z
37,755,438
<p>Write the response with "Content-Type: application/octet-stream" and "Content-Disposition: attachment". Then write the updated file to the response. <br/> For more exact mime types, check out: <a href="http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc">What is a correct mime t...
0
2016-06-10T18:59:00Z
[ "python", "django", "download", "docx", "temporary" ]
Override existing django-admin command
37,754,715
<p>In addition to writing custom django-admin commands, <a href="https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/" rel="nofollow">which is pretty well documented</a>, I would like to be able to override an existing command, like <code>manage.py loaddata (fixture)</code> so I could add some furthe...
1
2016-06-10T18:10:20Z
37,755,287
<p>Thanks to Moses link to other SO answers I eventually managed to write a template for additional treatment to a <code>loaddata</code> command. Here is a snippet which does the trick:</p> <pre><code>""" Additional treatment for the loaddata command. Location example: project/app/management/commands/loaddata.py """ f...
2
2016-06-10T18:47:31Z
[ "python", "django" ]
PyQt connecting signal from QComboBox inside the QTreeWidgetItem
37,754,719
<p>I've made a QTreeWidget where I have comboBox as a QTreeWidgetItem. How do I hook up the signal correctly so that each comboxBox index changed will change the same row in the treeWidget ?</p> <p><a href="http://i.stack.imgur.com/28ULl.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/28ULl.jpg" alt="exampleWi...
0
2016-06-10T18:10:31Z
37,783,053
<p>It's not really clear how you're creating each combobox (are <code>self.action</code> and <code>self.actionCombo</code> being set to a new combobox each time?). </p> <p>Assuming you're just creating a new <code>QComboBox</code> for each item widget, the simplest way would be to just pass <em>both</em> the combobox...
1
2016-06-13T06:26:21Z
[ "python", "pyqt", "qcombobox", "qtreewidget", "qtreewidgetitem" ]
How to get full path to python program including filename within the program?
37,754,733
<p>I have a python program, and I want to get the path to the program from within the program, but INCLUDING the file name itself. The name of my file is PyWrapper.py. Right now I'm doing this:</p> <pre><code>import sys,os pathname = os.path.dirname(sys.argv[0]) fullpath = os.path.abspath(pathname) print fullpath </co...
0
2016-06-10T18:11:17Z
37,754,821
<pre><code>print __file__ </code></pre> <p>should work. </p> <p><code>__file__</code> returns the path of the executed file</p>
0
2016-06-10T18:16:46Z
[ "python", "path", "python-os" ]
How to get full path to python program including filename within the program?
37,754,733
<p>I have a python program, and I want to get the path to the program from within the program, but INCLUDING the file name itself. The name of my file is PyWrapper.py. Right now I'm doing this:</p> <pre><code>import sys,os pathname = os.path.dirname(sys.argv[0]) fullpath = os.path.abspath(pathname) print fullpath </co...
0
2016-06-10T18:11:17Z
37,754,847
<p>Take a look at <code>__file__</code>. This gives you a filename where the code actually <strong>is</strong>.</p> <p>Also, there's another option:</p> <pre><code>import __main__ as main print(main.__file__) </code></pre> <p>This gives you a filename of a script being <strong>run</strong> (similar to what your <cod...
0
2016-06-10T18:19:00Z
[ "python", "path", "python-os" ]
How to get full path to python program including filename within the program?
37,754,733
<p>I have a python program, and I want to get the path to the program from within the program, but INCLUDING the file name itself. The name of my file is PyWrapper.py. Right now I'm doing this:</p> <pre><code>import sys,os pathname = os.path.dirname(sys.argv[0]) fullpath = os.path.abspath(pathname) print fullpath </co...
0
2016-06-10T18:11:17Z
37,754,850
<p>Just in case you would like to find the absolute path for other files, not just the one you are currently running, in that same directory, a general approach could look like this:</p> <pre><code>import sys,os pathname = os.path.dirname(sys.argv[0]) fullpath = os.path.abspath(pathname) for root, dirs, files in os....
0
2016-06-10T18:19:14Z
[ "python", "path", "python-os" ]
How to get full path to python program including filename within the program?
37,754,733
<p>I have a python program, and I want to get the path to the program from within the program, but INCLUDING the file name itself. The name of my file is PyWrapper.py. Right now I'm doing this:</p> <pre><code>import sys,os pathname = os.path.dirname(sys.argv[0]) fullpath = os.path.abspath(pathname) print fullpath </co...
0
2016-06-10T18:11:17Z
37,754,891
<p>try using <code>__file__</code>. as long as the module is ran from a file, i.e. not code in an editor, <code>__file__</code> will be the abs path to the module!</p> <pre><code>print __file__ </code></pre> <p>Or for command line.</p> <pre><code>def get_my_name(): if __name__ == '__main__': return os.pa...
0
2016-06-10T18:22:10Z
[ "python", "path", "python-os" ]
Mock bottle.request object in python
37,754,749
<p>I am using <a href="/questions/tagged/bottle" class="post-tag" title="show questions tagged &#39;bottle&#39;" rel="tag">bottle</a> framework. I have code like</p> <pre><code>from bottle import request def abc(): x = request.get_header('x') ... ... data = request.json() ... ... </code></pre>...
1
2016-06-10T18:12:10Z
37,770,054
<p>An easy alternative, to mock a bottle request, could be to inject it into your function:</p> <pre><code>from bottle import request def abc(_request=None): if _request is not None: request = _request x = request.get_header('x') ... ... data = request.json() ... ... </code></pre> ...
1
2016-06-12T01:58:56Z
[ "python", "unit-testing", "mocking", "bottle", "python-unittest" ]
Can I integrate MathJax into a Python program?
37,754,756
<p>This might be a silly question, but is it possible to merge MathJax into Python code? Many times I've wished the program output would look more neat, and honestly MathJax looks awesome.</p> <p>I know MathJax runs on Javascript, yet I have not given up hope. If the answer is no, are there some simple modules to use ...
1
2016-06-10T18:12:35Z
37,755,133
<p>I can only presume that maybe you want to output something to the display for printing. Hence the common usage in Python is probably Matplotlib (albeit Gnuplot is a good alternative that is python compatible). If you create a blank plot using Matplotlib then you can input normal plain LaTeX maths instructions (near ...
3
2016-06-10T18:37:02Z
[ "python", "mathjax", "integrate" ]
Python - Get Result of Google Search
37,754,771
<p><br> My goal is to create a small sript that find all the result of a google search but in "raw".<br> I don't speak english very well so i prefer to give an exemple to show you what i would like : <br> I Type : elephant<br> The script return <br> www.elephant.com<br> www.bluelephant.com<br> www.ebay.com/elephant<br>...
2
2016-06-10T18:13:29Z
37,754,845
<p>One simple way is to make a request to google search, then parse the html result. You can use some Python libraries such us Beautiful Soup to parse the html content easily, finally get the url link you need.</p>
3
2016-06-10T18:18:59Z
[ "python" ]
Python - Get Result of Google Search
37,754,771
<p><br> My goal is to create a small sript that find all the result of a google search but in "raw".<br> I don't speak english very well so i prefer to give an exemple to show you what i would like : <br> I Type : elephant<br> The script return <br> www.elephant.com<br> www.bluelephant.com<br> www.ebay.com/elephant<br>...
2
2016-06-10T18:13:29Z
37,755,227
<p>You have 2 options - using API or make a request like a browser does and then parse HTML.</p> <ul> <li><p>First option is rather <a href="http://stackoverflow.com/questions/4082966/what-are-the-alternatives-now-that-the-google-web-search-api-has-been-deprecated">tricky</a> to set up and is limited - 100 free querie...
0
2016-06-10T18:43:37Z
[ "python" ]
Python - Get Result of Google Search
37,754,771
<p><br> My goal is to create a small sript that find all the result of a google search but in "raw".<br> I don't speak english very well so i prefer to give an exemple to show you what i would like : <br> I Type : elephant<br> The script return <br> www.elephant.com<br> www.bluelephant.com<br> www.ebay.com/elephant<br>...
2
2016-06-10T18:13:29Z
37,755,362
<p>These seem to change often, so hopefully this answer remains useful for a little while...</p> <p>First, you'll need to create a Google Custom Search, by visiting their site or following the instructions provided here <a href="https://developers.google.com/custom-search/docs/tutorial/creatingcse" rel="nofollow">http...
1
2016-06-10T18:53:35Z
[ "python" ]
Preventing the user to access the data of another user by typing the slug in the url
37,754,778
<p>If user 1 creat this ticket : mywebsite/manager/tickets/ticket-from-user-1/</p> <p>And user 2 create that : mywebsite/manager/tickets/ticket-from-user-2/</p> <p>How can I prevent user 1 to access the ticket from user 2 or other users by typing it in the url?</p> <blockquote> <p>views.py</p> </blockquote> <pre>...
0
2016-06-10T18:13:48Z
37,755,423
<p>You will need to make user 1 have something that user 2 can not imitate.</p> <p>Preferred way would be to use your existing auth methods and check if user accessing the page is allowed to do so.</p> <p>If you don't have registration on your site then you could generate some random string - <code>secret</code> - an...
0
2016-06-10T18:58:12Z
[ "python", "django", "django-views" ]
Preventing the user to access the data of another user by typing the slug in the url
37,754,778
<p>If user 1 creat this ticket : mywebsite/manager/tickets/ticket-from-user-1/</p> <p>And user 2 create that : mywebsite/manager/tickets/ticket-from-user-2/</p> <p>How can I prevent user 1 to access the ticket from user 2 or other users by typing it in the url?</p> <blockquote> <p>views.py</p> </blockquote> <pre>...
0
2016-06-10T18:13:48Z
37,757,376
<p>I recently implemented this functionality in a project. It can be done by using automatically generated uuid's. Django has <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#uuidfield" rel="nofollow">a built-in model field</a> for this, or you can use a slug field and give it a default value. Here is ...
1
2016-06-10T21:25:40Z
[ "python", "django", "django-views" ]
Python - Adding Decimal places to elements in cvs file
37,754,853
<p>When exporting a CSV file from a data simulation, we lost the decimal places that were associated with the data recorded, making our plots and values inaccurate.</p> <p>When the data was collected, it was imported into excel and then exported as a CSV. There were originally decimal values with the data (e.g. 1356.0...
0
2016-06-10T18:19:20Z
37,755,312
<p>I'm not sure your problem is so much about precision as it is about data type. Is all your data being interpreted as integers?</p> <p>Try converting your row into floating point before accessing its columns:</p> <pre><code>row = map(float, row) </code></pre> <p>Or if you just want to change the string...
0
2016-06-10T18:49:58Z
[ "python", "csv", "numpy" ]
How to get the indices list of all NaN value in numpy array?
37,754,948
<p>Say now I have a numpy array which is defined as,</p> <pre><code>[[1,2,3,4], [2,3,NaN,5], [NaN,5,2,3]] </code></pre> <p>Now I want to have a list that contains all the indices of the missing values, which is <code>[(1,2),(2,0)]</code> at this case.</p> <p>Is there any way I can do that?</p>
4
2016-06-10T18:26:38Z
37,755,016
<p><a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.isnan.html">np.isnan</a> combined with <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.argwhere.html">np.argwhere</a></p> <pre><code>x = np.array([[1,2,3,4], [2,3,np.nan,5], [np.nan,5,2,3]...
6
2016-06-10T18:29:58Z
[ "python", "numpy", "scipy" ]
How to get the indices list of all NaN value in numpy array?
37,754,948
<p>Say now I have a numpy array which is defined as,</p> <pre><code>[[1,2,3,4], [2,3,NaN,5], [NaN,5,2,3]] </code></pre> <p>Now I want to have a list that contains all the indices of the missing values, which is <code>[(1,2),(2,0)]</code> at this case.</p> <p>Is there any way I can do that?</p>
4
2016-06-10T18:26:38Z
37,755,179
<p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> to match the boolean conditions corresponding to <code>Nan</code> values of the array.</p> <pre><code>&gt;&gt;&gt;print map(tuple, np.where(np.isnan(arr))) [(1, 2), (2, 0)] </co...
3
2016-06-10T18:40:25Z
[ "python", "numpy", "scipy" ]
Google Calendar Integration with Django
37,754,999
<p>Is there a fully fledged Django-based example of a Google Calendar integration? I was reading through <a href="https://developers.google.com/api-client-library/python/guide/django" rel="nofollow">Google's example page</a> but their link at the bottom is outdated.</p> <p>I'm specifically struggeling with the refresh...
2
2016-06-10T18:29:18Z
37,933,674
<p>Researching a lot of different approaches I found out that server-to-server authentication is what I wanted. This way no user has to explicitly give permissions and acquired auth-tokens don't have to be renewed. Instead, using a service account, a server can make calls itself.</p> <p>Before you can start coding, yo...
1
2016-06-21T00:06:40Z
[ "python", "django", "oauth-2.0", "google-calendar" ]
store pk from detail route in the serializer [django REST API]
37,755,035
<p><strong>I asked this question before but with less clarity</strong></p> <p>How to save the <code>id</code> inside the <code>RelatedFiled</code> of the <code>ForeignKey</code> ?</p> <p>I am testing an application on django, I have two models:</p> <pre><code>class Album(models.Model): album_id = models.IntegerF...
0
2016-06-10T18:31:07Z
37,759,588
<p>Instead of passing <code>album_id</code> in <code>context</code>, you can <strong>pass <code>album_id</code> via <code>serializer.save()</code></strong> and DRF will automatically create <code>Song</code> object with <code>album_id</code> field.</p> <p>You need to make some changes to your code. </p> <p>In your vi...
0
2016-06-11T03:18:35Z
[ "python", "django", "django-rest-framework" ]
store pk from detail route in the serializer [django REST API]
37,755,035
<p><strong>I asked this question before but with less clarity</strong></p> <p>How to save the <code>id</code> inside the <code>RelatedFiled</code> of the <code>ForeignKey</code> ?</p> <p>I am testing an application on django, I have two models:</p> <pre><code>class Album(models.Model): album_id = models.IntegerF...
0
2016-06-10T18:31:07Z
37,792,535
<p>Turns out inside the serializer I need to use:</p> <pre><code>self.context.get("request").parser_context["kwargs"]["album_id"] </code></pre>
0
2016-06-13T14:35:52Z
[ "python", "django", "django-rest-framework" ]
Pandas change column value if greater than len
37,755,069
<p>I am trying to use an if statement to change values within a column if there length is greater than x</p> <p>My csv data ..</p> <pre><code> ID Test_Case TC_NUM 14581,dialog_testcase_4000.0134_mvp_not_understood-inprogress.xml,4000.0134 14582,dialog_testcase_40...
1
2016-06-10T18:32:54Z
37,755,328
<p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a>:</p> <pre><code>print (df.TC_NUM.str.len() &gt; 9) 0 False 1 False 2 False 3 True 4 True Name: TC_NUM, dtype: bool df['TC_NUM'] = df.TC_NUM.mask(df.TC_NUM....
2
2016-06-10T18:51:06Z
[ "python", "csv", "pandas" ]
Arranging the data in a text file using python: group data by month
37,755,080
<p>I have a text file called <code>data.txt</code> which contains the following information in it</p> <pre><code>03/05/2016 502 04/05/2016 502 05/05/2016 501 07/05/2016 504 09/05/2016 505 13/05/2016 506 23/05/2016 501 30/05/2016 501 02/06/2016 502 04/06/2016 502 06/06/2016 501 07/06/2016 504 08/06/2016 50...
-1
2016-06-10T18:33:30Z
37,755,973
<p>Looks like the output requirement changed a bit! Nevertheless, this should provide enough motivation to smooth out the rough edges.</p> <pre><code>dataStore = {} # Method to process an input line def processLine(dateStr, val): if dateStr not in dataStore: dataStore[dateStr] = val else: dataStore[dateSt...
0
2016-06-10T19:38:49Z
[ "python", "python-2.7", "logic" ]
Arranging the data in a text file using python: group data by month
37,755,080
<p>I have a text file called <code>data.txt</code> which contains the following information in it</p> <pre><code>03/05/2016 502 04/05/2016 502 05/05/2016 501 07/05/2016 504 09/05/2016 505 13/05/2016 506 23/05/2016 501 30/05/2016 501 02/06/2016 502 04/06/2016 502 06/06/2016 501 07/06/2016 504 08/06/2016 50...
-1
2016-06-10T18:33:30Z
37,755,985
<pre><code>import re from collections import defaultdict def sum_months(data_path): with open (data_path, 'r') as f: rows = f.readlines() sumdict = defaultdict(int) for row in rows: month = re.findall("/\d{2}/\d{4}", row)[0] sum = re.findall("\d+$", row)[0] ...
0
2016-06-10T19:39:22Z
[ "python", "python-2.7", "logic" ]
Calculating forward or backwards with pandas dataframes
37,755,090
<p>I want to calculate % differences in a dataframe by week, and put those calculations in a new dataframe.</p> <p>Start with <code>df</code>:</p> <pre><code>index Date Zone Amount 0 2011-01-08 YQHDK 1691938000.0 1 2011-02-05 YQHDK 1760009000.0 2 2011-03-05 YQHDK 1893000000.0...
0
2016-06-10T18:34:11Z
37,755,211
<p>you can do it this way:</p> <pre><code>In [15]: df.Amount.pct_change()*100 Out[15]: 0 NaN 1 4.023256 2 7.556268 Name: Amount, dtype: float64 </code></pre> <p>or </p> <pre><code>In [16]: df.Amount.pct_change().shift(-1)*100 Out[16]: 0 4.023256 1 7.556268 2 NaN Name: Amount, dtype: fl...
3
2016-06-10T18:42:16Z
[ "python", "pandas", "dataframe" ]
Is there any way to export raw data from Google Analytics using BigQuery?
37,755,143
<p>...without being a Google Premium customer?</p> <p>There are a bunch of sources telling how I can export the raw data from GA to BigQuery if I'm a premium customer...</p> <p><a href="https://cloud.google.com/bigquery/query-reference" rel="nofollow">https://cloud.google.com/bigquery/query-reference</a> <a href="htt...
1
2016-06-10T18:37:46Z
37,755,399
<p>Unfortunately, there really is no way to export raw, unaggregated, hit-level data from GA to BigQuery without being a GAP customer. </p> <p>However, it is possible to leverage the GA API to capture the metrics and dimensions that you may be interested in and then upload these data as tables in BigQuery. The obvious...
0
2016-06-10T18:56:36Z
[ "python", "google-api", "google-bigquery" ]
Is there any way to export raw data from Google Analytics using BigQuery?
37,755,143
<p>...without being a Google Premium customer?</p> <p>There are a bunch of sources telling how I can export the raw data from GA to BigQuery if I'm a premium customer...</p> <p><a href="https://cloud.google.com/bigquery/query-reference" rel="nofollow">https://cloud.google.com/bigquery/query-reference</a> <a href="htt...
1
2016-06-10T18:37:46Z
37,762,380
<p>As I understand you can use solution from OWOX, it would be cheaper. <a href="https://www.owox.com/pricing/" rel="nofollow">https://www.owox.com/pricing/</a></p>
0
2016-06-11T09:59:01Z
[ "python", "google-api", "google-bigquery" ]
Implementing the Algorithm for Erastosthenes Sieve
37,755,147
<p>I'm new to programming and python and would like some help with finding the primality of an integer. I've read some approaches to implementing Eratosthene's sieve but most seem a bit too involved (too much code). Here is my approach and the part where I need help is below the #HELP comment:</p> <pre><code>def prime...
0
2016-06-10T18:37:58Z
37,755,212
<p>To answer your direct question:</p> <pre><code>for element in integer_list: for each_integer in integer_list: if (each_integer % element == 0) and (each_integer != element): integer_list.remove(each_integer) </code></pre> <p>(I'm assuming that you meant for <code>fourth_element</code> to be...
1
2016-06-10T18:42:21Z
[ "python", "algorithm" ]
"ImportError: No module named webapp2" after Linux SDK upgrade (1.9.35 -> 1.9.38)
37,755,195
<p>After upgrading my GAE Python Linux SDK from version 1.9.35 to 1.9.38 my application stopped working, all requests are failing in similar manner:</p> <pre><code>ERROR 2016-06-10 17:55:06,100 wsgi.py:263] Traceback (most recent call last): File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", li...
2
2016-06-10T18:41:28Z
37,764,786
<p>Update: The issue was fixed in SDK version 1.9.40.</p> <p>The issue is already known to Google, introduced in 1.9.37:</p> <ul> <li><a href="https://groups.google.com/forum/#!topic/google-appengine/LucknWk8iaQ" rel="nofollow">the acknowledged report</a> with more info</li> <li>tracked as <a href="https://code.googl...
1
2016-06-11T14:20:16Z
[ "python", "google-app-engine" ]
ArgumentParser for numpy array
37,755,273
<p>Is there a way to add an argument to ArgumentParser for an np.array instead of a list? I know I can do something like this</p> <pre><code>import argparse parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-foo', action='store', type=int, nargs='+') args = parser.parse_args(['-foo', '1', '2']) args.f...
1
2016-06-10T18:46:20Z
37,755,413
<p>To specify a slight change in how the <code>StoreAction</code> action handler works you would create a subclass of the handler with appropriate change:</p> <pre><code>import argparse, numpy as np class Store_as_array(argparse._StoreAction): def __call__(self, parser, namespace, values, option_string=None): ...
0
2016-06-10T18:57:38Z
[ "python", "arrays", "numpy", "argparse" ]
ArgumentParser for numpy array
37,755,273
<p>Is there a way to add an argument to ArgumentParser for an np.array instead of a list? I know I can do something like this</p> <pre><code>import argparse parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-foo', action='store', type=int, nargs='+') args = parser.parse_args(['-foo', '1', '2']) args.f...
1
2016-06-10T18:46:20Z
37,755,635
<p>As indicated in my comment, 'complete description before parsing' is unclear.</p> <p>But it occurred to me that it is possible to create a 2d array with <code>argparse</code>. I can use <code>nargs=3</code> to specify 3 columns, and <code>action='append'</code> to collect the input in multiple sublists. And of co...
0
2016-06-10T19:13:05Z
[ "python", "arrays", "numpy", "argparse" ]
Find max value in a pandas dataframe that also has None's, Python 3.5
37,755,374
<p>I have a pandas dataframe setup like this:</p> <pre><code> Group1 Group2 Group3 0 0.04058678 0.04282689 0.06680679 1 0.11657916 0.06695174 0.05153584 2 0.08382576 0.03587087 0.08919266 3 0.17477007 0.08141088 0.10727157 4 0.0821453 0.08226264 0.06800853 5 0.15685707 None ...
0
2016-06-10T18:54:21Z
37,755,410
<p>I think you can use:</p> <pre><code>print (df.apply(lambda x: pd.to_numeric(x, errors='coerce')).max()) Group1 0.174770 Group2 0.082263 Group3 0.179665 dtype: float64 print (df.apply(lambda x: pd.to_numeric(x, errors='coerce')).idxmax()) Group1 3 Group2 4 Group3 9 dtype: int64 </code></pre>
1
2016-06-10T18:57:31Z
[ "python", "pandas", "dataframe" ]
Find max value in a pandas dataframe that also has None's, Python 3.5
37,755,374
<p>I have a pandas dataframe setup like this:</p> <pre><code> Group1 Group2 Group3 0 0.04058678 0.04282689 0.06680679 1 0.11657916 0.06695174 0.05153584 2 0.08382576 0.03587087 0.08919266 3 0.17477007 0.08141088 0.10727157 4 0.0821453 0.08226264 0.06800853 5 0.15685707 None ...
0
2016-06-10T18:54:21Z
37,755,412
<p>is that what you want?</p> <p>maximum element:</p> <pre><code>In [53]: df.replace('None', np.nan).max().max() Out[53]: 0.17966472 </code></pre> <p>or</p> <pre><code>In [46]: df.replace('None', -np.inf).max() Out[46]: Group3 0.179665 dtype: float64 </code></pre> <p>maximum per column:</p> <pre><code>In [35]:...
2
2016-06-10T18:57:37Z
[ "python", "pandas", "dataframe" ]
apply/ map function to prior row
37,755,429
<p>still new to functions and its application I would like to create a new column <code>D</code> for a dataframe:</p> <pre><code> df = pd.DataFrame([[1, 2, 3], [1, 3, 5], [4, 6, 7]], columns=['A', 'B', 'C']) A B C 0 1 2 3 1 1 3 5 2 4 6 7 </code></pre> <p>the column <code>D</code> and its co...
2
2016-06-10T18:58:39Z
37,755,570
<p>You could also just:</p> <pre><code>df.loc[df.C &gt; df.B.shift(), 'D'] = 'left' df.D = df.D.fillna('right') A B C D 0 1 2 3 right 1 1 3 5 left 2 4 6 7 left </code></pre>
2
2016-06-10T19:08:15Z
[ "python", "dictionary", "pandas", "dataframe" ]
apply/ map function to prior row
37,755,429
<p>still new to functions and its application I would like to create a new column <code>D</code> for a dataframe:</p> <pre><code> df = pd.DataFrame([[1, 2, 3], [1, 3, 5], [4, 6, 7]], columns=['A', 'B', 'C']) A B C 0 1 2 3 1 1 3 5 2 4 6 7 </code></pre> <p>the column <code>D</code> and its co...
2
2016-06-10T18:58:39Z
37,755,581
<p>Lets suppose this is a pandas dataframe named <code>df</code></p> <pre><code>A B 0 0 1 1 2 2 3 3 4 4 </code></pre> <p>Now lets suppose I apply shift to <code>B</code> column</p> <p>What'll happen is </p> <pre><code>A B 0 NaN 1 0 2 1 3 2 4 3 </code></pre> <p>So no...
3
2016-06-10T19:08:59Z
[ "python", "dictionary", "pandas", "dataframe" ]
apply/ map function to prior row
37,755,429
<p>still new to functions and its application I would like to create a new column <code>D</code> for a dataframe:</p> <pre><code> df = pd.DataFrame([[1, 2, 3], [1, 3, 5], [4, 6, 7]], columns=['A', 'B', 'C']) A B C 0 1 2 3 1 1 3 5 2 4 6 7 </code></pre> <p>the column <code>D</code> and its co...
2
2016-06-10T18:58:39Z
37,755,625
<p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p> <pre><code>df['D'] = np.where(df.C &gt; df.B.shift(), 'left', 'right') print (df) A B C D 0 1 2 3 right 1 1 3 5 left 2 4 6 7 left </code></pre> ...
4
2016-06-10T19:12:14Z
[ "python", "dictionary", "pandas", "dataframe" ]
Compute natural log of survival function of a Gaussian in Python/numpy/scipy
37,755,455
<p>I can compute the natural log of the survival function of a Gaussian distribution using</p> <pre><code>np.log( scipy.stats.norm.sf(s) ) </code></pre> <p>I need to compute the survival function for some ludicrously large values of s (maybe up to 1000), but the above function hits double point machine precision arou...
0
2016-06-10T19:00:13Z
37,755,711
<p>Use the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.logsf.html" rel="nofollow"><code>logsf</code></a> method of <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html" rel="nofollow"><code>scipy.stats.norm</code></a>.</p> <p>For example:</p> <p...
3
2016-06-10T19:18:48Z
[ "python", "numpy", "scipy", "statistics" ]
Executing bash file via php on apache server
37,755,463
<p>So I have hosted a webpage on my apache server and I'm trying to run some python and bash scripts when the user presses a button via PHP and AJAX.</p> <p>Now my php file executes at python script (located in <code>/var/www/html</code>) which in turn executes a bash file (located in <code>root/files</code>).</p> <p...
2
2016-06-10T19:00:35Z
37,755,902
<p>Most likeley because a bash script in its self won't be executable, it's just a plain textfile.<br> Your bash (and perhaps even <code>appgenserver.py</code>?) might be located under <code>/root</code> and apache probably runs as a non-priviliged user such as <code>www-data</code>, that user won't be able to access e...
1
2016-06-10T19:33:57Z
[ "php", "python", "git", "bash", "apache" ]
Trouble finding certain tag values
37,755,492
<p>I'm trying to find the value of several tags using pydicom. For some reason only certain tags work while others do not. Below is a traceback explaining my problem. Can anyone see a way around the int() base 16 problem?</p> <pre><code>&gt;&gt;&gt; ds['0x18','0x21'].value 'SP' &gt;&gt;&gt; ds['0x18','13x14'].value Tr...
-1
2016-06-10T19:02:59Z
37,755,607
<p>'13x14' is not a valid representation of base 16 number.</p> <p>In python, base 16 numbers are represented with '0x' as prefix and then the number in base 16.</p> <p>For example:</p> <p>0x0, 0x1, 0x001, 0x235, 0xA5F, ..., are all valid base 16 number representations.</p> <hr> <p>This:</p> <pre><code>ds['0x18',...
0
2016-06-10T19:10:52Z
[ "python", "int", "dicom" ]
WARNING:tensorflow:TensorFlowDNNRegressor class is deprecated. Please consider using DNNRegressor as an alternative
37,755,579
<p>Yesterday, I had updated Tensorflow to version 0.9 from 0.8. After which, I am observing the following warning with my Skflow models. Could anyone please let me know what this means? Is there a way to fix it? Are there alternate methods to model DNN Regressor with Skflow? </p> <blockquote> <p>/Library/Framework...
0
2016-06-10T19:08:54Z
37,761,236
<p>This is just a Warning so your model will train fine. Skflow (or TFLearn same thing) advises you to use <code>skflow.DNNRegressor</code> instead of <code>skflow.TensorFlowDNNRegressor</code>.</p> <p>Here are the arguments of <code>DNNRegressor</code> and the <a href="https://www.tensorflow.org/versions/r0.9/api_doc...
0
2016-06-11T07:41:12Z
[ "python", "tensorflow", "skflow" ]
psycopg2: use a list in a query without index rows
37,755,600
<p>I'm writing to a db using this query with various placeholders:</p> <pre><code>sql_write_ord = '''INSERT INTO rest_order_test (date_order, pos_line_id, pos_order_id, product_name, instructions, qty, partner_name, status, to_wait, to_floor) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''' order= '...
1
2016-06-10T19:10:35Z
37,755,736
<p>You can just concatenate the lists:</p> <pre><code>cur.execute(sql_write_ord, [order] + newTable) </code></pre>
1
2016-06-10T19:20:22Z
[ "python", "postgresql", "list", "python-2.7", "psycopg2" ]
Backslashes in Python Regex
37,755,603
<p>I'm writing a quick Python script to do a bit of inspection on some of our Hibernate mapping files. I'm trying to use this bit of Python to get the table name of a POJO, whether or not its class path is fully defined:</p> <pre><code>searchObj = re.search(r'&lt;class name="(.*\\.|)' + pojo + '".*table="(.*?)"', cont...
2
2016-06-10T19:10:41Z
37,755,823
<p>On <a href="http://pythex.org" rel="nofollow">Pythex</a>, I tried this regex:</p> <p><code>&lt;class name="(.*)\.MyObject" table="([^"]*)"</code></p> <p>on this string:</p> <p><code>&lt;class name="com.place.package.MyObject" table="my_cool_object" dynamic-insert="true" dynamic-update="true"&gt;</code></p> <p>an...
2
2016-06-10T19:27:21Z
[ "python", "regex" ]
Backslashes in Python Regex
37,755,603
<p>I'm writing a quick Python script to do a bit of inspection on some of our Hibernate mapping files. I'm trying to use this bit of Python to get the table name of a POJO, whether or not its class path is fully defined:</p> <pre><code>searchObj = re.search(r'&lt;class name="(.*\\.|)' + pojo + '".*table="(.*?)"', cont...
2
2016-06-10T19:10:41Z
37,756,251
<p>Given this:</p> <pre><code>re.search(r'&lt;class name="(.*\\.|)' + pojo + '".*table="(.*?)"', contents) </code></pre> <p>The the first part of the pattern is interpreted like this:</p> <pre><code>1. class name=" a literal string beginning with c and ending with " 2. ( the beginning of a group 3. ...
2
2016-06-10T19:57:58Z
[ "python", "regex" ]
randomly fill 2d matrix with conditions
37,755,618
<p>Here is my situation and I am just throwing it out there to get ideas how to approach it.</p> <p>I have categories <code>categories = [0, 1, 3]</code> and an <code>10 x 5</code> matrix, A</p> <p>How can I fill matrix A with random choices from categories such that each column must have ONE and only ONE occurrence...
2
2016-06-10T19:11:32Z
37,755,748
<p>Your question is a bit vague. Please provide more details on what you can have in other positions. if one position is 0 and 1 position is 1 and the other positions can be whatever, than use this.</p> <p>make an array[number_of_columns] = {0,1,2,2,....,2], Shuffle it. then for each position in the column (i) <code...
1
2016-06-10T19:21:38Z
[ "python", "matrix", "random-sample", "choice" ]
randomly fill 2d matrix with conditions
37,755,618
<p>Here is my situation and I am just throwing it out there to get ideas how to approach it.</p> <p>I have categories <code>categories = [0, 1, 3]</code> and an <code>10 x 5</code> matrix, A</p> <p>How can I fill matrix A with random choices from categories such that each column must have ONE and only ONE occurrence...
2
2016-06-10T19:11:32Z
37,756,085
<p>Here's one way to do it assuming you already have the matrix. (The question says fill a matrix, not create a matrix)</p> <pre><code>import pprint import random categories = [0,1,3] #complete pool of numbers restrictedNumbers = [0, 1] #numbers to only appear once unrestrictedNumbers = [num for num in categories if ...
2
2016-06-10T19:48:01Z
[ "python", "matrix", "random-sample", "choice" ]
Having trouble getting root.after() to work
37,755,629
<p>Here's some back ground to the problem: I'm currently trying to have a simple tkinter gui on a raspberry pi display the sensor readings from a thermometer/humidity sensor. However, before I get to that, I needed to check if I could get tkinter to update itself with new values. I've included the code I'm using. Right...
0
2016-06-10T19:12:33Z
37,756,374
<p>did you try to use root.update() instead of root.after()? for me it works alot better like this:</p> <pre><code>import tkinter as tk root = tk.Tk() b = Frame(root) root.update() </code></pre> <p>in this example i use root.update instead of root.mainloop(), but thay can be combined and the cool part of root.update(...
0
2016-06-10T20:06:08Z
[ "python", "tkinter" ]
Creating a set of Python classes
37,755,675
<p>I have a class representing a Request. I have a set of very specific requests such as "I-95", "P-22", etc. which perform distinct functions and are called by a controller class. What is the best way to do this so that one could add more requests easily down the road? </p> <p>I have something like this at the moment...
1
2016-06-10T19:15:32Z
37,755,768
<p>Try something like:</p> <pre><code>class BaseRequest: name = None class FooRequest(BaseRequest): name = 'I-95' def response(self): return "foo" class BarRequest(BaseRequest): name = 'P-22' def response(self): return "bar" class RequestManager: def __init__(self): ...
8
2016-06-10T19:22:56Z
[ "python", "class", "data-structures", "code-organization" ]
Retrieve youtube subscriptions python api
37,755,678
<p>I want to use youtube-api to retrieve list of my youtube subscriptions and other data from just command line using python (without display), after reading google developer docs I realized ouath 2 needs user interface but there's also a <a href="https://github.com/Kolifanes/plugin.video.youtube/" rel="nofollow">plugi...
0
2016-06-10T19:15:48Z
37,769,580
<p>You can use <a href="https://developers.google.com/youtube/v3/docs/activities/list" rel="nofollow"><code>Activities:list</code></a> this method returns a list of channel activity events that match the request criteria. For example, you can retrieve events associated with a particular channel, events associated with ...
0
2016-06-12T00:07:19Z
[ "python", "youtube-api", "youtube-api-v3" ]
Retrieve youtube subscriptions python api
37,755,678
<p>I want to use youtube-api to retrieve list of my youtube subscriptions and other data from just command line using python (without display), after reading google developer docs I realized ouath 2 needs user interface but there's also a <a href="https://github.com/Kolifanes/plugin.video.youtube/" rel="nofollow">plugi...
0
2016-06-10T19:15:48Z
38,825,902
<p>As you mentioned in order to retrieve a list of your subscriptions, you need to first authenticate and authorize your application or script to "read" your subscriptions. Once this is done, you'll be able to retrieve your YouTube subscriptions using the YouTube Subscriptions Data API list method: <a href="https://dev...
0
2016-08-08T09:43:00Z
[ "python", "youtube-api", "youtube-api-v3" ]
Python lxml getpath error
37,755,740
<p>I'm trying to get a full list of xpaths from a device config in xml. </p> <p>When I run it though I get:</p> <pre><code> AttributeError: 'Element' object has no attribute 'getpath' </code></pre> <p>Code is just a few lines </p> <pre><code>import xml.etree.ElementTree import os from lxml import etree file1 = 'C:...
1
2016-06-10T19:20:39Z
37,769,448
<p>You are doing it incorrectly, don't call getroot just parse and iter using <strong><em>lxml</strong>.etree</em>:</p> <pre><code>import lxml.etree as et file1 = 'C:/Users/test1/Desktop/test.xml' root = et.parse(file1) for e in root.iter(): print root.getpath(e) </code></pre> <p>If you are dealing with namespa...
0
2016-06-11T23:41:36Z
[ "python", "lxml" ]
setting username and password in the http header for a SOAP request message using zeep (python)?
37,755,843
<p>How can you set the username and password in the http header for a SOAP request message using python's zeep? I believe that is why i am getting a connection refused error but cannot figure out where the http header details can be set. I even tried just running python -mzeep on the wsdl file (vs creating a client and...
0
2016-06-10T19:28:51Z
37,761,728
<p>Zeep uses the requests library for http requests. The request session is available as <code>client.transport.session</code>.</p> <p>So doing something like <code>client.transport.session.headers.update({})</code> should work. See <a href="http://docs.python-requests.org/en/master/user/advanced/#session-objects" rel...
0
2016-06-11T08:38:06Z
[ "python", "web-services", "soap", "passwords" ]
Read in Large CSV File and feed into TensorFlow
37,755,972
<p>So I'm trying to read my csv file into python and then split the data into training and test data (n-fold Cross-validation) and then feed it into my already made deep learning architecture. However, after reading the TensorFlow tutorial on how to read in csv files, which is shown here:</p> <pre><code>filename_queue...
0
2016-06-10T19:38:42Z
37,756,427
<p>(1) 1200 is arbitrary - we should fix the example to have a named constant used there to make it more clear. Thanks for spotting it. :) With the way <a href="https://www.tensorflow.org/versions/r0.9/how_tos/reading_data/index.html#file-formats" rel="nofollow">the CSV reading example</a> is set up, continued reads...
1
2016-06-10T20:10:29Z
[ "python", "csv", "asynchronous", "tensorflow" ]
Import module defined in another module
37,756,028
<p>I have the following setup. The first file (config.py) defines a path, that tells file1.py which module to import.</p> <pre><code>#file:config.py moduleToBeImported="/here/is/some/path/file2.py" import file1 </code></pre> <p>Then in file1.py, I import the module that is defined in config.py</p> <pre><code>#file:...
0
2016-06-10T19:44:17Z
37,756,322
<p><strong>Short Answer</strong> - <strong>NO</strong></p> <hr> <p><strong>Long Answer</strong> - Maybe, you can. And <strong>NO</strong>, you <em>shouldn't</em>. Circular imports would result in import <em>cycles</em>. And that is bad.</p> <p>For example, let's say you imported <code>config.py</code> in <code>file1...
1
2016-06-10T20:02:36Z
[ "python", "python-2.7", "import" ]
Why doesn't Python spot errors before execution?
37,756,081
<p>Suppose I have the following code in Python:</p> <pre><code>a = "WelcomeToTheMachine" if a == "DarkSideOfTheMoon": awersdfvsdvdcvd print "done!" </code></pre> <p>Why doesn't this error? How does it even compile? In Java or C#, this would get spotted during compilation.</p>
2
2016-06-10T19:47:43Z
37,756,120
<p>Python isn't a compiled language, that's why your code doesn't throw compilation errors. </p> <p>Python is a byte code interpreted language. Technically the source code gets "compiled" to byte code, but then the byte code is just in time (JIT) compiled if using PyPy or Pyston otherwise it's line by line interpreted...
6
2016-06-10T19:50:08Z
[ "python" ]
Why doesn't Python spot errors before execution?
37,756,081
<p>Suppose I have the following code in Python:</p> <pre><code>a = "WelcomeToTheMachine" if a == "DarkSideOfTheMoon": awersdfvsdvdcvd print "done!" </code></pre> <p>Why doesn't this error? How does it even compile? In Java or C#, this would get spotted during compilation.</p>
2
2016-06-10T19:47:43Z
37,756,151
<p>During "compiling", python pretty much only checks your syntax. Since <code>awersdfvsdvdcvd</code> <em>is</em> a valid identifier, no error is raised until that line actually gets executed. Just because you use a name which wasn't defined doesn't mean that it couldn't have been defined elsewhere... e.g.:</p> <pre...
2
2016-06-10T19:51:59Z
[ "python" ]
Why doesn't Python spot errors before execution?
37,756,081
<p>Suppose I have the following code in Python:</p> <pre><code>a = "WelcomeToTheMachine" if a == "DarkSideOfTheMoon": awersdfvsdvdcvd print "done!" </code></pre> <p>Why doesn't this error? How does it even compile? In Java or C#, this would get spotted during compilation.</p>
2
2016-06-10T19:47:43Z
37,756,297
<p>Because Python is an interpreted language. This means that if Python's interpreter doesn't arrive to that line, it won't produce any error.</p>
2
2016-06-10T20:00:40Z
[ "python" ]
Moving a drawn rectangle
37,756,154
<p>I have the game come up and the rectangle rendered. When I press my KEYDOWN it doesn't move the rectangle, it just makes it longer. I have tried tons of stuff. I am new to Pygame.<br> Any help would be amazing.</p> <p>Here is the code:</p> <pre><code>import pygame import time import random import math import sys ...
0
2016-06-10T19:52:13Z
37,756,543
<p>So the problem is this: The rectangle is being constantly redrawn at a different coord, but the screen is not being drawn over the rectangle to cover up the part that is not supposed to be there. In simpler terms, we need to constantly draw the background. </p> <p>So now the code in the main game loop:</p> <pre><c...
0
2016-06-10T20:17:54Z
[ "python", "pygame" ]
Moving a drawn rectangle
37,756,154
<p>I have the game come up and the rectangle rendered. When I press my KEYDOWN it doesn't move the rectangle, it just makes it longer. I have tried tons of stuff. I am new to Pygame.<br> Any help would be amazing.</p> <p>Here is the code:</p> <pre><code>import pygame import time import random import math import sys ...
0
2016-06-10T19:52:13Z
37,756,682
<p>it actualy does move it, but the old one just stays there, making it look like it does not move but just grows. one way to change that would be to change the old ones color to the background color</p> <p>try this code it works :-)</p> <pre><code>import pygame import time import random import math import sys pyga...
0
2016-06-10T20:26:38Z
[ "python", "pygame" ]
Python, using tkinter how to customize where classes of ui components are displayed?
37,756,170
<p>I am very new to python, and am currently trying to organize my tkinter app in a slightly different way. I'm trying to use classes to make the app more modular and be able to use methods in the class in multiple places in the app. Here is the updated code that I have:</p> <pre><code>from tkinter import * class A...
0
2016-06-10T19:53:05Z
37,756,758
<p>One solution is to have the caller be responsible for calling <code>pack</code> or <code>grid</code> on the individual widgets. This requires that you save references to the widgets somehow, such as attributes of the object. You do this already for some widgets, but not for others. You need to be consistent.</p> <...
0
2016-06-10T20:32:29Z
[ "python", "tkinter" ]
How to interpret Singular Value Decomposition results (Python 3)?
37,756,171
<p>I'm trying to learn how to reduce dimensionality in datasets. I came across some tutorials on <code>Principle Component Analysis</code> and <code>Singular Value Decomposition</code>. I understand that it takes the dimension of greatest variance and sequentially collapses dimensions of the next highest variance (ov...
6
2016-06-10T19:53:09Z
37,949,853
<p>As you stated above matrix M can decomposed as product ot 3 matrices: U * S * V<sup>*</sup>. Geometrical sense is next: any transformation could be deemed as a sequence of rotation (V<sup> * </sup>), scaling (S) and rotation again(U). Here's good <a href="https://en.wikipedia.org/wiki/Singular_value_decomposition" r...
1
2016-06-21T16:28:40Z
[ "python", "machine-learning", "linear-algebra", "pca", "svd" ]
Using Pandas Melt() to pivot on two sets of data
37,756,265
<p>I have cell phone usage and bill data arranged in the <code>Pandas</code> <code>dataframe</code> that has stats for two months of data. I'd like to pivot the data so that columns for each month become rows.</p> <p>Starting point:</p> <pre><code> Name Jan Minutes Used Feb Minutes Used Jan Bill Paid Feb Bill...
1
2016-06-10T19:58:47Z
37,758,037
<p>You can achieve this with constructing a multi-index and then using stack:</p> <pre><code>In [31]: df = df.set_index(['Name', 'Gender']) # split column names on first space and create multi-index (expand=True) In [33]: df.columns = df.columns.str.split(' ', n=1, expand=True) In [34]: df Out[34]: ...
4
2016-06-10T22:34:33Z
[ "python", "python-2.7", "pandas" ]
Compare two excel files with different headers but same row data using Pandas DataFrames
37,756,280
<p>Here I am trying to compare two excel files. Server_report has 42 columns, Email_report has 19 (of which 5 columns have no match at all to the server_report). 14 of the columns match in each report but have different headers. When I have both files open I do a sort on three columns to line the data up 'Delivery', 'P...
1
2016-06-10T19:59:44Z
37,757,494
<p>In this solution I am assuming that both reports have the same number of rows and index.</p> <pre><code>import copy import pandas as pd import numpy as np # Example reports email_report = pd.DataFrame({'a':np.arange(6), 'b':np.arange(6), 'c':['A', 'B', email_report &gt;&gt;&gt; 'C', 'D', 'E', 'F'], 'extra_col':...
0
2016-06-10T21:37:12Z
[ "python", "excel", "pandas", "row", "matching" ]
Kernel smooth set of xyz tuplets (python preferred pseudocode welcome)
37,756,318
<p>I'd like to smooth a set of <code>xyz</code> tuplets into a surface and return the value of the <code>surface(z')</code> at the original set of of coordinates <code>(x,y)</code>. </p> <p>Is there a more direct approach then interpolating the original data onto a grid, smoothing it and re-evaluating. If that's the b...
0
2016-06-10T20:02:30Z
37,770,230
<p>"Smoothing" is not a well-defined operation; what it means is open to interpretation. There are many operations that result in "smoother" data, and most of them have at least one parameter that controls the amount of smoothing. Without knowing more about what you are going to do with the smoothed data, it is hard...
0
2016-06-12T02:43:43Z
[ "python", "scipy", "geometry-surface" ]
Missing a loop to write a file
37,756,392
<pre><code>import urllib.request import re import csv import pandas as pd from bs4 import BeautifulSoup stocklist = ['aapl','goog','fb','amzn','COP'] for stocklist in stocklist: optionsUrl = urllib.request.urlopen('http://finance.yahoo.com/q?s='+stocklist).read() soup = BeautifulSoup(optionsUrl) stocksymbo...
0
2016-06-10T20:07:42Z
37,756,518
<p>You can append to a file by doing </p> <pre><code>with open('test.csv', 'a') as f: my_df.to_csv(f, header=False) </code></pre> <p>this</p>
0
2016-06-10T20:16:49Z
[ "python", "pandas" ]
Missing a loop to write a file
37,756,392
<pre><code>import urllib.request import re import csv import pandas as pd from bs4 import BeautifulSoup stocklist = ['aapl','goog','fb','amzn','COP'] for stocklist in stocklist: optionsUrl = urllib.request.urlopen('http://finance.yahoo.com/q?s='+stocklist).read() soup = BeautifulSoup(optionsUrl) stocksymbo...
0
2016-06-10T20:07:42Z
37,757,013
<p>You're overwriting your csv everytime you loop. You should collect all the data and write them to the csv after looping:</p> <pre><code>stocklist = ['aapl','goog','fb','amzn','COP'] columns = [] data = [] for s in stocklist: optionsUrl = urllib.request.urlopen('http://finance.yahoo.com/q?s='+s).read() soup ...
2
2016-06-10T20:53:55Z
[ "python", "pandas" ]
Missing a loop to write a file
37,756,392
<pre><code>import urllib.request import re import csv import pandas as pd from bs4 import BeautifulSoup stocklist = ['aapl','goog','fb','amzn','COP'] for stocklist in stocklist: optionsUrl = urllib.request.urlopen('http://finance.yahoo.com/q?s='+stocklist).read() soup = BeautifulSoup(optionsUrl) stocksymbo...
0
2016-06-10T20:07:42Z
37,763,947
<p>I would recommend you to use <a href="http://pandas-datareader.readthedocs.io/en/latest/remote_data.html#yahoo-finance" rel="nofollow">pandas-datareader</a>, which is designed for the things you are going to do.</p> <p>Here is a small demo:</p> <pre><code>from datetime import datetime import pandas_datareader.data...
0
2016-06-11T12:52:58Z
[ "python", "pandas" ]
Convert to directed graph to undirected graph in Python igraph
37,756,415
<p>I am attempting to draw an undirected graph in iGraph, but the graph I draw seems to have little arrows on it still. Is it possible to convert the directed graph object to an undirected graph object, so that the arrows are gone?</p> <p><strong>Here's my code:</strong></p> <pre><code>import igraph import cairo impo...
0
2016-06-10T20:09:26Z
37,756,445
<p>As documented here: <a href="http://igraph.org/python/doc/igraph.GraphBase-class.html" rel="nofollow">http://igraph.org/python/doc/igraph.GraphBase-class.html</a></p> <p>There are functions:</p> <pre><code>to_directed() to_undirected() </code></pre> <p>Depending on which way you want to go (it isn't clear to me f...
1
2016-06-10T20:11:41Z
[ "python", "graph-theory", "igraph" ]
Query a multi-level JSON object stored in MySQL
37,756,438
<p>I have a JSON column in a MySQL table that contains a multi-level JSON object. I can access the values at the first level using the function <code>JSON_EXTRACT</code> but I can't find how to go over the first level. </p> <p>Here's my MySQL table: </p> <pre><code>CREATE TABLE ref_data_table ( `id` INTEGER(11) A...
0
2016-06-10T20:11:13Z
37,756,629
<p>Try this:</p> <pre><code>'$.data_sources.provider3' SELECT symbol, JSON_EXTRACT(metadata, '$.data_sources.provider3) FROM ref_data_table WHERE symbol = 'VXX'; </code></pre>
2
2016-06-10T20:22:34Z
[ "python", "mysql", "sql", "json" ]
Query a multi-level JSON object stored in MySQL
37,756,438
<p>I have a JSON column in a MySQL table that contains a multi-level JSON object. I can access the values at the first level using the function <code>JSON_EXTRACT</code> but I can't find how to go over the first level. </p> <p>Here's my MySQL table: </p> <pre><code>CREATE TABLE ref_data_table ( `id` INTEGER(11) A...
0
2016-06-10T20:11:13Z
37,756,780
<p>the JSON_EXTRACT method in MySql supports that, the '$' references the JSON root, whereas periods reference levels of nesting. in this JSON example </p> <pre><code>{ "key": { "value": "nested_value" } } </code></pre> <p>you could use JSON_EXTRACT(json_field, '$.key.value') to get "nested_value"</p>...
0
2016-06-10T20:34:06Z
[ "python", "mysql", "sql", "json" ]
No module named tensor flow -- iPython notebook
37,756,452
<p>I understand this may be an old question, but still I cannot find solution from off-the-shelf Q$A. Here is the problem:</p> <p>I am following <strong>Udacity</strong> "Machine Learning" and its assignments, and need use <strong><em>iPythonNotebook &amp; tensorflow</em></strong>. Details : <a href="https://github.co...
0
2016-06-10T20:12:12Z
37,756,701
<p>This is likely due to an anemic environment variable, one of the library path class. I don't know how iPythonNotebook denotes the libraries it will search for files (say, $LD_LIBRARY_PATH), but I believe that you have to find it (a list of paths to libraries) and add the root directory of TensorFlow.</p>
0
2016-06-10T20:28:10Z
[ "python", "machine-learning", "tensorflow", "anaconda", "jupyter-notebook" ]
No module named tensor flow -- iPython notebook
37,756,452
<p>I understand this may be an old question, but still I cannot find solution from off-the-shelf Q$A. Here is the problem:</p> <p>I am following <strong>Udacity</strong> "Machine Learning" and its assignments, and need use <strong><em>iPythonNotebook &amp; tensorflow</em></strong>. Details : <a href="https://github.co...
0
2016-06-10T20:12:12Z
37,757,963
<p>After I tried Anaconda-installation (I was using the other installation methods, which are all shown in the link below) <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#anaconda-installation" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/ten...
1
2016-06-10T22:26:59Z
[ "python", "machine-learning", "tensorflow", "anaconda", "jupyter-notebook" ]
No module named tensor flow -- iPython notebook
37,756,452
<p>I understand this may be an old question, but still I cannot find solution from off-the-shelf Q$A. Here is the problem:</p> <p>I am following <strong>Udacity</strong> "Machine Learning" and its assignments, and need use <strong><em>iPythonNotebook &amp; tensorflow</em></strong>. Details : <a href="https://github.co...
0
2016-06-10T20:12:12Z
39,399,762
<p>More than likely either Tensorflow is not installed in the right Python environment of Conda or not installed at all. Follow the below steps.</p> <pre><code>$ conda create -n tensorflow python=3.5 </code></pre> <p>Once that is done, need to activate that as below.</p> <pre><code>$ source activate tensor flow </co...
0
2016-09-08T20:35:15Z
[ "python", "machine-learning", "tensorflow", "anaconda", "jupyter-notebook" ]
Droping lower order terms of a polynomial with Sympy
37,756,478
<p>Say we have this function,</p> <p>f = poly(2*x**2 + 3*x - 1,x)</p> <p>How would one go about dropping terms of degree n or lower. </p> <p>For instance if n = 1 the result would be 2*x**2. </p>
4
2016-06-10T20:13:23Z
37,757,327
<pre><code>from sympy import poly from sympy.abc import x p = poly(x ** 5 + 2 * x ** 4 - x ** 3 - 2 * x ** 2 + x) print(p) n = 2 new_p = poly(sum(c * x ** i[0] for i, c in p.terms() if i[0] &gt; n)) print(new_p) </code></pre> <p>Output:</p> <pre><code>Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') Poly(x**5...
4
2016-06-10T21:20:41Z
[ "python", "sympy" ]
Python I/O error: How do I fix this program for file paths with whitespace?
37,756,522
<p>When running the codes.</p> <pre><code>file_path = raw_input("Drag the text file here: ") file_path = file_path.strip() file_handle = open(file_path, 'r') for line in file_handle: print line </code></pre> <p>Output:</p> <pre><code>Drag the text file here: /Users/user_name/Desktop/white\ space/text.txt Traceb...
1
2016-06-10T20:17:01Z
37,756,902
<p>The immediate fix would be removing the escaped <code>'\\'</code> characters, <code>file_path.strip().replace('\\', '')</code> </p> <p>This should return <code>/Users/user_name/Desktop/white space/text.txt</code> which is a valid path for you to use.</p> <p>Look into <a href="https://docs.python.org/2/library/os.p...
1
2016-06-10T20:44:24Z
[ "python", "io", "whitespace", "filepath" ]
python pygame how to debounce a button?
37,756,523
<p>so im building a pi based robot. It uses a ps3 controller for input. When the X button is pressed, it takes a photo. For some reason, it takes around 5 shots at a time. Is there a way to bounce the input so it only recognises one press?</p> <p>I'm assuming it's registering multiple presses each time... Part of the ...
0
2016-06-10T20:17:03Z
37,756,886
<p>What seems to be happening is that the X button stays down for multiple frames. Some other events might happen during this time, causing a call to <code>take_picture()</code> in your code for every frame. To fix this, you can either call <code>take_picture()</code> only on <code>JOYBUTTONUP</code> (when the button i...
1
2016-06-10T20:43:41Z
[ "python", "pygame" ]
pyspark: keep a function in the lambda expression
37,756,549
<p>I have the following working code:</p> <pre><code>def replaceNone(row): myList = [] row_len = len(row) for i in range(0, row_len): if row[i] is None: myList.append("") else: myList.append(row[i]) return myList rdd_out = rdd_in.map(lambda row : replaceNone(row)) </code></pre> <p>Here <c...
-1
2016-06-10T20:18:02Z
37,756,878
<p>I'm not sure what your goal is. It seems like you're jsut trying to replace all the <code>None</code> values in each row in <code>rdd_in</code> with empty strings, in which case you can use a list comprehension:</p> <p><code>rdd_out = rdd_in.map(lambda row: [r if r is not None else "" for r in row])</code></p> <p>...
1
2016-06-10T20:43:15Z
[ "python", "apache-spark", "add", "pyspark" ]
Loop dictionary in ansible template
37,756,586
<p>I'm trying to loop a dictionary through an ansible template using jinja2 to create a number of datasources but receive this error <code>[{'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'value'", 'failed': True}]}</code></p> <p>When running a debug task it does get ...
0
2016-06-10T20:20:13Z
37,757,074
<p>In Jinja, when <code>databases</code> is a dictionary, <code>for items in databases</code> will (as in Python) iterate over the <em>keys</em> of the dictionary, not its key/value pairs. Thus, in your template, <code>item.value</code> (which I'm assuming is meant to be <code>items.value</code>) should be <code>datab...
1
2016-06-10T20:59:13Z
[ "python", "ansible", "jinja2" ]
Loop dictionary in ansible template
37,756,586
<p>I'm trying to loop a dictionary through an ansible template using jinja2 to create a number of datasources but receive this error <code>[{'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'value'", 'failed': True}]}</code></p> <p>When running a debug task it does get ...
0
2016-06-10T20:20:13Z
37,760,368
<p>You can achieve your goal by modifying your jinja2 template and task like this:</p> <p><strong>Jinja2 Template:</strong></p> <pre><code>&lt;resource name="{{ databases[item].db_resource }}" auth="container" type="javax.sql.datasource" maxtotal="{{ databases[item].db_maxconn }}" maxidle="{{ databases[item].db_maxi...
1
2016-06-11T05:40:00Z
[ "python", "ansible", "jinja2" ]
Arranging data in an text document using python
37,756,609
<p>I have a text file called <code>data.txt</code> which contains the following information in it </p> <pre><code>03/05/2016 11:00 50 03/05/2016 11:11 10 03/05/2016 11:20 30 03/05/2016 11:33 40 03/05/2016 11:40 40 03/05/2016 11:50 50 03/05/2016 11:60 70 03/05/2016 12:00 25 03/05/2016 12:10 69 03/05/2016 12:12...
-2
2016-06-10T20:21:43Z
37,757,501
<p>In case it helps you at all, here's the most compact form of my debugging run. Your original code works fine for me, but this may help you diagnose your problem.</p> <pre><code>from collections import Counter import re with open('data.txt') as f: res = sum((Counter({x.group(1): int(x.group(2))}) ...
0
2016-06-10T21:37:32Z
[ "python", "python-2.7" ]
Python querying mysql iteratively
37,756,625
<p>I have a list of column names that I want to pull from a mysql database. It is good practice to loop through it and query each time? </p> <p>When I do this, sometimes/randomly it seems to hang; when I restart the script, it hangs at different iterations. Was wondering whether this is bad practice to do in the first...
0
2016-06-10T20:22:27Z
37,756,767
<p>It's very odd to query individual columns one at a time, since you won't be able to relate the values in one column to another. Unless your table is a grab-bag of unrelated data (not really records, i.e. your table is not at all normalized) this will remove all meaning from the data. If you're trying to deal with d...
2
2016-06-10T20:33:10Z
[ "python", "mysql", "sql", "database", "mysql-python" ]
Python querying mysql iteratively
37,756,625
<p>I have a list of column names that I want to pull from a mysql database. It is good practice to loop through it and query each time? </p> <p>When I do this, sometimes/randomly it seems to hang; when I restart the script, it hangs at different iterations. Was wondering whether this is bad practice to do in the first...
0
2016-06-10T20:22:27Z
37,757,530
<p>Try something like this...not tested:</p> <pre><code>cnx = mysql.connector.connect(user='user', password='pw', host='ip_here') cursor.execute('SELECT * FROM database.`table_name`') iValues = cursor.fetchall() cursor.close cnx.close #for i,j in enumerate(iValues): # if i == 0: # extractedValues = iValues # ...
0
2016-06-10T21:40:37Z
[ "python", "mysql", "sql", "database", "mysql-python" ]
Python querying mysql iteratively
37,756,625
<p>I have a list of column names that I want to pull from a mysql database. It is good practice to loop through it and query each time? </p> <p>When I do this, sometimes/randomly it seems to hang; when I restart the script, it hangs at different iterations. Was wondering whether this is bad practice to do in the first...
0
2016-06-10T20:22:27Z
37,757,635
<p>You should try this, it will get only the columns you need, each together in a single row with only one select:</p> <pre><code> import mysql.connector import numpy as np cnx = mysql.connector.connect(user='user', password='pw', host='ip_here') cursor.execute('SELECT ' + ['`' + col + '`' for col in columnLi...
0
2016-06-10T21:53:32Z
[ "python", "mysql", "sql", "database", "mysql-python" ]