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
Python NameError: name 'encrypt' is not defined
38,631,474
<p>When I attempt to run this it says NameError: name 'encrypt' is not defined.</p> <pre><code>MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in "encrypt" 'e' 'decrypt' 'd'.split(): r...
0
2016-07-28T08:52:31Z
38,631,721
<p>Gotcha! <code>input</code> tries to eval your input (as such, it's named very misleadingly). Use <code>raw_input</code> for capturing user's wishes in string format.</p> <p>Basically what <code>input</code> does is it takes <code>raw_input</code> and pipes it to <code>eval</code>: now you're trying to evaluate a st...
1
2016-07-28T09:03:49Z
[ "python", "nameerror" ]
Python NameError: name 'encrypt' is not defined
38,631,474
<p>When I attempt to run this it says NameError: name 'encrypt' is not defined.</p> <pre><code>MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in "encrypt" 'e' 'decrypt' 'd'.split(): r...
0
2016-07-28T08:52:31Z
38,632,362
<pre><code>MAX_KEY_SIZE = 26 def getMode(): while True: print ('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in "encrypt" 'e' 'decrypt' 'd'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d"...
0
2016-07-28T09:29:51Z
[ "python", "nameerror" ]
Python NameError: name 'encrypt' is not defined
38,631,474
<p>When I attempt to run this it says NameError: name 'encrypt' is not defined.</p> <pre><code>MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in "encrypt" 'e' 'decrypt' 'd'.split(): r...
0
2016-07-28T08:52:31Z
38,632,416
<p>Expanding on <a href="https://stackoverflow.com/questions/38631474/38631721#38631721">pogo's answer</a>, which is correct...</p> <p>What surprised me (and apparently many others) is that the cluster of strings in the <code>if mode in ...:</code> line is <em>not</em> a syntax error.</p> <pre><code>if mode in "encry...
0
2016-07-28T09:31:42Z
[ "python", "nameerror" ]
how to paging from top 99 rows in sqlalchemy?
38,631,475
<p>select *from (select *from new_count_goods_details limit 99) sub limit 10 offset 90;</p> <p>how to achieve the mysql statement by sqlalchemy?</p> <p>this is my code:</p> <pre><code> limit_subquery = q.filter(StyleList.add_time &gt;= yesterday_18).\ filter(StyleList.add_time &lt;= today_18).\ ...
0
2016-07-28T08:52:34Z
38,632,661
<p>You need to select from subquery</p> <pre><code>q = session.query(limit_subquery).offset((p-1)*ps).limit(ps) </code></pre>
0
2016-07-28T09:41:55Z
[ "python", "sqlalchemy" ]
Python third party Module global import
38,631,493
<p>i'm currently into learning a bit of python and i want to import the paperclip third party module into my python file.</p> <p>Yes, i already installed the pyperclip module with <code>pip install pyperclip</code>.</p> <p>if i create a file on my desktop, i get an error which says <code> Traceback (most recent cal...
0
2016-07-28T08:53:17Z
38,631,601
<p>You can do this :</p> <p>pip3.5 install paperclip</p> <p>pyperclip is install but not paperclip</p>
0
2016-07-28T08:58:32Z
[ "python", "import", "module" ]
Python third party Module global import
38,631,493
<p>i'm currently into learning a bit of python and i want to import the paperclip third party module into my python file.</p> <p>Yes, i already installed the pyperclip module with <code>pip install pyperclip</code>.</p> <p>if i create a file on my desktop, i get an error which says <code> Traceback (most recent cal...
0
2016-07-28T08:53:17Z
38,632,431
<p>Found the problem. </p> <p>The <code>pip install</code>automatically used <code>pip3.5 install</code> <br/> whereas <code>python test.py</code>didn't use <code>python3.5 test.py</code></p> <p>Thank you @Bakurìu </p> <p>Is there a way i can define <code>python3.5</code>as <code>python</code>?</p>
0
2016-07-28T09:32:12Z
[ "python", "import", "module" ]
Python 3.4.4 - pip collection error
38,631,525
<p>I would really appreciate some help on the below query - I've been trying to get pip to work for the best of a day and really struggling. </p> <p>Regardless of which module I try to install I keep getting a "Could not find a version that satisfies the requirement openpyxl (from version s: ) No matching distributio...
0
2016-07-28T08:54:47Z
38,631,627
<p>Have you tried to check the internet connection? From your screenshot, seems like you cannot access the URL as follow:.<br> <a href="https://pypi.python.org/simple/openpyxl/" rel="nofollow">https://pypi.python.org/simple/openpyxl/</a></p>
0
2016-07-28T08:59:58Z
[ "python", "pip" ]
How can I create a word that does not contain the previous letter contained in the word?
38,631,534
<p>I see the point of the question stays in the first <code>elif</code>:</p> <pre><code>import random as rnd vowels="aeiou" consonants="bcdfghlmnpqrstvz" alphabet=vowels+consonants vocabulary={} index=0 word="" positions=[] while index&lt;5: random_lenght=rnd.randint(2,5) while len(word)&lt;random_lenght: ...
-1
2016-07-28T08:55:14Z
38,633,158
<p>What you want should be something like this (based on your implementation) :</p> <pre><code>import random as rnd vowels="aeiou" consonants="bcdfghlmnpqrstvz" alphabet=vowels+consonants vocabulary={} index=0 word="" positions=[] while index&lt;5: random_lenght=rnd.randint(2,5) while len(word)&lt;random_len...
0
2016-07-28T10:02:27Z
[ "python", "vocabulary" ]
How can I turn csv file row column value into (row, column, value) in Python
38,631,570
<p><a href="http://i.stack.imgur.com/Yvgkg.png" rel="nofollow">for example, I read this 3x3 csv file.</a></p> <pre><code> 01 02 03 01 | 11 | 22 | 33 | 02 | 44 | 55 | 66 | 03 | 77 | 88 | 99 | </code></pre> <p><a href="http://i.stack.imgur.com/JzCkm.png" rel="nofollow">Then ,I want to output a new textfile...
0
2016-07-28T08:56:57Z
38,632,180
<p>suppose you have example.csv file like this:</p> <pre><code>11|22|33 44|55|66 77|88|99 </code></pre> <hr> <pre><code>with open("example.csv") as handler: for r,l in enumerate(handler): for col, e in enumerate(l.split('|')): print('row: %s, col %s, value: %s' % (r+1, col+1, e)) </code></pre...
0
2016-07-28T09:22:49Z
[ "python", "python-2.7", "csv", "row" ]
How can I turn csv file row column value into (row, column, value) in Python
38,631,570
<p><a href="http://i.stack.imgur.com/Yvgkg.png" rel="nofollow">for example, I read this 3x3 csv file.</a></p> <pre><code> 01 02 03 01 | 11 | 22 | 33 | 02 | 44 | 55 | 66 | 03 | 77 | 88 | 99 | </code></pre> <p><a href="http://i.stack.imgur.com/JzCkm.png" rel="nofollow">Then ,I want to output a new textfile...
0
2016-07-28T08:56:57Z
38,634,200
<pre><code>with open("t.csv","rb") as open_file:#Read the file my_file = open_file.read().decode('utf-8','ignore') data = my_file.splitlines() data = [r.split('|') for r in data] row_len = len(data) for i,j in enumerate(data): col_len = len(data[0]) start_index = 0 while s...
0
2016-07-28T10:49:49Z
[ "python", "python-2.7", "csv", "row" ]
Can you extend SQLAlchemy Query class and use different ones in the same session?
38,631,651
<p>I am using SQL Alchemy ORM and have some classes/tables each of which may have some custom queries. Let's say, I want to add to table <code>Fruit</code> the filtering possibility called <code>with_seed</code> giving me only fruits with seeds, and to table <code>Cutlery</code> the filtering method <code>is_sharp</cod...
1
2016-07-28T09:01:12Z
38,655,960
<p>You can pass session to Query constructor</p> <pre><code>CustomQuery(entities=[Fruit], session=session).with_seed().delete(synchronize_session='fetch') </code></pre>
0
2016-07-29T10:01:32Z
[ "python", "orm", "sqlalchemy" ]
while true loop doesn't work inside another in python
38,631,668
<p>I have a <code>while true</code> loop (code below) within another loop. I want to check if you clicked on a button and if so, change the cursor into an image that I have imported before. I tried to do that by hiding the cursor and let an image follow it. But when I run this, it hides the cursor draws the image where...
2
2016-07-28T09:01:47Z
38,633,478
<p>Change your code to this:</p> <pre><code>while True: for event in pygame.event.get(): if event.type == MOUSEBUTTONUP: mousex, mousey = pygame.mouse.get_pos() if mousex &gt; 100 and mousex &lt; 200 and mousey &gt; 50 and mousey &lt; 100: # a button on my screen p...
1
2016-07-28T10:15:47Z
[ "python", "while-loop" ]
Running a timer for function which will be called later (python)
38,631,717
<pre><code>def child_thread(i): global lock while True: try: lock.acquire() f1() f2() f3() finally : lock.release() thread1 = threading.Thread(target=child_thread, args=(0,)) thread1.start() </code></pre> <p>here i need a...
0
2016-07-28T09:03:40Z
38,631,841
<p>The function will be call after 30.0 seconds</p> <pre><code>from threading import Timer def hello(): print "hello, world" t = Timer(30.0, hello) t.start() </code></pre>
0
2016-07-28T09:08:30Z
[ "python" ]
Python extract variables from an imported file
38,632,067
<p>I've 3 files. One is for defining the variables and other two contain the required modules.</p> <p><strong>variable.py</strong></p> <pre><code>my_var = "" </code></pre> <p><strong>test.py</strong></p> <pre><code>import variable def trial(): variable.my_var = "Hello" </code></pre> <p><strong>main.py</strong...
1
2016-07-28T09:17:30Z
38,633,208
<p>What you want to achieve is not possible. <code>from MODULE import *</code> imports all the variables names and the values into your namespace, but not the variables themselves. The variables are allocated in your local namespace and changing their value is therefore not reflected onto their origin. However, changes...
2
2016-07-28T10:04:09Z
[ "python", "import" ]
Hi, I am trying to add weekstart column
38,632,209
<p>In my current table I am having date column and from that column I am able to find out weekday.By using to_timedelta I have created week_start column but it is not giving correct date. Here the code is:</p> <pre><code>final_data['weekday'] = final_data['DateOfInvoice'].dt.weekday final_data['Weekstart'] = final_da...
1
2016-07-28T09:23:57Z
38,632,260
<p>IIUC you can construct a TimedeltaIndex and subtract from the other column:</p> <pre><code>In [152]: df['weekstart'] = df['Date'] - pd.TimedeltaIndex(df['weekday'], unit='D') df Out[152]: Date weekday weekstart 0 2016-07-23 5 2016-07-18 </code></pre> <p>in fact the weekday column is unnecessary:<...
1
2016-07-28T09:25:38Z
[ "python", "pandas" ]
How to set parameters of the Adadelta Algorithm in Tensorflow correctly?
38,632,536
<p>I've been using Tensorflow for regression purposes. My neural net is very small with 10 input neurons, 12 hidden neurons in a single layer and 5 output neurons.</p> <ul> <li>activation function is relu</li> <li>cost is square distance between output and real value</li> <li>my neural net trains correctly with other ...
1
2016-07-28T09:36:13Z
38,636,092
<h3>Short answer: don't use Adadelta</h3> <p>Very few people use it today, you should instead stick to:</p> <ul> <li><code>tf.train.MomentumOptimizer</code> with <code>0.9</code> momentum is very standard and works well. The drawback is that you have to find yourself the best learning rate.</li> <li><code>tf.train.RM...
1
2016-07-28T12:15:58Z
[ "python", "neural-network", "tensorflow" ]
Encode IP address using all printable characters in Python 2.7.x
38,632,580
<p>I would like to encode an IP address in as short a string as possible using all the printable characters. According to <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" rel="nofollow">https://en.wikipedia.org/wiki/ASCII#Printable_characters</a> these are codes 20hex to 7Ehex.</p> <p>For example:</p...
4
2016-07-28T09:38:18Z
38,633,276
<p>An IP stored in binary is 4 bytes.</p> <p>You can encode it in 5 printable ASCII characters using Base85.</p> <p>Using more printable characters won't be able to shorten the resulting string more than that.</p> <pre><code>import ipaddress import base64 def encode(ip): ip_as_integer = int(ipaddress.IPv4Addres...
5
2016-07-28T10:06:54Z
[ "python" ]
Encode IP address using all printable characters in Python 2.7.x
38,632,580
<p>I would like to encode an IP address in as short a string as possible using all the printable characters. According to <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" rel="nofollow">https://en.wikipedia.org/wiki/ASCII#Printable_characters</a> these are codes 20hex to 7Ehex.</p> <p>For example:</p...
4
2016-07-28T09:38:18Z
39,681,744
<p>I found this question looking for a way to use base85/ascii85 on python 2. Eventually I discovered a couple of projects available to install via pypi. I settled on one called <code>hackercodecs</code> because the project is specific to encoding/decoding whereas the others I found just offered the implementation as...
1
2016-09-24T23:00:56Z
[ "python" ]
Can I run multiple threads in a single heroku (python) dyno?
38,632,621
<p>Does the <code>threading</code> module work when running a single dyno on heroku? eg:</p> <pre><code>import threading import time import random def foo(x, s): time.sleep(s) print ("%s %s %s" % (threading.current_thread(), x, s)) for x in range(4): threading.Thread(target=foo, args=(x, random.rand...
1
2016-07-28T09:40:06Z
38,729,726
<p>Yes. This works fine =) Just tested on the latest Python 3 release. You can easily test this on Heroku yourself.</p> <p>Heroku dynos are using virtual CPU cores, but threading still works fine.</p> <p><strong>EDIT</strong>: Here's my Heroku logs</p> <pre><code>2016-08-02T20:18:35.040230+00:00 heroku[test.1]: Stat...
1
2016-08-02T20:19:16Z
[ "python", "multithreading", "heroku" ]
Parsing a json nested dictionary in python
38,632,687
<p>I need to reach the value "y "of "B" in result.</p> <pre><code>{ "Response": { "Result": [2] 0: { "A": "x" "B": "y" "C": "z" } ...
-2
2016-07-28T09:43:02Z
38,632,782
<p>The key <code>0</code> is not under <code>"Result"</code> you should use <code>['Response'][0]['B']</code></p>
2
2016-07-28T09:47:34Z
[ "python", "json" ]
Pandas: selecting multiple groups for inset plot
38,632,724
<p>I have a group data frame (<code>grouped_df</code>) used for plotting in the following way:</p> <pre><code>grouped_df[['col1','col2','col3']].sum().plot(kind='bar') </code></pre> <p>resulting in the expected plot, which contains a group-wise sum for all three columns. However, for some of the groups these sums are...
0
2016-07-28T09:45:03Z
38,633,133
<p>Is this what you are looking for?</p> <pre><code>def apply_cut_off(x1,x2,x3, CUT_OFF): if x1 &lt; CUT_OFF: return False elif x2 &lt; CUT_OFF: return False elif x3 &lt; CUT_OFF: return False return True grouped_sum = grouped_df[['col1','col2','col3']].sum() cutoff_df = grouped_sum[ grouped_sum.ap...
2
2016-07-28T10:01:35Z
[ "python", "pandas" ]
XlsxWriter: add color to cells
38,632,753
<p>I try to write dataframe to xlsx and give color to that. I use</p> <pre><code>worksheet.conditional_format('A1:C1', {'type': '3_color_scale'}) </code></pre> <p>But it's not give color to cell. And I want to one color to this cells. I saw <code>cell_format.set_font_color('#FF0000')</code> but there is don't specify...
1
2016-07-28T09:46:11Z
38,633,106
<p>The problem is that <code>worksheet.write('A1:C1', 'Ray', format)</code> is used only to write a single cell. A possible solution to write more cells in a row, is use <code>write_row()</code>.</p> <pre><code>worksheet.write_row("A1:C1", ['Ray','Ray2','Ray3'], format) </code></pre> <p>Remember that <strong>write_r...
1
2016-07-28T10:00:27Z
[ "python", "pandas", "xlsxwriter" ]
Python 3: PyQt: Make checkbox disabled + not grayed out + display tooltip
38,632,825
<p>The only way I found to do this is <a href="http://stackoverflow.com/questions/35190259/how-to-make-qcheckbox-readonly-but-not-grayed-out">here: How to make QCheckBox readonly, but not grayed-out</a>. This, however, disables mouse interactions with the control. But I need the tooltip to be displayed when mouse is ov...
0
2016-07-28T09:49:04Z
38,667,489
<pre><code>#If your are not expecting this answer, sorry. self.checkBox = QtGui.QCheckBox() self.checkBox.setEnabled (False) self.checkBox.setToolTip ('my checkBox') </code></pre>
0
2016-07-29T21:06:22Z
[ "python", "checkbox", "pyqt", "pyqt4", "disabled-control" ]
Python 3: PyQt: Make checkbox disabled + not grayed out + display tooltip
38,632,825
<p>The only way I found to do this is <a href="http://stackoverflow.com/questions/35190259/how-to-make-qcheckbox-readonly-but-not-grayed-out">here: How to make QCheckBox readonly, but not grayed-out</a>. This, however, disables mouse interactions with the control. But I need the tooltip to be displayed when mouse is ov...
0
2016-07-28T09:49:04Z
38,752,619
<p>If I've understood correctly, this is what you'd be asking for, a disabled checkbox showing tooltips:</p> <pre><code> import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): ...
0
2016-08-03T20:01:39Z
[ "python", "checkbox", "pyqt", "pyqt4", "disabled-control" ]
Shodan. Get all open ports for a net
38,632,844
<p>I want to get all the open ports for a network with Shodan (I know I can use <code>nmap</code> but I want to carry this out with Shodan).</p> <p>The problem is that the website only shows the "TOP Services", and I would like to be given all the services.</p> <p>For example, for this net: 195.53.102.0/24 I am given...
0
2016-07-28T09:49:58Z
38,667,275
<p>When you use the api.search() Shodan search for a service banner. And a service banner can only have 1 port. </p> <p>So, if you want to return all the port that a host can have, you should use api.host() </p> <p>For example, </p> <pre><code>import shodan SHODAN_API_KEY = "XXXXXXXXXXXXXXXXXXXXXXx" api = shodan.S...
0
2016-07-29T20:50:56Z
[ "python", "cidr", "port-scanning", "shodan" ]
Sublime Text plugin - how to find all regions in selection
38,632,861
<p>How to find all regions in selection (regeon type too)? If we calling this method:</p> <pre><code>def chk_links(self,vspace): url_regions = vspace.find_all("https?://[^\"'\s]+") i=0 for region in url_regions: cl = vspace.substr(region) code = self.get_response(cl) vspace.add_reg...
0
2016-07-28T09:50:56Z
38,644,598
<p>The <code>Selection</code> class (returned by <code>View.sel()</code>) is essentially just a list of <code>Region</code> objects that represent the current selection. A <code>Region</code> can be empty, so the list always contains a least one region with a length of 0.</p> <p>The only <a href="http://www.sublimetex...
1
2016-07-28T18:55:04Z
[ "python", "sublimetext2", "sublimetext3", "sublimetext", "sublime-text-plugin" ]
Python function with default argument inside loop
38,632,891
<pre><code>for i in range(5): def test(i=i): print(i) test() test() test() test() test() </code></pre> <p>This prints 4 every time? Can someone help me understanding this.</p>
2
2016-07-28T09:52:01Z
38,632,942
<p>You redefine the <code>test</code> 4 times:</p> <p>same as:</p> <pre><code>#define test def test(i = 0): print(i) #redefine test def test(i = 1): print(i) #redefine test def test(i = 2): print(i) #redefine test def test(i = 3): print(i) #redefine test def test(i = 4): print(i) </code></pre>...
6
2016-07-28T09:54:09Z
[ "python", "python-2.7" ]
Python function with default argument inside loop
38,632,891
<pre><code>for i in range(5): def test(i=i): print(i) test() test() test() test() test() </code></pre> <p>This prints 4 every time? Can someone help me understanding this.</p>
2
2016-07-28T09:52:01Z
38,632,965
<p>The function <code>test</code> is redefined every iteration of the loop.</p> <p>By the time the loop is done, <code>test</code> is simply:</p> <pre><code>def test(i=4): print(i) </code></pre>
3
2016-07-28T09:55:26Z
[ "python", "python-2.7" ]
Python function with default argument inside loop
38,632,891
<pre><code>for i in range(5): def test(i=i): print(i) test() test() test() test() test() </code></pre> <p>This prints 4 every time? Can someone help me understanding this.</p>
2
2016-07-28T09:52:01Z
38,633,127
<p>first your script completes for loop, by the end of for loop, i value is 4</p> <p>Then how many ever times, you can call <code>test()</code>, it will print 4</p> <p>I have added few prints to your code, so that you can understand the flow better</p> <pre><code>for i in range(5): print(i) def test(i=i): ...
2
2016-07-28T10:01:10Z
[ "python", "python-2.7" ]
Can not load the json file of urls in python
38,633,009
<p>I tried to make a dict with python , I try to retrieve data via the url however json error what is wrong ? I use python 2.7.6</p> <pre><code>import json import urllib json_string = 'http://localhost/csv/taxo.json' parsed_json = json.loads(json_string) print(parsed_json['genus']) </code></pre> <p>This error</p> <...
-1
2016-07-28T09:57:06Z
38,633,095
<p><code>json_string</code> is not a <code>json</code> string. It is simply a URL...</p> <p>You should get the <strong>content</strong> of this URL with one of the HTTP modules that are available for Python.</p> <p>You should do it the other way around. The <code>requests</code> module gives you the option to do a GE...
3
2016-07-28T10:00:11Z
[ "python", "python-2.7" ]
Can not load the json file of urls in python
38,633,009
<p>I tried to make a dict with python , I try to retrieve data via the url however json error what is wrong ? I use python 2.7.6</p> <pre><code>import json import urllib json_string = 'http://localhost/csv/taxo.json' parsed_json = json.loads(json_string) print(parsed_json['genus']) </code></pre> <p>This error</p> <...
-1
2016-07-28T09:57:06Z
38,633,173
<p>First you need to get the content of the url, for example with <strong>urllib</strong> try sth like this, but it won't work for python3:</p> <pre><code>import json import urllib json_url = 'http://localhost/csv/taxo.json' parsed_json = json.load(urllib.urlopen(json_url )) print(parsed_json['genus']) </code></pre> ...
1
2016-07-28T10:02:59Z
[ "python", "python-2.7" ]
Can not load the json file of urls in python
38,633,009
<p>I tried to make a dict with python , I try to retrieve data via the url however json error what is wrong ? I use python 2.7.6</p> <pre><code>import json import urllib json_string = 'http://localhost/csv/taxo.json' parsed_json = json.loads(json_string) print(parsed_json['genus']) </code></pre> <p>This error</p> <...
-1
2016-07-28T09:57:06Z
38,633,416
<p>I think you want to do this:</p> <p>First download the webpage:</p> <pre><code>from urllib import urlopen response_object = urlopen('http://localhost/csv/taxo.json') </code></pre> <p>After convert to string:</p> <pre><code>response_string = response_object.read() </code></pre> <p>Then convert to dictionary:</p>...
0
2016-07-28T10:12:53Z
[ "python", "python-2.7" ]
Scripting in logstash
38,633,063
<p>Is it possible to do python like scripting in logstash? I can import the csv data into elasticsearch using logstash. But I need to use update API instead of simply indexing all rows.</p> <p>Here is my sample csv file...</p> <pre><code>vi /tmp/head.txt "Home","Home-66497273a5a83c99","Spice Xlife 350, 3.5inch Androi...
7
2016-07-28T09:59:00Z
38,648,184
<p><code>elasticsearch</code> output plugin supports script parameters:</p> <pre><code>output { elasticsearch { action =&gt; "update" hosts =&gt; ["172.17.0.1"] index =&gt; "logstash-%{+YYYY.MM.dd}" workers =&gt; 1 script =&gt; "&lt;your script here&gt;" script_type ...
1
2016-07-28T23:12:43Z
[ "python", "elasticsearch", "groovy", "logstash" ]
Scripting in logstash
38,633,063
<p>Is it possible to do python like scripting in logstash? I can import the csv data into elasticsearch using logstash. But I need to use update API instead of simply indexing all rows.</p> <p>Here is my sample csv file...</p> <pre><code>vi /tmp/head.txt "Home","Home-66497273a5a83c99","Spice Xlife 350, 3.5inch Androi...
7
2016-07-28T09:59:00Z
38,800,490
<p>The event is passed to the script in your output using the <code>event</code> variable name (by default, but you can change it using the <code>script_var_name</code> setting).</p> <p>So the script in your output needs to account for it.</p> <pre><code> script =&gt; "ctx._source.parent = (ctx._source.parent ?: [...
1
2016-08-06T04:17:30Z
[ "python", "elasticsearch", "groovy", "logstash" ]
Scripting in logstash
38,633,063
<p>Is it possible to do python like scripting in logstash? I can import the csv data into elasticsearch using logstash. But I need to use update API instead of simply indexing all rows.</p> <p>Here is my sample csv file...</p> <pre><code>vi /tmp/head.txt "Home","Home-66497273a5a83c99","Spice Xlife 350, 3.5inch Androi...
7
2016-07-28T09:59:00Z
38,912,079
<p>Since you have working python script, maybe that will be useful ? <a href="https://www.elastic.co/guide/en/elasticsearch/plugins/current/lang-python.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/plugins/current/lang-python.html</a></p> <p>Regarding update nr 2 - I think the error can be fixed b...
0
2016-08-12T07:17:37Z
[ "python", "elasticsearch", "groovy", "logstash" ]
Django sort by Articles with most similar tags
38,633,110
<p>I have a model for Articles and Tags, using filter for suggestions. </p> <p>The article tags as <code>tags = article.tags.all()</code> then filter <code>Article.objects.filter(tags__in=tags)[:5]</code> what I'd like is to add a sort by tags similar.</p> <p>Model for Article and Tags</p> <pre><code>class Article(m...
0
2016-07-28T10:00:35Z
38,635,533
<p>I would suggest to use app <a href="http://django-taggit.readthedocs.io/en/latest/index.html" rel="nofollow">django-taggit</a>. <code>TaggableManager</code> has method <code>similar_objects</code> which does exactly what you want.</p>
0
2016-07-28T11:51:08Z
[ "python", "django" ]
Arrange the multi-similar data efficiently
38,633,246
<p>The datafile showed here is the measuring record exported from instrument. </p> <p>I uploaded it <a href="https://drive.google.com/file/d/0B7FE0kxAL8kQSmxoMEhHUjV0VUk/view?usp=sharing" rel="nofollow">here</a>, anyone interested can download it. </p> <h3>Background</h3> <pre><code>Sample RECORD-1 FID1, FID2, f...
0
2016-07-28T10:05:46Z
38,639,897
<p>I think you are looking for something like this:</p> <pre><code>import pandas as pd # Whole datafile with several samples record inside with open("record.txt",'r') as f: mylist = f.read().splitlines() dataset = [] while True: try: ## The record for each sample length in 803 lines lines, ...
1
2016-07-28T14:53:12Z
[ "python", "arrays", "pandas", "dataframe" ]
Error while testing the raise of self-defined exceptions (using assertRaises())
38,633,263
<p>I am creating tests for a python project. The normal tests work just fine, however I want to test if in a certain condition my function raises a self-defined exception. Therefor I want to use assertRaises(Exception, Function). Any ideas?</p> <p>The function that raises the exception is:</p> <pre><code>def connect(...
1
2016-07-28T10:06:18Z
38,633,401
<p><code>assertRaises</code> expects to actually <a href="https://docs.python.org/3.4/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow"><em>perform</em> the call</a>. Yet, you already perform it by yourself, thereby throwing the error before <code>assertRaises</code> actually executes.</p> <pre><cod...
5
2016-07-28T10:12:12Z
[ "python", "exception" ]
Use base class's property/attribute as a table column?
38,633,319
<p>A game engine provides me with a <code>Player</code> class with a <code>steamid</code> property (coming from C++, this is just a basic example on what it would look like in Python):</p> <pre><code># game_engine.py class Player: def __init__(self, steamid): self.__steamid = steamid @property d...
8
2016-07-28T10:08:58Z
38,675,933
<p>this could be done using <a href="http://docs.sqlalchemy.org/en/latest/orm/mapping_styles.html#classical-mappings" rel="nofollow">classical mapping</a></p> <pre><code>from sqlalchemy import Column, Integer, Table from sqlalchemy.orm import mapper from sqlalchemy.ext.hybrid import hybrid_property class MyPlayer(Pl...
1
2016-07-30T16:09:32Z
[ "python", "python-3.x", "inheritance", "properties", "sqlalchemy" ]
Use base class's property/attribute as a table column?
38,633,319
<p>A game engine provides me with a <code>Player</code> class with a <code>steamid</code> property (coming from C++, this is just a basic example on what it would look like in Python):</p> <pre><code># game_engine.py class Player: def __init__(self, steamid): self.__steamid = steamid @property d...
8
2016-07-28T10:08:58Z
38,678,734
<p>This is simpler than you might expect. The solution below is roughly equivalent to the one from r-m-n, but more straightforward because it uses modern declarative mapping. There is no need for <code>@hybrid_property</code>, you can just inherit <code>steamid</code> from the parent class.</p> <pre><code># my_plugin....
2
2016-07-30T21:39:43Z
[ "python", "python-3.x", "inheritance", "properties", "sqlalchemy" ]
ZeroMQ: How to prioritise sockets in a .poll() method?
38,633,359
<p>Imagine the following code:</p> <pre><code>import threading, zmq, time context = zmq.Context() receivers = [] poller = zmq.Poller() def thread_fn(number: int): sender = context.socket(zmq.PUSH) sender.connect("tcp://localhost:%d" % (6666 + number)) for i in range(10): sender.send_string("messa...
4
2016-07-28T10:10:37Z
38,655,009
<blockquote> <p>Welcome to the Wild Worlds of (managed)-chaos,</p> <h2><code>A1:</code> Yes<sup><code>TL;DR</code> check <code>zmq.select()</code> in recent API / python wrapper</sup><br><code>A2:</code> Yes<sub><code>TL;DR</code> a must do part of the rigorous dependable system design</sub></h2> </blockquote> ...
2
2016-07-29T09:16:52Z
[ "python", "select", "zeromq" ]
pip install askbot error - Command "python setup.py egg_info" failed with error code 1
38,633,376
<p>I want to install askbot app (<a href="http://askbot.org/doc/install.html" rel="nofollow">http://askbot.org/doc/install.html</a>). But I encountered error during installation. </p> <p>I've did below actions.</p> <p>1) made virtual environment under ananconda (python 3.5.2 / ubuntu 14.04)</p> <p>2) installed djang...
1
2016-07-28T10:11:14Z
38,633,471
<p><a href="https://pypi.python.org/pypi/askbot/0.7.56" rel="nofollow">Askbot</a> is not compatible with python 3, which changes <code>print</code> from a statement like so:</p> <pre><code>print `Hello World` </code></pre> <p>into a function:</p> <pre><code>print('Hello world') </code></pre> <p>More about this chan...
2
2016-07-28T10:15:20Z
[ "python", "django", "askbot" ]
Unnamed error using Urllib2 and Beautiful soup
38,633,439
<p>The output of this code block always returns me the "except". No specific error is shown in my terminal. What am i doing wrong ? Any help is appreciated!</p> <pre><code>from bs4 import BeautifulSoup import csv import urllib2 # get page source and create a BeautifulSoup object based on it try: print("Fetching ...
0
2016-07-28T10:13:50Z
38,633,567
<blockquote> <p>"No specific error is shown in my terminal" </p> </blockquote> <p>That's because your <code>except</code> block is shadowing it. Either remove the <code>try/except</code> or print the exception in the <code>except</code> block:</p> <pre><code>try: . . . except Exception as ex: print(...
0
2016-07-28T10:19:47Z
[ "python", "python-2.7", "beautifulsoup", "urllib2", "scraper" ]
Unnamed error using Urllib2 and Beautiful soup
38,633,439
<p>The output of this code block always returns me the "except". No specific error is shown in my terminal. What am i doing wrong ? Any help is appreciated!</p> <pre><code>from bs4 import BeautifulSoup import csv import urllib2 # get page source and create a BeautifulSoup object based on it try: print("Fetching ...
0
2016-07-28T10:13:50Z
38,634,351
<p>You can use requests for getting the data.</p> <pre><code>from bs4 import BeautifulSoup import requests import csv import urllib2 # get page source and create a BeautifulSoup object based on it try: print("Fetching page.") page = requests.get("http://siph0n.net") soup = BeautifulSoup(page, 'lxml') ...
0
2016-07-28T10:56:14Z
[ "python", "python-2.7", "beautifulsoup", "urllib2", "scraper" ]
if form field is None don't find in model in that field
38,633,484
<p>I have model with blank=True fields. In my form I have fields that are optional if in model they are blank=True. So, if in my form I want to make them empty, and then I want to filter my model objects, I don't want to use empty fields to search. Do I need to create other query in this case?</p> <p>forms.py</p> <pr...
0
2016-07-28T10:16:01Z
39,246,339
<p>The situation is that I forget to do <code>makemigrations</code>. After that all works fine!</p>
0
2016-08-31T09:53:29Z
[ "python", "django", "forms" ]
Must be called from a blob upload callback request
38,633,490
<p>I have implemented this GWT example for blobstore API in Java: <a href="https://cloud.google.com/appengine/docs/java/blobstore/" rel="nofollow">https://cloud.google.com/appengine/docs/java/blobstore/</a></p> <p>it works fine when POST is made via the client side form (inside a browser).</p> <p>However, now I am se...
0
2016-07-28T10:16:20Z
38,635,109
<p>That <code>/upload</code> handler is not meant for you to call directly, neither from the browser nor a python application. Instead, your application will need to make two calls: the first to your server to get a temporary URL, then the second to upload to that URL, which will connect with the blobstore directly. Yo...
1
2016-07-28T11:31:53Z
[ "java", "python", "google-app-engine", "gwt" ]
Train model using queue Tensorflow
38,633,539
<p>I designed a neural network in tensorflow for my regression problem by following and adapting the tensorflow tutorial. However, due to the structure of my problem (~300.000 data points and use of the costful FTRLOptimizer), my problem took too long to execute even with my 32 CPUs machine (I don't have GPUs).</p> <p...
2
2016-07-28T10:18:25Z
38,715,186
<p>My mistake, everything worked fine. I was misled because I estimated at each step of the algorithm my performance on different batches and also because my model was too complicated for a dummy one (I should had something like y=W*x or y=x+b). Then, when I tried to print in the console, I exucuted several times sess....
0
2016-08-02T08:17:49Z
[ "python", "multithreading", "machine-learning", "queue", "tensorflow" ]
Quick evaluation of many functions at same point in Python
38,633,584
<p><strong>Problem</strong>: I need a very fast way in <code>Python3</code> to evaluate many (in the thousands) functions at the same argument. So in a sense, I kind of need the opposite of <code>NumPy's</code> Broadcasting which allows to quickly evaluate <em>one</em> function at <em>multiple</em> points.</p> <p><str...
2
2016-07-28T10:20:40Z
38,633,667
<p>Evaluate them using threading by running them in multiple threads, as long as they do not have resource conflicts.</p> <p><a href="http://www.tutorialspoint.com/python/python_multithreading.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_multithreading.htm</a></p>
0
2016-07-28T10:24:43Z
[ "python", "numpy" ]
Quick evaluation of many functions at same point in Python
38,633,584
<p><strong>Problem</strong>: I need a very fast way in <code>Python3</code> to evaluate many (in the thousands) functions at the same argument. So in a sense, I kind of need the opposite of <code>NumPy's</code> Broadcasting which allows to quickly evaluate <em>one</em> function at <em>multiple</em> points.</p> <p><str...
2
2016-07-28T10:20:40Z
38,634,425
<p>If your functions are IO bound (meaning they spend most of their time waiting for some IO operation to complete), then using multiple threads may be a fair solution.</p> <p>If your functions are CPU bound (meaning they spend most of their time doing actual computational work), then multiple threads will not help yo...
3
2016-07-28T11:00:15Z
[ "python", "numpy" ]
JSON2HTML: Not a valid JSON list python
38,633,629
<p>I have a piece of JSON in a file I would like to convert to HTML. I seen online there is a tool called json2html for python which takes care of this for me.</p> <pre><code>[{ "name": "Steve", "timestampe": "2016-07-28 10:04:15", "age": 22 }, { "name": "Dave", "timestamp": "2016-07-28 10:04:15",...
0
2016-07-28T10:22:52Z
38,633,762
<p>Try setting the value of _json using json.loads(), as in this answer - <a href="http://stackoverflow.com/a/31011255/1772475">Converting json to html table in python</a></p>
0
2016-07-28T10:29:17Z
[ "python", "json", "python-2.7", "json2html" ]
JSON2HTML: Not a valid JSON list python
38,633,629
<p>I have a piece of JSON in a file I would like to convert to HTML. I seen online there is a tool called json2html for python which takes care of this for me.</p> <pre><code>[{ "name": "Steve", "timestampe": "2016-07-28 10:04:15", "age": 22 }, { "name": "Dave", "timestamp": "2016-07-28 10:04:15",...
0
2016-07-28T10:22:52Z
38,634,133
<p>parameter <code>json</code> must be a dictionary object and you pass a list. try this:</p> <pre><code>_json = { "data" : [{"name": "Steve", "timestampe": "2016-07-28 10:04:15", "age": 22 }, { "name": "Dave", "timestamp": "2016-07-28 10:04:15", "age": 34 }] } print json2html.convert(json=_json) ...
1
2016-07-28T10:47:15Z
[ "python", "json", "python-2.7", "json2html" ]
Python Gmail API 'not JSON serializable'
38,633,781
<p>I want to send an Email through Python using the Gmail API. Everythingshould be fine, but I still get the error "An error occurred: b'Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJ1cy1hc2NpaSIKTUlNRS..." Here is my code:</p> <pre><code>import base64 import httplib2 from email.mime.text import MIMEText from apicl...
2
2016-07-28T10:30:07Z
39,693,258
<p>I had this same issue, I assume you are using Python3 I found this on another post and the suggestion was to do the following:</p> <pre><code>raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} </code></pre> <p>Check out: <a href="https://github.com/google/google-api-python-cl...
0
2016-09-26T00:44:50Z
[ "python", "json", "api", "email", "gmail" ]
How to edit lines of all text files in a directory with python
38,633,787
<p>I would like to edit and replace lines of all .txt files in a directory with python for this purpose I am using the following code:</p> <pre><code>path = '.../dbfiles' for filename in os.listdir(path): for i in os.listdir(path): if i.endswith(".txt"): with open(i, 'r') as f_in: for line in ...
0
2016-07-28T10:30:22Z
38,633,899
<p>You should add the base path when you use <code>open</code>:</p> <pre><code> with open(path + '/' + i, 'r') as f_in: </code></pre> <p>the same goes for:</p> <pre><code> open(path + '/' + i, 'w').write(line) </code></pre>
2
2016-07-28T10:35:40Z
[ "python", "text-files", "ioerror" ]
How to edit lines of all text files in a directory with python
38,633,787
<p>I would like to edit and replace lines of all .txt files in a directory with python for this purpose I am using the following code:</p> <pre><code>path = '.../dbfiles' for filename in os.listdir(path): for i in os.listdir(path): if i.endswith(".txt"): with open(i, 'r') as f_in: for line in ...
0
2016-07-28T10:30:22Z
38,634,280
<p>The glob module is useful for getting files with similar endings:</p> <pre><code>import glob print glob.glob("*.txt") # Returns a list of all .txt files, with path info for item in glob.glob("*.txt"): temp = [] # Might be useful to use a temp list before overwriting your file with open(item, "r") as f: ...
1
2016-07-28T10:53:24Z
[ "python", "text-files", "ioerror" ]
Python Request: Post Images on Facebook using Multipart/form-data
38,633,791
<p>I'm using the facebook API to post images on a page, I can post image from web using this :</p> <pre><code>import requests data = 'url=' + url + '&amp;caption=' + caption + '&amp;access_token=' + token status = requests.post('https://graph.facebook.com/v2.7/PAGE_ID/photos', data=data) print ...
0
2016-07-28T10:30:31Z
38,633,884
<p>Pass in <code>data</code> as a <em>dictionary</em>:</p> <pre><code>data = { 'caption', caption, 'access_token', token } files = { 'file': open(IMG_PATH, 'rb') } status = requests.post( 'https://graph.facebook.com/v2.7/PAGE_ID/photos', data=data, files=files) </code></pre> <p><code>requests</co...
1
2016-07-28T10:35:09Z
[ "python", "facebook", "python-requests", "multipartform-data" ]
How can I open up webcam and process images with docker and OpenCV?
38,633,799
<p>I have a python script that uses OpenCV and when somebody runs my script I want process the image from their webcam and give back a result. How can I make it?</p> <p>This is how I tried:</p> <p>My simple test python script:</p> <pre><code>import cv2 cap = cv2.VideoCapture(0) while True: ret, frame = cap.read...
0
2016-07-28T10:30:46Z
38,634,175
<p>You have to show the frame. Using <code>cv2.imshow('Preview', frame)</code>. And outside the <code>while loop</code> you have to release the camera, so you should type <code>cap.release()</code>. </p>
0
2016-07-28T10:49:06Z
[ "python", "opencv", "docker", "dockerfile" ]
How to save data from the data stream while not blocking the stream? (PyQt5 signal emit() performance)
38,633,914
<p>I'm developing a PyQt5 application. In my application, it has a data stream, and its speed is about 5~20 data/sec.</p> <p>Every time data arrives, the following <code>onData()</code> method of class <code>Analyzer</code> is called. (Following code is simplified code of my app)</p> <pre><code>class Analyzer(): ...
1
2016-07-28T10:36:08Z
38,635,201
<p>something like this might work</p> <pre><code>class PickleDumpingThread(QThread): def __init__(self, data): super().__init__() self.data = data def run(self): pickle.dump(self.data["deque"], open(file, 'wb')) self.emit(QtCore.SIGNAL('threadFinished(int)'), self.currentThreadId()) ...
0
2016-07-28T11:35:58Z
[ "python", "pyqt", "python-multithreading", "pyqt5", "qthread" ]
How to save data from the data stream while not blocking the stream? (PyQt5 signal emit() performance)
38,633,914
<p>I'm developing a PyQt5 application. In my application, it has a data stream, and its speed is about 5~20 data/sec.</p> <p>Every time data arrives, the following <code>onData()</code> method of class <code>Analyzer</code> is called. (Following code is simplified code of my app)</p> <pre><code>class Analyzer(): ...
1
2016-07-28T10:36:08Z
38,649,894
<p>The problem was that I was not using <code>QThread</code> properly.</p> <p>The result of printing</p> <pre><code>print("(Current Thread)", QThread.currentThread(),"\n") print("(Current Thread)", int(QThread.currentThreadId()),"\n") </code></pre> <p>noticed me that the <code>PickleDumpingThread</code> I created wa...
0
2016-07-29T03:03:30Z
[ "python", "pyqt", "python-multithreading", "pyqt5", "qthread" ]
How to save data from the data stream while not blocking the stream? (PyQt5 signal emit() performance)
38,633,914
<p>I'm developing a PyQt5 application. In my application, it has a data stream, and its speed is about 5~20 data/sec.</p> <p>Every time data arrives, the following <code>onData()</code> method of class <code>Analyzer</code> is called. (Following code is simplified code of my app)</p> <pre><code>class Analyzer(): ...
1
2016-07-28T10:36:08Z
39,421,279
<p>When the GIL is a problem the workaround is to subdivide the task into chunks in such a way that you can refresh the GUI between chunks. </p> <p>E.g say you have one huge list of size S to dump, then you could try defining a class that derives from list and overrides getstate to return N subpickle objects, each one...
0
2016-09-10T00:13:39Z
[ "python", "pyqt", "python-multithreading", "pyqt5", "qthread" ]
Django URL error when using forms
38,633,980
<p>I am fairly new to Django and I am totally stuck on what is causing this error. I have done lots of searching but to no avail! Any help would be super appreciated.</p> <p>The actual form works fine but when I try and submit the input data I get the error:</p> <pre><code>Using the URLconf defined in mysite.urls, Dj...
0
2016-07-28T10:39:14Z
38,634,126
<p>the form "action" attribute is wrong... seeing your urls configuration you dont have a <code>/spirit3/add_patient/</code> url, I think It is <code>/add_patient/</code></p> <p>or you could just use a form tag without an "action" it will post to the current page:</p> <pre><code>&lt;form role="form" method="post"&gt;...
2
2016-07-28T10:46:52Z
[ "python", "django" ]
Django URL error when using forms
38,633,980
<p>I am fairly new to Django and I am totally stuck on what is causing this error. I have done lots of searching but to no avail! Any help would be super appreciated.</p> <p>The actual form works fine but when I try and submit the input data I get the error:</p> <pre><code>Using the URLconf defined in mysite.urls, Dj...
0
2016-07-28T10:39:14Z
38,635,003
<p>As pleasedontbelong mentionned, there's indeed no url matching "/spirit3/add_patient/" in your current url config. What you have in tour root urlconf is:</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('spirit3.urls')), ] </code></pre> <p>This means that urls with path sta...
0
2016-07-28T11:26:22Z
[ "python", "django" ]
Tkinter Show webcam view in second window
38,633,995
<p>I am using a webcam view and performing analysis on the images taken in. I wish to introduce a functionality where a window can be summoned and the user can look at the webcam view in a new window, should they desire. However my attempt causes buttons in my main window to swap over to the instance when I open up the...
1
2016-07-28T10:40:06Z
38,634,447
<p>Fixed! I was getting confused because of <code>self.lmain</code>. Here is the working code:</p> <pre><code>import Tkinter as tk import cv2 from PIL import Image, ImageTk class CamView(): def __init__(self, parent): self.parent = parent self.window = tk.Toplevel(parent) self.lmain2 = ...
1
2016-07-28T11:01:08Z
[ "python", "opencv", "tkinter" ]
pandas pivot_table apply aggfunc last instance
38,634,120
<p>I have made a pivot table with various columns and have applied aggfunc like np.sum and first and count. I want last instance of corresponding value of a column from a dataframe. Is there any function that could serve this purpose?</p>
1
2016-07-28T10:46:37Z
38,634,152
<p>I think you can use </p> <pre><code>aggfunc='last' </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({ 'Age':[35, 37, 40, 29, 31, 26, 28], 'City':['B', 'Ch', 'LA', 'Ch', 'B', 'B', 'Ch'], 'Position':['M','M','M','P', 'P','M','M']}) print (df) Age City Position 0 3...
1
2016-07-28T10:48:09Z
[ "python", "pandas" ]
Django unit test on custom model manager method
38,634,138
<p>I am pretty new in python and django.</p> <p>I have model with custom model manager with a method ,where i am raising <code>ValidationError</code> on some exceptions.now i want to test this custom manager method.but don't know how to catch <code>ValidationError</code> or anyother error in terms of testing django m...
0
2016-07-28T10:47:25Z
38,634,660
<p>use <a href="https://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a></p> <pre><code>with self.assertRaises(ValidationError): issues = Issues.objects.custom_method(field1='wrong field') </code></pre>
1
2016-07-28T11:10:24Z
[ "python", "django", "unit-testing" ]
Django unit test on custom model manager method
38,634,138
<p>I am pretty new in python and django.</p> <p>I have model with custom model manager with a method ,where i am raising <code>ValidationError</code> on some exceptions.now i want to test this custom manager method.but don't know how to catch <code>ValidationError</code> or anyother error in terms of testing django m...
0
2016-07-28T10:47:25Z
38,634,681
<p>You want <a href="https://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">`assertRaises'</a>:</p> <pre><code>def test_sample_model(self): with self.assertRaises(ValidationError): issues = Issues.objects.custom_method(field1='wrong field') </code></pre>
1
2016-07-28T11:11:17Z
[ "python", "django", "unit-testing" ]
Pandas: create dataframe using value_counts
38,634,235
<p>I have data</p> <pre><code>age 32 16 39 39 23 36 29 26 43 34 35 50 29 29 31 42 53 </code></pre> <p>I need to get smth like this <a href="http://i.stack.imgur.com/3Trd2.png" rel="nofollow"><img src="http://i.stack.imgur.com/3Trd2.png" alt="image"></a> I can get </p> <p><code>df.age.value_counts()</code> and </p> ...
-1
2016-07-28T10:51:04Z
38,634,767
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>cut</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>agg</code></a>:</p> <pre><code>#helper df with min and ...
1
2016-07-28T11:15:18Z
[ "python", "pandas" ]
PySpark Data Frame - give an ID to sequence of same values
38,634,248
<p>I have a dataset in a pyspark job that looks a bit like this:</p> <pre><code>frame_id direction_change 1 False 2 False 3 False 4 True 5 False </code></pre> <p>I want to add a "track" counter to each row so that all the frames between direction change...
0
2016-07-28T10:52:02Z
38,635,139
<p>Long story short there is no efficient way to do in PySpark with <code>DataFrames</code> alone. One could be tempted to use window functions like this:</p> <pre><code>from pyspark.sql.functions import col, sum as sum_ from pyspark.sql.window import Window w = Window().orderBy("frame_id") df.withColumn("change", 1...
2
2016-07-28T11:33:13Z
[ "python", "apache-spark", "pyspark", "spark-dataframe" ]
cx_freeze build doesn't allow program quitting
38,634,265
<p>I've tried with <code>exit(0)</code> in tkinter, <code>pygame.quit()</code> in pygme and other things in my cx_freeze build, but an error pops up when using <code>pygame.quit()</code> (which stops the whole program which is not intentional) and when I use <code>exit(0)</code> in tkinter it won't allow me to quit. It...
1
2016-07-28T10:52:52Z
38,636,660
<p>It is odd, it should be correct but you can try this...</p> <pre><code>import sys print("") </code></pre>
0
2016-07-28T12:40:42Z
[ "python", "cx-freeze" ]
XML to pandas: Export to csv and make the childrens in same row
38,634,290
<p>I am in the "munging stage", trying to convert a XML file to csv with pandas. I finally did with the code bellow: </p> <pre><code>for element in etree.iterparse(path): data.append({element.tag: element.text}) df = pd.DataFrame(data,columns=['NOME_DISTRITO', 'NR_CPE', 'MARCA_EQUIPAMENTO', ...
1
2016-07-28T10:53:40Z
38,649,358
<p>Consider running conditionals in the <code>iterparse()</code>. Because <code>&lt;NOME_DISTRITO&gt;</code> and <code>&lt;NR_CPE&gt;</code> lie outside the repeated <code>&lt;LEITURA&gt;</code> elements, save their values in scalars to be added to the <code>inner{}</code> dictionary for appending to dataframe:</p> <p...
0
2016-07-29T01:57:56Z
[ "python", "excel", "pandas" ]
Empty Div return with Xpath or Css Selector Using Scrapy
38,634,495
<p>I'm using Scrapy to crawl a web page which contains a specific article.</p> <p>I'm trying to get the informations stored inside the div with the class "return". The big problem that the div return always empty when i use Scrapy Xpath or Css selectors.</p> <p><strong>The Div that i'm trying to extract:</strong> </...
0
2016-07-28T11:02:45Z
38,648,774
<p>The <a href="http://www.alinea.fr/orca-canape-angle-gauche-droit-convertible-gris.html" rel="nofollow">page</a> you visited has no content for that <code>div</code> at all. So you are supposed to get what you got.</p> <p>If you change to other pages, for example <a href="http://www.alinea.fr/orca-canape-angle-droit...
0
2016-07-29T00:33:41Z
[ "python", "web-scraping", "scrapy" ]
Check GitHub credentials validity
38,634,656
<p>I am trying to verify GitHub credentials with Python.</p> <p>I have tried this:</p> <pre><code>import urllib2, base64 username = "test@example.com" password = "password" request = urllib2.Request("https://github.com/") base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.a...
1
2016-07-28T11:10:17Z
38,635,980
<p>I should've been using <code>https://api.github.com/user</code> instead of <code>https://github.com/</code>.</p> <p>Nevertheless, I will use <code>requests</code> 3rd party library, which makes this code concise:</p> <pre><code>import requests print requests.get( 'https://api.github.com/user', auth=('usern...
0
2016-07-28T12:10:56Z
[ "python", "github", "urllib2" ]
beautifulsoup installation in pyCharm with two versions of python installed
38,634,685
<p>I use PyCharm to write Python, at first I configurated PyCharm with Python 2.7.12, and I installed the Beautiful Soup package under the 2.7.12 environment. </p> <p>However, I now have installed python 3.5.2 in PyCharm and I want to use Beautiful Soup in PyCharm with 3.5.2, but I can't import bs4 because the interpr...
0
2016-07-28T11:11:32Z
38,634,744
<p>To be sure to install your package for the right version of python, you can use pip as a module :</p> <pre><code>python3.5 -m pip install [package] </code></pre> <p>So for bs4 :</p> <pre><code>python3.5 -m pip install beautifulsoup4 </code></pre>
0
2016-07-28T11:14:04Z
[ "python", "pycharm" ]
Catch an error from command line Python
38,634,746
<p>I need to catch an error from command line without print error message on the screen. When this occurs I need to give another command to run.</p> <p>This is what I do now:</p> <pre><code>hyst_cmd = "si viewhistory ..." process = subprocess.Popen(hyst_cmd, stdout=subprocess.PIPE) hyst = process.stdout.read().splitl...
1
2016-07-28T11:14:07Z
38,634,986
<p>According to the official document, the most common exception for Popen in subprocess is <strong>OSError</strong>.</p> <p>To catch the error, you can simply try the following approach:</p> <pre><code>hyst_cmd = "si viewhistory ..." try: process = subprocess.Popen(hyst_cmd, stdout=subprocess.PIPE) hyst = p...
0
2016-07-28T11:25:40Z
[ "python", "command" ]
Extracting parameters from astropy.modeling Gaussian2D
38,634,782
<p>I have managed to use <code>astropy.modeling</code> to model a 2D Gaussian over my image and the parameters it has produced to fit the image seem reasonable. However, I need to run the 2D Gaussian over thousands of images because we are interested in examining the mean x and y of the model and also the x and y stand...
1
2016-07-28T11:15:52Z
38,635,135
<p>The models have attributes you can access:</p> <pre><code>from astropy.modeling import models g2d = models.Gaussian2D(1,2,3,4,5) g2d.amplitude.value # 1.0 g2d.x_mean.value # 2.0 g2d.y_mean.value # 3.0 g2d.x_stddev.value # 4.0 g2d.y_stddev.value # 5.0 </code></pre> <p>You need to extract these values a...
1
2016-07-28T11:33:08Z
[ "python", "modeling", "astropy" ]
Python Regular Expression for stopping in between
38,634,788
<p>This is my string:</p> <blockquote> <p>age: adult/child gender: male/female <strong>age range: 3 - 5 years/5 - 8 years/8 - 12 yrs/12 years and up</strong> product type: costume character: animals &amp; insects material: polyester theme: animal age start: 3 years age end: adult features: -face is seen thr...
0
2016-07-28T11:16:01Z
38,634,959
<p>You could try this pattern using <code>re.search()</code>:</p> <pre><code>import re string = 'age: adult/child gender: male/female age range: 3 - 5 years/5 - 8 years/8 - 12 years/12 years and up product type: costume character: animals &amp;amp; insects material: polyester theme: animal age start: 3 years ...
0
2016-07-28T11:24:21Z
[ "python", "regex" ]
Python Regular Expression for stopping in between
38,634,788
<p>This is my string:</p> <blockquote> <p>age: adult/child gender: male/female <strong>age range: 3 - 5 years/5 - 8 years/8 - 12 yrs/12 years and up</strong> product type: costume character: animals &amp; insects material: polyester theme: animal age start: 3 years age end: adult features: -face is seen thr...
0
2016-07-28T11:16:01Z
38,634,993
<p>You can use the following:</p> <pre><code>\bage range:\s*(?:\d+\s*-\s*\d+\s*y(?:ea)?rs/)+\d+\s*y(?:ea)?rs and up\b </code></pre> <p>See <a href="https://regex101.com/r/eK1nM9/1" rel="nofollow">Demo</a></p>
0
2016-07-28T11:26:02Z
[ "python", "regex" ]
Python Regular Expression for stopping in between
38,634,788
<p>This is my string:</p> <blockquote> <p>age: adult/child gender: male/female <strong>age range: 3 - 5 years/5 - 8 years/8 - 12 yrs/12 years and up</strong> product type: costume character: animals &amp; insects material: polyester theme: animal age start: 3 years age end: adult features: -face is seen thr...
0
2016-07-28T11:16:01Z
38,635,150
<p>If "product type" is always following your desired string, then you can use <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookahead assertion</a>:</p> <pre><code>&gt;&gt;&gt; r = re.search(r'(age range:.*?)(?= product type)', s) &gt;&gt;&gt; r.group(1) 'age range: 3 - 5 years/5 - 8 ye...
0
2016-07-28T11:33:53Z
[ "python", "regex" ]
Failing to import itertools in Python 3.5.2
38,634,810
<p>I am new to Python. I am trying to import izip_longest from itertools. But I am not able to find the import "itertools" in the preferences in Python interpreter. I am using Python 3.5.2. It gives me the below error-</p> <pre><code>from itertools import izip_longest ImportError: cannot import name 'izip_longest' </c...
0
2016-07-28T11:16:52Z
38,634,822
<p><code>izip_longest</code> was <em>renamed</em> to <a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="nofollow"><code>zip_longest</code></a> in Python 3 (note, no <code>i</code> at the start), import that instead:</p> <pre><code>from itertools import zip_longest </code></pre> <p>a...
1
2016-07-28T11:17:37Z
[ "python", "python-2.7", "pycharm", "python-3.5", "itertools" ]
Use Flask to convert a Pandas dataframe to CSV and serve a download
38,634,862
<p>I have a Pandas dataframe in my Flask app that I want to return as a CSV file.</p> <pre><code>return Response(df.to_csv()) </code></pre> <p>The problem is that the output appears in the browser instead of downloading as a separate file. How can I change that?</p> <p>I tried the following as well but it just gave ...
2
2016-07-28T11:19:45Z
38,635,222
<p>Set the <code>Content-Disposition</code> to tell the browser to download the file instead of showing its content on the page.</p> <pre><code>resp = make_response(df.to_csv()) resp.headers["Content-Disposition"] = "attachment; filename=export.csv" resp.headers["Content-Type"] = "text/csv" return resp </code></pre>
3
2016-07-28T11:37:01Z
[ "python", "pandas", "flask" ]
Check if programm runs in Debug mode
38,634,988
<p>I use the PyCharm IDE for Python programming.</p> <p>Is there a possibility to check, whether I'm in debugging mode or not when I run my proframm?</p> <p>I use pyplot as plt and want a Figure only to be shown if I debug my programm. Yes, I could have a global boolean <em>debug</em> which is set by myself, but I lo...
1
2016-07-28T11:25:45Z
38,636,826
<p>It is better not to use other programming platforms.... use this instead (If you like!):- <a href="https://www.python.org/downloads/windows/(If" rel="nofollow">https://www.python.org/downloads/windows/(If</a> you are using windows) <a href="https://www.python.org/downloads/mac-osx/(If" rel="nofollow">https://www.pyt...
0
2016-07-28T12:47:23Z
[ "python", "python-2.7", "debugging", "pycharm" ]
Check if programm runs in Debug mode
38,634,988
<p>I use the PyCharm IDE for Python programming.</p> <p>Is there a possibility to check, whether I'm in debugging mode or not when I run my proframm?</p> <p>I use pyplot as plt and want a Figure only to be shown if I debug my programm. Yes, I could have a global boolean <em>debug</em> which is set by myself, but I lo...
1
2016-07-28T11:25:45Z
38,637,774
<p>According to the documentation, <code>settrace</code> / <code>gettrace</code> functions could be used in order to implement Python debugger:</p> <blockquote> <pre><code>sys.settrace(tracefunc) </code></pre> <p>Set the system’s trace function, which allows you to implement a Python source code debugger in ...
1
2016-07-28T13:25:05Z
[ "python", "python-2.7", "debugging", "pycharm" ]
Finding the optimal combination of algorithms in an sklearn machine learning toolchain
38,635,075
<p>In sklearn it is possible to create a pipeline to optimize the complete tool chain of a machine learning setup, as shown in the following sample:</p> <pre><code>from sklearn.pipeline import Pipeline from sklearn.svm import SVC from sklearn.decomposition import PCA estimators = [('reduce_dim', PCA()), ('svm', SVC())...
0
2016-07-28T11:29:35Z
38,636,748
<p>A pipeline is something sequential:</p> <pre><code>Data -&gt; Process input with algorithm A -&gt; Process input with algorithm B -&gt; ... </code></pre> <p>Something parallel, and I also think what you're looking for is called an "Ensemble". For example, in a classification context you can train several SVMs but ...
1
2016-07-28T12:44:21Z
[ "python", "machine-learning", "scikit-learn" ]
Finding the optimal combination of algorithms in an sklearn machine learning toolchain
38,635,075
<p>In sklearn it is possible to create a pipeline to optimize the complete tool chain of a machine learning setup, as shown in the following sample:</p> <pre><code>from sklearn.pipeline import Pipeline from sklearn.svm import SVC from sklearn.decomposition import PCA estimators = [('reduce_dim', PCA()), ('svm', SVC())...
0
2016-07-28T11:29:35Z
38,636,833
<p>The pipeline is not a parallel process. It's rather sequential (Pipe<strong>line</strong>) - see <a href="http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html" rel="nofollow">here</a> the documentation, mentionning : </p> <blockquote> <p>Sequentially apply a list of transforms and a fin...
1
2016-07-28T12:47:34Z
[ "python", "machine-learning", "scikit-learn" ]
Define range for index for lists in for loops
38,635,088
<p>I'm a complete beginner in <em>Python</em>. I was coding the "minimum difference between array elements" problem. The idea was to sort the array and then find the difference between adjacent elements, to find the one with the minimum difference. </p> <p>However, I wonder how to define the range for the index of the...
3
2016-07-28T11:30:29Z
38,635,124
<p>You can pass a slice of <code>a</code> with the specified start and stop indices to <code>enumerate</code>:</p> <pre><code>for i, x in enumerate(a[:size-1]): ... </code></pre> <p><code>i</code> will run from <code>0</code> to <code>size-2</code></p> <hr> <p>On a side note, comments in Python start with <code...
3
2016-07-28T11:32:51Z
[ "python", "arrays" ]
Define range for index for lists in for loops
38,635,088
<p>I'm a complete beginner in <em>Python</em>. I was coding the "minimum difference between array elements" problem. The idea was to sort the array and then find the difference between adjacent elements, to find the one with the minimum difference. </p> <p>However, I wonder how to define the range for the index of the...
3
2016-07-28T11:30:29Z
38,635,288
<p>If you really want to use manual indexing, then dont use <code>enumerate()</code> and just create a <code>range()</code> (or <code>xrange()</code> if Python 2.x) of the right size, ie:</p> <pre><code>for i in xrange(len(a) - 2): # code here </code></pre> <p>Now you don't have to manually take care of indexes at...
5
2016-07-28T11:39:49Z
[ "python", "arrays" ]
Define range for index for lists in for loops
38,635,088
<p>I'm a complete beginner in <em>Python</em>. I was coding the "minimum difference between array elements" problem. The idea was to sort the array and then find the difference between adjacent elements, to find the one with the minimum difference. </p> <p>However, I wonder how to define the range for the index of the...
3
2016-07-28T11:30:29Z
38,635,291
<p>You could just <a class='doc-link' href="http://stackoverflow.com/documentation/python/289/indexing-and-slicing#t=201607281137123998325">slice</a> <code>a</code>. Then <code>enumerate(a[:-1])</code> will ignore one element at the end of <code>a</code>.</p> <p>You don't even need to compute <code>size</code> anymore...
4
2016-07-28T11:39:50Z
[ "python", "arrays" ]
How to create Json Web Token to User login in Django Rest Framework?
38,635,092
<p>I want to add JWT to my User Login API for authenticate. What should I do according to this codes? I create a token by manuel. But it must change. How can I integrated? Thank you.</p> <p><strong>Serializers</strong></p> <pre><code>class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read...
0
2016-07-28T11:30:48Z
38,640,350
<p>You can try doing something like this:</p> <p>First, install <code>pip install djangorestframework-jwt</code>.</p> <p><strong>settings.py:</strong></p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES...
0
2016-07-28T15:12:40Z
[ "python", "django", "django-rest-framework" ]
How to create Json Web Token to User login in Django Rest Framework?
38,635,092
<p>I want to add JWT to my User Login API for authenticate. What should I do according to this codes? I create a token by manuel. But it must change. How can I integrated? Thank you.</p> <p><strong>Serializers</strong></p> <pre><code>class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read...
0
2016-07-28T11:30:48Z
38,735,964
<p>Automatically, you can use 'rest_framework_jwt.views.obtain_jwt_token' for User Login. It create a token. And then, you need to go RestrictedView and use to token for authentication. Basicly, that's all.</p>
0
2016-08-03T06:29:04Z
[ "python", "django", "django-rest-framework" ]
Exception when training data in Predictionio
38,635,166
<p>I am trying to Deploy an Recommendation Engine as mentioned in <a href="http://docs.prediction.io/templates/recommendation/quickstart/" rel="nofollow">quick start guide</a>. I completed the steps up to build the engine. Now I want to train the Recommendation Engine. I did as mentioned in quick start guide. (execute ...
5
2016-07-28T11:34:18Z
38,655,950
<p>Your error says <code>java.lang.StackOverflowError</code> for that you can reduce the <code>numIterations parameter</code> in <code>engine.json</code> file. Refer <a href="http://stackoverflow.com/questions/34133172/predictionio-engine">this</a>.</p>
1
2016-07-29T10:01:14Z
[ "python", "apache-spark", "recommendation-engine", "data-science", "predictionio" ]
TensorFlow: Implementing Spearman Distance as the Objective Function
38,635,182
<p>In order to make my issue reproducible, I have generated the following <code>.csv</code> file using iris flower data set (10 arbitrary rows, all columns standard normalized) and a minimal neural network model (which predicts petal width using sepal length, sepal width and petal length) by modifying an MNIST example ...
0
2016-07-28T02:56:13Z
38,636,465
<p>Your error comes from the fact that <code>tf.py_func</code> has no gradient defined. </p> <p>Anyway, as @user20160 said in the comments, no gradient even exists for the operation <code>rank</code>, so this is not a loss on which you can train your algorithm directly.</p>
2
2016-07-28T12:31:37Z
[ "python", "ranking", "tensorflow" ]
Inserting elements from array to the string
38,635,199
<p>I have two variables:</p> <pre><code>query = "String: {} Number: {}" param = ['text', 1] </code></pre> <p>I need to merge these two variables and keep the quote marks in case of string and numbers without quote marks.</p> <p>result= <code>"String: 'text' Number: 1"</code></p> <p>I tried to use query.format(param...
2
2016-07-28T11:35:53Z
38,635,274
<p>You can use <code>repr</code> on each item in <code>param</code> within a generator expression, then use <code>format</code> to add them to your string.</p> <pre><code>&gt;&gt;&gt; query = "String: {} Number: {}" &gt;&gt;&gt; param = ['text', 1] &gt;&gt;&gt; query.format(*(repr(i) for i in param)) "String: 'text' N...
7
2016-07-28T11:39:10Z
[ "python", "arrays", "string" ]
Matching a number within a number in a python List
38,635,408
<p>A queryset returned a list:</p> <pre><code>list1=[2856,28564,1245,232856] </code></pre> <p>When I try to find if a number exists in the above list by writing:</p> <pre><code>num=2856 if num in list1: </code></pre> <p>it matches 2856, 25564, and 232856. How can I make sure it matches only 2856 and not the rest?</...
-2
2016-07-28T11:45:14Z
38,635,491
<p>It does not behave like you suggest. In fact your current syntax gives your desired output.</p> <pre><code>&gt;&gt;&gt; list1=[2856,28564,1245,232856] &gt;&gt;&gt; num=2856 &gt;&gt;&gt; if num in list1: ... print(num) ... 2856 &gt;&gt;&gt; </code></pre> <p>This is the behavior you are suggesting. Note how it ...
3
2016-07-28T11:49:04Z
[ "python" ]
Matching a number within a number in a python List
38,635,408
<p>A queryset returned a list:</p> <pre><code>list1=[2856,28564,1245,232856] </code></pre> <p>When I try to find if a number exists in the above list by writing:</p> <pre><code>num=2856 if num in list1: </code></pre> <p>it matches 2856, 25564, and 232856. How can I make sure it matches only 2856 and not the rest?</...
-2
2016-07-28T11:45:14Z
38,635,530
<p>You are checking if the value of num is inside of the list. Therefore, the expression </p> <pre><code>num in list1 </code></pre> <p>is True if num is equal to any item of list1. To make it only True when num is equal to the first (here: 2856) you have to write:</p> <pre><code>num == list1[0] </code></pre>
-1
2016-07-28T11:50:54Z
[ "python" ]
Matching a number within a number in a python List
38,635,408
<p>A queryset returned a list:</p> <pre><code>list1=[2856,28564,1245,232856] </code></pre> <p>When I try to find if a number exists in the above list by writing:</p> <pre><code>num=2856 if num in list1: </code></pre> <p>it matches 2856, 25564, and 232856. How can I make sure it matches only 2856 and not the rest?</...
-2
2016-07-28T11:45:14Z
38,635,570
<p>For your specific example:</p> <p>[x for x in list1 if x==2856][0]</p> <p>returns a single element list containing only the value you want and you access its only position to get the element.</p>
0
2016-07-28T11:52:41Z
[ "python" ]
Searching in Google with Python
38,635,419
<p>I want to search a text in Google using a python script and return the name, description and URL for each result. I'm currently using this code:</p> <pre><code>from google import search ip=raw_input("What would you like to search for? ") for url in search(ip, stop=20): print(url) </code></pre> <p>This retur...
-3
2016-07-28T11:45:37Z
38,635,722
<p>I assume you are using <a href="https://breakingcode.wordpress.com/2010/06/29/google-search-python/" rel="nofollow">this library by Mario Vilas</a> because of the <code>stop=20</code> argument which appears in his code. It seems like this library is not able to return anything but the URLs, making it horribly undeve...
3
2016-07-28T11:58:57Z
[ "python", "python-2.7", "google-search" ]
Searching in Google with Python
38,635,419
<p>I want to search a text in Google using a python script and return the name, description and URL for each result. I'm currently using this code:</p> <pre><code>from google import search ip=raw_input("What would you like to search for? ") for url in search(ip, stop=20): print(url) </code></pre> <p>This retur...
-3
2016-07-28T11:45:37Z
38,639,228
<p>Not exatcly what I was looking for, but I found myself a nice solution for now (I might edit this if I will able to make this better). I combined searching in Google like I did (returning only URL) and the Beautiful Soup package for parsing HTML pages:</p> <pre><code>from google import search import urllib from bs4...
0
2016-07-28T14:23:37Z
[ "python", "python-2.7", "google-search" ]
Matrix of polynomial elements
38,635,580
<p>I am using NumPy for operations on matrices, to calculate matrixA * matrixB, the trace of the matrix, etc... And elements of my matrices are integers. But what I want to know is if there is possibility to work with matrices of polynomials. So for instance I can work with matrices such as <code>[x,y;a,b]</code>, not ...
4
2016-07-28T11:53:01Z
38,635,743
<p>One option is to use the <a href="http://docs.sympy.org/dev/modules/matrices/matrices.html" rel="nofollow">SymPy Matrices module</a>. SymPy is a symbolic mathematics library for Python which is quite interoperable with NumPy, especially for simple matrix manipulation tasks such as this. </p> <pre><code>&gt;&gt;&gt...
2
2016-07-28T11:59:42Z
[ "python", "numpy", "matrix", "sympy" ]
Why I output csv file with a blank row
38,635,669
<p>This is my code:</p> <pre><code>with open("testoffset.csv") as handler: f = open('output_file2.csv', 'w+') f.write('X,Y,value\n') for r,l in enumerate(handler): for col, e in enumerate(l.split(',')): f.write('{0},{1},{2}\n'.format(r+1,col+1,e)) </code></pre> <p>This outputs</p> <pr...
0
2016-07-28T11:56:36Z
38,635,741
<p>Your lines from the <code>handler</code> file have a newline at the end, which you write to your output file.</p> <p>Remove that newline by stripping before you split the line:</p> <pre><code>for col, e in enumerate(l.rstrip('\n').split(',')): </code></pre> <p>You may want to avoid re-inventing the CSV reading an...
2
2016-07-28T11:59:34Z
[ "python", "python-2.7", "csv" ]
Why I output csv file with a blank row
38,635,669
<p>This is my code:</p> <pre><code>with open("testoffset.csv") as handler: f = open('output_file2.csv', 'w+') f.write('X,Y,value\n') for r,l in enumerate(handler): for col, e in enumerate(l.split(',')): f.write('{0},{1},{2}\n'.format(r+1,col+1,e)) </code></pre> <p>This outputs</p> <pr...
0
2016-07-28T11:56:36Z
38,635,885
<pre><code>with open("testoffset.csv",'wb') as handler: </code></pre> <p>Replace first line of your code. </p>
0
2016-07-28T12:05:52Z
[ "python", "python-2.7", "csv" ]
Why I output csv file with a blank row
38,635,669
<p>This is my code:</p> <pre><code>with open("testoffset.csv") as handler: f = open('output_file2.csv', 'w+') f.write('X,Y,value\n') for r,l in enumerate(handler): for col, e in enumerate(l.split(',')): f.write('{0},{1},{2}\n'.format(r+1,col+1,e)) </code></pre> <p>This outputs</p> <pr...
0
2016-07-28T11:56:36Z
38,635,947
<p>Just skip empty lines.</p> <pre><code>... for r,l in enumerate(handler): if not l.startswith('\n'): #or if l[0] != '\n': for col, e in enumerate(l.split(',')): ... </code></pre>
1
2016-07-28T12:08:49Z
[ "python", "python-2.7", "csv" ]