title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to create an adjacency list from an edge list efficiently
39,562,253
<p>I have a csv that looks like</p> <pre><code>id1,id2 a,b c,d a,e c,f c,g </code></pre> <p>I read it in to a dataframe with df = pd.read_csv("file.csv").</p> <p>I would like to convert it to an adjacency list. That is the output should be</p> <pre><code>a,b,e c,d,f,g </code></pre> <p>I feel that df.groupby('id1') should help but variable length rows aren't suited to pandas so I am a little stuck. As my csv is large I am looking for an efficient solution however.</p> <p>What is a good way to do this?</p>
1
2016-09-18T20:16:23Z
39,610,393
<p>Something like this:</p> <pre><code>adj = defaultdict(set) for line in input: left, right = line.split(",") adj[left].add(right) </code></pre> <p>Output:</p> <pre><code>for k,v in adj.items(): print("%s,%s" % (k, ",".join(v))) </code></pre>
0
2016-09-21T07:44:09Z
[ "python", "pandas", "graph" ]
My djcelery tasks run locally but not remotely?
39,562,277
<p>I have automated tasks working locally but not reomotely in my django app. I was watching a tutorial and the guy said to stop my worker. but before I did that I put my app in maintenance mode, that didn't work. then I ran</p> <pre><code>heroku ps:restart </code></pre> <p>that didn't work, then I ran </p> <pre><code>heroku ps:stop worker </code></pre> <p>which outputed </p> <pre><code> Warning: The dynos in your dyno formation will be automatically restarted. </code></pre> <p>then I ran </p> <pre><code>heroku ps:scale worker=1 </code></pre> <p>and still nothing. I remind those who are reading this that it worked locally. What am I missing?</p> <p>my procfile</p> <pre><code>web: gunicorn gettingstarted.wsgi --log-file - worker: celery worker -A blog -l info. </code></pre> <p>While researching I'm seeing mentions of adding beat to the procfile. 2 mentions in fact but this was not discussed in the tutorial I watched. only time celery beat was mentioned is when I added this to the settings.py file</p> <pre><code>CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' </code></pre> <p>and just in case it makes a difference I'm using the djcelery gui to set periodic tasks not configuring the sceduler in the settings.py like I see in a majority of the examples. </p> <p>If I run the task in my view and call it, it works. But it wont run if I set it up using djcelery</p>
0
2016-09-18T20:18:52Z
39,563,551
<p>I read the docs and realized I had to add to my worker procfile</p> <pre><code>-B </code></pre> <p>so it now looks like this</p> <pre><code>celery -A proj worker -B -l info </code></pre> <p>after I made the change I did this</p> <pre><code>heroku ps:scale worker=0 </code></pre> <p>then</p> <pre><code>git add . git commit -am 'added -B' git push heroku master </code></pre> <p>then I </p> <pre><code>heroku ps:scale worker=1 </code></pre> <p>then so I could see the output from heroku</p> <pre><code>heroku logs -t -p worker </code></pre> <p>and created a schedule in my admin and it worked. I saw the output in the console. Hope this helps. NOTE it says it's not recomended for production not sure why but if you know or find out let me know</p>
0
2016-09-18T23:21:59Z
[ "python", "django", "heroku", "task", "crontab" ]
My djcelery tasks run locally but not remotely?
39,562,277
<p>I have automated tasks working locally but not reomotely in my django app. I was watching a tutorial and the guy said to stop my worker. but before I did that I put my app in maintenance mode, that didn't work. then I ran</p> <pre><code>heroku ps:restart </code></pre> <p>that didn't work, then I ran </p> <pre><code>heroku ps:stop worker </code></pre> <p>which outputed </p> <pre><code> Warning: The dynos in your dyno formation will be automatically restarted. </code></pre> <p>then I ran </p> <pre><code>heroku ps:scale worker=1 </code></pre> <p>and still nothing. I remind those who are reading this that it worked locally. What am I missing?</p> <p>my procfile</p> <pre><code>web: gunicorn gettingstarted.wsgi --log-file - worker: celery worker -A blog -l info. </code></pre> <p>While researching I'm seeing mentions of adding beat to the procfile. 2 mentions in fact but this was not discussed in the tutorial I watched. only time celery beat was mentioned is when I added this to the settings.py file</p> <pre><code>CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' </code></pre> <p>and just in case it makes a difference I'm using the djcelery gui to set periodic tasks not configuring the sceduler in the settings.py like I see in a majority of the examples. </p> <p>If I run the task in my view and call it, it works. But it wont run if I set it up using djcelery</p>
0
2016-09-18T20:18:52Z
39,565,209
<p>As you've read in the docs, using the <strong>-B</strong> option is not recommended for production use, you'd better run <code>celery-beat</code> as a different process.</p> <p>So it's best practice to run it in the server like : </p> <pre><code>celery beat -A messaging_router --loglevel=INFO </code></pre> <p>And if you're using <code>supervisor</code> to keep your processes running, you'd add something like the following to your configuration file.</p> <pre><code>[program:api_beat] command=/path/to/v_envs/v_env/bin/celery -A project beat --loglevel=info autostart=true autorestart=true user=your_user (echo $USER) directory=/path/to/project/root stdout_logfile=/var/log/supervisor/beat.log stderr_logfile=/var/log/supervisor/beat.log redirect_stderr=true environment=EVN_VAR1="whatever", </code></pre> <p>The reason for this is as the docs say</p> <blockquote> <p>You can also start embed beat inside the worker by enabling workers -B option, this is convenient if you will never run more than one worker node, but it’s not commonly used and for that reason is not recommended for production use:</p> </blockquote> <p>Consider you having more than 1 worker, in maintenance, you need to always be vary of which one of the celery workers you've run with the <code>-B</code> and that definitely can be burden. </p>
0
2016-09-19T04:06:30Z
[ "python", "django", "heroku", "task", "crontab" ]
substract from date tuple
39,562,373
<p>I have an index consisting of Date tuples.</p> <pre><code>2005-02-04 00:00:00 31.81 31.81 31.81 31.81 2005-02-07 00:00:00 31.885 31.885 31.885 31.885 2005-02-08 00:00:00 31.5326 31.5326 31.5326 31.5326 </code></pre> <p>I would like to add a row at the top of the index, and I use the following way:</p> <pre><code>df.ix[ (df.index.min()) - dt.timedelta(minutes=5), :] = ([ dict[n] for n in df.columns.values.tolist()]) </code></pre> <p>dict contains some values, but it's irrelevant here I think. However, I get the following error:</p> <pre><code>TypeError: unsupported operand type(s) for -: 'tuple' and 'datetime.timedelta' </code></pre> <p>The type of the Index is: df.index.dtype gives type Object as opposed to Datetime as it should I suppose. thanks</p>
-2
2016-09-18T20:28:35Z
39,562,559
<p>Actually I ve found it, you simply need to take the first element off the tuple, and it returns a 'TimeStamp' object: </p> <pre><code>df.index.min()[0] - dt.timedelta(minutes=5) </code></pre> <p>works </p>
0
2016-09-18T20:49:57Z
[ "python", "datetime", "pandas", "dataframe" ]
Plot gyrosensor data in csv file in matplotlib
39,562,374
<p>I have exported gyro sensor data from my mobile using sensorLog app in csv format. I am trying the plot of three axis data wrt timestamp. Data looks like this </p> <p>1474145797.91346 -0.055417 -0.465534 -0.284113</p> <p>1474145797.93344 -0.108296 -0.42116 -0.240057</p> <p>1474145797.95342 -0.047696 -0.424263 -0.247162</p> <p>1474145797.99336 0.051028 -0.479374 -0.275701</p> <p>Columns are timestamp, xaxis(rad/sec), yaxis(rad/sec), zaxis(rad/sec)</p> <p>to plot this data I used the following python code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt xaxis, x, y, z = np.loadtxt('gyroscope.csv', delimiter=',', unpack = True) plt.plot(xaxis, np.rad2deg(x), color = "blue", label = "xaxis") plt.plot(xaxis, np.rad2deg(y), color = "red", label = "yaxis") plt.plot(xaxis, np.rad2deg(z), color = "black", label = "zaxis") plt.xlabel('x') plt.ylabel('y') plt.legend() plt.show() </code></pre> <p>This is the error I get:<br> return float(x) ValueError: could not convert string to float: b'timestamp' . </p> <p>However if I change the timestamp, the above code works fine which is not what i want. I want the graph of degrees with respect to time(millisec). I think the problem is with timestamp which is in format 1.47E+09. Could any one suggest me on how I can format the timestamp column? Am I missing anything?</p> <p>Thanks in advance. Any suggestions or corrections is really appreciated.</p>
0
2016-09-18T20:28:35Z
39,563,002
<p>I believe your Problem is the first line in the CSV-file which is actually the header.</p> <p>Try passing <em>skiprows=1</em> to loadtxt</p>
0
2016-09-18T21:48:41Z
[ "python", "matplotlib" ]
Printing coeficients of several linear regressions on a single python script
39,562,376
<p>I am running this code:</p> <pre><code>import sklearn IVS=['CRIM', 'RM', 'PTRATIO'] IVS2=['CRIM','PTRATIO'] model1=lm.fit(bos[IVS],bos.PRICE) model2=lm.fit(bos[IVS2],bos.PRICE) print(model1.coef_) print(model2.coef_) </code></pre> <p>When trying to print out the coefficients for both models, I only get the last model coef for both print functions:</p> <pre><code>[-0.27939868 -1.83737204] [-0.27939868 -1.83737204] </code></pre> <p>Any idea why this is?</p>
0
2016-09-18T20:28:54Z
39,563,819
<p>You need to create separate instances of your classifier before you call fit:</p> <pre><code>from sklearn.linear_model import LinearRegression() model1 = LinearRegression() model1.fit(bos[IVS],bos.PRICE) model2 = LinearRegression() model2.fit(bos[IVS2],bos.PRICE) </code></pre>
0
2016-09-19T00:16:10Z
[ "python", "scikit-learn", "regression", "linear", "coefficients" ]
MySQL/Python -- committed changes not appearing in loop
39,562,468
<p>Using MySQL Connector/Python I have a loop that keeps checking a value for a change every 2 seconds. Without all the meat, here is the loop (the print is there for testing purposes:</p> <pre><code>try: while True: request = database.get_row(table="states", wherecol="state", whereval="request_from_interface")[0] print(request.value) time.sleep(2) except KeyboardInterrupt: pass # back to normal operation </code></pre> <p>get_row is a simple select query and it returns the namedtuple fetchall (hence the [0] at the end, it will only ever be one row).</p> <p>The problem is that once it gets the initial value, it keeps returning that value even if I change it. For example, if it is "0" to start, it keeps printing "0" even if I go to adminer and change it and even if I open a new terminal and change it and commit it. I've tried setting the query_cache_size to 0, still no luck. I thought it was a commit problem, but that wasn't it, either. If I change it and reconnect, I see the change, but I'm not sure why it won't change while in the program. Any thoughts?</p> <p>EDIT: in case it comes up, yes I'm closing the cursor and grabbing a new cursor with every call.</p>
0
2016-09-18T20:39:34Z
39,562,906
<p>The default <a href="http://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html" rel="nofollow">isolation level</a> of InnoDB is <a href="http://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html#isolevel_repeatable-read" rel="nofollow">REPEATABLE READ</a>. This means that subsequent consistent <code>SELECT</code> statements will read the same snapshot established by the first within a transaction. Though you're opening and closing cursors, you're probably doing that inside a transaction and so you're reading the established snapshot over and over again. Either <code>ROLLBACK</code> or <code>COMMIT</code> to end the current transaction so that you can read values committed after the snapshot was taken.</p>
0
2016-09-18T21:33:49Z
[ "python", "mysql", "python-3.x", "mysql-connector-python" ]
ImportError: No module named bs4 in django
39,562,519
<p>I am learning Django and I was working with bs4 in PyCharm on mac. I am using Python3 with Django which also has bs4 installed and it can be seen below. <a href="http://i.stack.imgur.com/fRQP7.png" rel="nofollow"><img src="http://i.stack.imgur.com/fRQP7.png" alt="enter image description here"></a></p> <p>But when I run the project, it throws me an error saying bs4 does not exist which can be seen below. <a href="http://i.stack.imgur.com/x6vy3.png" rel="nofollow"><img src="http://i.stack.imgur.com/x6vy3.png" alt="enter image description here"></a></p> <p>I have tried a lot of ways and it couldn't get it to work. Help</p>
0
2016-09-18T20:44:57Z
39,562,552
<p>You are running the script with Python2.7 (according to the traceback) while having <code>beautifulsoup4</code> package installed in Python3.5 environment.</p> <p><em>Adjust your run configuration to use Python3.5 to run the script.</em></p>
1
2016-09-18T20:49:24Z
[ "python", "django", "beautifulsoup", "pycharm", "bs4" ]
ImportError: No module named bs4 in django
39,562,519
<p>I am learning Django and I was working with bs4 in PyCharm on mac. I am using Python3 with Django which also has bs4 installed and it can be seen below. <a href="http://i.stack.imgur.com/fRQP7.png" rel="nofollow"><img src="http://i.stack.imgur.com/fRQP7.png" alt="enter image description here"></a></p> <p>But when I run the project, it throws me an error saying bs4 does not exist which can be seen below. <a href="http://i.stack.imgur.com/x6vy3.png" rel="nofollow"><img src="http://i.stack.imgur.com/x6vy3.png" alt="enter image description here"></a></p> <p>I have tried a lot of ways and it couldn't get it to work. Help</p>
0
2016-09-18T20:44:57Z
39,562,555
<p>ok first thing, in your python 3 environment you have installed bs4, but in your python 2.7, you probably do not have. As you can see in your attached second screen, django is running on python 2.7.</p> <p>I recommend using virtual environment, where you can have all of your dependencies personalized for single project. In fact, every project you are working on, should have its own separate virtualenv. </p>
1
2016-09-18T20:49:31Z
[ "python", "django", "beautifulsoup", "pycharm", "bs4" ]
ImportError: No module named bs4 in django
39,562,519
<p>I am learning Django and I was working with bs4 in PyCharm on mac. I am using Python3 with Django which also has bs4 installed and it can be seen below. <a href="http://i.stack.imgur.com/fRQP7.png" rel="nofollow"><img src="http://i.stack.imgur.com/fRQP7.png" alt="enter image description here"></a></p> <p>But when I run the project, it throws me an error saying bs4 does not exist which can be seen below. <a href="http://i.stack.imgur.com/x6vy3.png" rel="nofollow"><img src="http://i.stack.imgur.com/x6vy3.png" alt="enter image description here"></a></p> <p>I have tried a lot of ways and it couldn't get it to work. Help</p>
0
2016-09-18T20:44:57Z
39,562,562
<p>You've installed wrong Beautiful Soup package. The one that you installed is <a href="https://pypi.python.org/pypi/bs4/0.0.1" rel="nofollow">bs4</a></p> <blockquote> <p>This is a dummy package managed by the developer of Beautiful Soup to prevent name squatting. The official name of PyPI’s Beautiful Soup Python package is beautifulsoup4.</p> </blockquote> <p>The one that you need to install is <a href="https://pypi.python.org/pypi/beautifulsoup4" rel="nofollow">beautifulsoup4</a>. Which you should get with <code>pip install beautifulsoup4</code> and not <code>pip install bs4</code></p>
0
2016-09-18T20:50:08Z
[ "python", "django", "beautifulsoup", "pycharm", "bs4" ]
How do I resolve this Python inheritance super-child call?
39,562,574
<p>If i'm using a super constructor to create a class that is inherited from a parent class, is it possible to use that same call to set an attribute to create a child class? So in my I am creating an Electric Car. An Electric Car is a child class of a Car. An Electric Car has an attribute battery which will be initialized through its Class constructor. Can I specify the size of the Battery in my initial call to construct Electric Car?</p> <p>Currently its giving me an error because I have a super call that has less parameters than my Electric car constructor</p> <p>Ex:</p> <pre><code>class Car(): def __init__(self,model,year): self.model = model self.year = year def getInfo(self): print(self.model, self.year) class ElectricCar(Car): def __init__(self, model, year, battery_size): super().__init__(model, year) self.battery = Battery(battery_size) class Battery(): def __init__(self, battery_size=70): self.battery_size = battery_size def describe_battery(self): print("Battery size is", self.battery_size) my_tesla = ElectricCar('TeslaX', 2016) my_tesla.getInfo() print(my_tesla.battery) my_tesla.battery.describe_battery() my_big_tesla = ElectricCar('TeslaY', 2016, 90) my_big_tesla.battery.describe_battery() </code></pre>
-2
2016-09-18T20:52:14Z
39,562,624
<p>You don't give battery size here:</p> <pre><code>my_tesla = ElectricCar('TeslaX', 2016) </code></pre> <p>Change it to:</p> <pre><code>my_tesla = ElectricCar('TeslaX', 2016, 1337) # 1337 is battery size. </code></pre> <hr> <p>If you wish to supply a default, you should also supply it in <code>ElectricCar</code> like so:</p> <pre><code>def __init__(self, model, year, battery_size=70): super().__init__(model, year) self.battery = Battery(battery_size) </code></pre>
1
2016-09-18T20:58:58Z
[ "python" ]
Trying to plot Mandelbrot set - no matter what, always get plain black image
39,562,659
<p>First, here's the code I have:</p> <pre><code>from PIL import Image as im import numpy as np def mandelbrot_iteration(c): iters = 0 while abs(c)&lt;2 and iters&lt;200: c=c**2+c iters+=1 return iters HEIGHT = 400 WIDTH = 500 diag = im.new('L',(WIDTH, HEIGHT)) pix = diag.load() x_pts = np.arange(-2,2,4/WIDTH) y_pts = np.arange(-2,2,4/HEIGHT) for x in x_pts: for y in y_pts: pix[x+2,y+2]=mandelbrot_iteration(complex(x,y)) diag.save("Fractal.png") </code></pre> <p>I thought this was quite straight forward. I see how many interations each point on a grid of complex numbers takes to grow past an abs. value of 2 and plot these values as a colour at each point (with 200 being the cutoff, assuming the sequence doesn't diverge). In the range specified, there should definitely be some non-trivial things going on, but no matter what I try, the image made is plain black. </p> <p>Also this method of generating images has almost zero documentation. I've searched a lot, and this: </p> <blockquote> <p>im.load()</p> <p>Allocates storage for the image and loads it from the file (or from the source, for lazy operations). In normal cases, you don’t need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time.</p> <p>(New in 1.1.6) In 1.1.6 and later, load returns a pixel access object that can be used to read and modify pixels. The access object behaves like a 2-dimensional array, so you can do:</p> <p>pix = im.load() print pix[x, y] pix[x, y] = value</p> <p>Access via this object is a lot faster than getpixel and putpixel</p> </blockquote> <p>Is <em>everything</em> that I can find about it (no examples out there either), which is very frustrating. I imagine the line pix[x+2,y+2] is at fault. The '+2's are there to stop the "out of range" errors, but, having tried some examples, I have no idea what it does with input numbers to generate a colour. I did find that 'L' when the image is created should make a greyscale image, but no idea what range pix[x,y] expects or anything. Everything came out black...</p>
1
2016-09-18T21:03:40Z
39,562,863
<p>The immediate problem is your <em>scale</em> is off.</p> <p>In this line <code>pix[x+2,y+2]=...</code>, with your ranges for <code>x</code> and <code>y</code>, the only pixels that are being drawn are <code>0..4</code>. Since the last few pixels drawn are black, the entire top left 4x4 square is black (and the rest is 0 – also black – by default, for a new image).</p> <p>That can be fixed like this:</p> <pre><code>from PIL import Image as im import numpy as np def mandelbrot_iteration(c): iters = 0 while abs(c)&lt;2 and iters&lt;200: c=c**2+c iters+=1 return iters HEIGHT = 400 WIDTH = 500 diag = im.new('L',(WIDTH, HEIGHT)) pix = diag.load() x_pts = np.arange(-2,2,4.0/WIDTH) y_pts = np.arange(-2,2,4.0/HEIGHT) for x in x_pts: for y in y_pts: pix[WIDTH*(x+2)/4.0,HEIGHT*(y+2)/4.0]=mandelbrot_iteration(complex(x,y)) diag.show() </code></pre> <p>although the result is not yet a good Mandelbrot...</p> <p><a href="http://i.stack.imgur.com/kgqoH.png" rel="nofollow"><img src="http://i.stack.imgur.com/kgqoH.png" alt="mandelsmorgasbord"></a></p> <p>With hcs' comment "mandelbrot iteration should be z=0, while abs(z)&lt;2, z=z**2+c" applied, you'd use this code</p> <pre><code>from PIL import Image as im import numpy as np def mandelbrot_iteration(c): iters = 0 z = 0 while abs(z)&lt;2 and iters&lt;200: z=z**2+c iters+=1 return iters HEIGHT = 400 WIDTH = 500 diag = im.new('L',(WIDTH, HEIGHT)) pix = diag.load() x_pts = np.arange(-2,2,4.0/WIDTH) y_pts = np.arange(-2,2,4.0/HEIGHT) for x in x_pts: for y in y_pts: pix[WIDTH*(x+2)/4.0,HEIGHT*(y+2)/4.0]=mandelbrot_iteration(complex(x,y)) # diag.show() diag.save("Fractal.png") </code></pre> <p>and lo and behold, a true Mandelbrot pops up:</p> <p><a href="http://i.stack.imgur.com/NOo72.png" rel="nofollow"><img src="http://i.stack.imgur.com/NOo72.png" alt="Correct Mandelbrot"></a></p>
2
2016-09-18T21:29:13Z
[ "python", "python-imaging-library" ]
I want use different kernels on jupyter, but how can I install different libraries on different kernel?
39,562,730
<p>I have two kernels on my jupyter, one is py2.7 and the other is py3.5, but how can I install different libraries like pandas or numpy for py2.7?</p>
1
2016-09-18T21:12:16Z
39,562,849
<p>You ought to use a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a>: this create a local copy of the Python of your choice. </p> <p>Then you can use <a href="https://pypi.python.org/pypi/pip" rel="nofollow">pip</a> to install libraries like Pandas…</p> <p>But, before, install Jupyter in your newly created virtualenv with:</p> <pre><code>pip install jupyter </code></pre>
1
2016-09-18T21:27:53Z
[ "python", "jupyter" ]
HTML between extension tags
39,562,731
<p>Lets say I have an extension in Jinja. I want the extension to have the form: </p> <pre><code>{% start %} &lt;h1&gt;{{ something }}&lt;/h1&gt; &lt;p&gt;{{ something.else }}&lt;/p&gt; {% for content in lst %} &lt;h3&gt;{{ i.name }}&lt;/h3&gt; {% endfor %} {% end %} </code></pre> <p>In my extension, I want to have access to the raw text between start and end, so this: </p> <pre><code>&lt;h1&gt;{{ something }}&lt;/h1&gt; &lt;p&gt;{{ something.else }}&lt;/p&gt; {% for content in lst %} &lt;h3&gt;{{ i.name }}&lt;/h3&gt; {% endfor %} </code></pre> <p>I would like that in my extension. How could I do that? I have poured over the jinja documentation to no avail. </p>
0
2016-09-18T21:12:19Z
39,586,483
<p>If your desire output is {{something}}, then you can use "raw" block in jinja.</p> <pre><code>{% raw %} &lt;h1&gt;{{ something }}&lt;/h1&gt; {% endraw %} </code></pre> <p>It will print "{{something}}" (with curly braces).</p>
0
2016-09-20T05:42:27Z
[ "python", "flask", "jinja2" ]
How to add new blank row in the middle of text in Google Docs when using gspread module for python?
39,562,807
<p>I tried to insert a new blank row example after 8 rows with <code>insert_row</code> or <code>append_row</code> or <code>add_row</code>, but they only add a new row in the end of the sheet.</p> <p>My question is how to correctly insert the row ?</p> <p>Also, I read <a href="http://gspread.readthedocs.io/en/latest/index.html?highlight=row" rel="nofollow">documentation</a> didn't find the needed class.</p>
0
2016-09-18T21:23:19Z
39,925,772
<p><a href="http://gspread.readthedocs.io/en/latest/index.html?highlight=row#gspread.Worksheet.insert_row" rel="nofollow">Worksheet.insert_row()</a> is the way to go</p> <p>Notice that you must supply the index for where the rows will be inserted.</p> <p>As for how to insert a certain number of rows your best bet is to use a for loop:</p> <pre><code>empty_row = ['' for cell in range(Worksheet.col_count)] insertion_row = 4 number_of_rows = 8 for row in range(number_of_rows): Worksheet.insert_row(empty_row,index=insertion_row) </code></pre> <p>Note that this will have to make as many API calls as the number of rows that you want to add and currently the insert_rows function is notoriously slow.</p>
0
2016-10-07T21:03:53Z
[ "python", "gspread" ]
How to find max in dataframe with in a certain length in python?
39,562,824
<p>Here's my DataFrame:</p> <pre><code>DATE_TIME 1997-02-25 12:50:00 3238.0 1997-02-25 12:55:00 3237.5 1997-02-25 13:00:00 3237.5 1997-02-25 13:05:00 3237.5 1997-02-25 13:10:00 3239.0 1997-02-25 13:15:00 3242.0 </code></pre> <p>I'm trying to find a way to find the max for every 2 intervals back and still keep in the DataFrame format. </p> <p>So I would like it to look like this.</p> <pre><code>DATE_TIME 1997-02-25 12:50:00 3238.0 1997-02-25 12:55:00 3238.0 1997-02-25 13:00:00 3238.0 1997-02-25 13:05:00 3237.5 1997-02-25 13:10:00 3239.0 1997-02-25 13:15:00 3242.0 </code></pre> <p>I've tried a variety of different things. Any help would be greatly appreciated.</p>
1
2016-09-18T21:24:58Z
39,562,852
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html" rel="nofollow">.rolling().max()</a> method:</p> <pre><code>In [141]: df Out[141]: DATE_TIME VAL 0 1997-02-25 12:50:00 3238.0 1 1997-02-25 12:55:00 3237.5 2 1997-02-25 13:00:00 3237.5 3 1997-02-25 13:05:00 3237.5 4 1997-02-25 13:10:00 3239.0 5 1997-02-25 13:15:00 3242.0 In [142]: df['roll_3_max'] = df['VAL'].rolling(3).max().bfill() In [143]: df Out[143]: DATE_TIME VAL roll_3_max 0 1997-02-25 12:50:00 3238.0 3238.0 1 1997-02-25 12:55:00 3237.5 3238.0 2 1997-02-25 13:00:00 3237.5 3238.0 3 1997-02-25 13:05:00 3237.5 3237.5 4 1997-02-25 13:10:00 3239.0 3239.0 5 1997-02-25 13:15:00 3242.0 3242.0 </code></pre> <p>Explanation:</p> <pre><code>In [140]: df['VAL'].rolling(3).max() Out[140]: 0 NaN 1 NaN 2 3238.0 3 3237.5 4 3239.0 5 3242.0 Name: VAL, dtype: float64 </code></pre>
1
2016-09-18T21:28:11Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Pandas groupby where all columns are added to a list prefixed by column name
39,562,915
<p>I have a CSV file that looks like this:</p> <pre><code>id1,feat1,feat2,feat3 a,b,asd,asg c,d,dg,ag a,e,sdg,as c,f,as,sdg c,g,adg,sd </code></pre> <p>I read it in to a dataframe with <code>df = pd.read_csv("file.csv")</code>.</p> <p>I would like group by <code>id1</code> and combine all the other columns in one line in the group with the header name added as a prefix. That is the output should be a data frame that looks like:</p> <pre><code>a [feat1=b,feat1=e,feat2=asd,feat2=sdg,feat3=asg,feat3=as] c [feat1=d,feat1=f,feat1=g,feat2=dg,feat2=as,feat2=adg,feat3=ag,feat3=sdg,feat3=sd] </code></pre> <p><code>df.groupby('id1')</code> will start me off but I am not sure where to go from there.</p> <p>What is a good way to do this?</p>
3
2016-09-18T21:35:22Z
39,568,940
<p>Applying this function will work:</p> <pre><code>def func(dfg): dfu = dfg.unstack() result = dfu.index.get_level_values(0) + '=' + dfu.values return result.tolist() df.groupby('id1').apply(func) </code></pre> <hr> <p><strong>Explanation</strong>: let's consider one group, for instance <code>dfg = df[df['id1'] == 'c']</code>.</p> <pre><code>dfg.unstack() Out[35]: id1 1 c 3 c 4 c feat1 1 d 3 f 4 g feat2 1 dg 3 as 4 adg feat3 1 ag 3 sdg 4 sd </code></pre> <p>By unstacking you get the values aligned with the column names (ignore the index values in between). All you need to do is concatenate:</p> <pre><code>dfu.index.get_level_values(0) + '=' + dfu.values Out[36]: Index(['feat1=d', 'feat1=f', 'feat1=g', 'feat2=dg', 'feat2=as', 'feat2=adg', 'feat3=ag', 'feat3=sdg', 'feat3=sd'], dtype='object') </code></pre> <p>Finally, convert to list before returning, otherwise you end up with index objects. </p>
1
2016-09-19T08:48:14Z
[ "python", "pandas" ]
Pandas groupby where all columns are added to a list prefixed by column name
39,562,915
<p>I have a CSV file that looks like this:</p> <pre><code>id1,feat1,feat2,feat3 a,b,asd,asg c,d,dg,ag a,e,sdg,as c,f,as,sdg c,g,adg,sd </code></pre> <p>I read it in to a dataframe with <code>df = pd.read_csv("file.csv")</code>.</p> <p>I would like group by <code>id1</code> and combine all the other columns in one line in the group with the header name added as a prefix. That is the output should be a data frame that looks like:</p> <pre><code>a [feat1=b,feat1=e,feat2=asd,feat2=sdg,feat3=asg,feat3=as] c [feat1=d,feat1=f,feat1=g,feat2=dg,feat2=as,feat2=adg,feat3=ag,feat3=sdg,feat3=sd] </code></pre> <p><code>df.groupby('id1')</code> will start me off but I am not sure where to go from there.</p> <p>What is a good way to do this?</p>
3
2016-09-18T21:35:22Z
39,568,945
<p>You can use a custom function and <code>apply</code> on the <code>groupby</code> object, the function calls <code>apply</code> again on the Series passed to zip the column names and values into a list, we then perform a list comprehension and return this inside a list as desired:</p> <pre><code>In [54]: def foo(x): l = (x.apply(lambda x: x.name + '=' + x)).values.tolist() return pd.Series([[i for j in l for i in j]]) ​ gp = df.groupby('id1')[['feat1','feat2','feat3']] gp1 = gp.apply(foo) gp1 Out[54]: 0 id1 a [feat1=b, feat2=asd, feat3=asg, feat1=e, feat2... c [feat1=d, feat2=dg, feat3=ag, feat1=f, feat2=a... </code></pre> <p>if we look at the contents we see that we have a list of the values:</p> <pre><code>In [55]: gp1.iloc[0].values Out[55]: array([['feat1=b', 'feat2=asd', 'feat3=asg', 'feat1=e', 'feat2=sdg', 'feat3=as']], dtype=object) </code></pre>
2
2016-09-19T08:48:33Z
[ "python", "pandas" ]
how i will remove widget with click button on another class (PyQt)
39,562,929
<p>there is an error, how can i provide this? i want to remove widgets with remove button. is this okay <code>self.removeButton.clicked.connect(self.removing.remove_widget)</code> ? i tried to connect another class with a pushbutton.</p> <pre><code>from PyQt4 import QtGui, QtCore import sys class Main(QtGui.QMainWindow): def __init__(self, parent = None): super(Main, self).__init__(parent) # main button self.addButton = QtGui.QPushButton('button to add other widgets') self.addButton.clicked.connect(self.addWidget) self.removing=Test() self.removeButton=QtGui.QPushButton("remove widget") self.removeButton.clicked.connect(self.removing.remove_widget) # scroll area widget contents - layout self.scrollLayout = QtGui.QFormLayout() # scroll area widget contents self.scrollWidget = QtGui.QWidget() self.scrollWidget.setLayout(self.scrollLayout) # scroll area self.scrollArea = QtGui.QScrollArea() self.scrollArea.setWidgetResizable(True) self.scrollArea.setWidget(self.scrollWidget) # main layout self.mainLayout = QtGui.QVBoxLayout() # add all main to the main vLayout self.mainLayout.addWidget(self.addButton) self.mainLayout.addWidget(self.removeButton) self.mainLayout.addWidget(self.scrollArea) # central widget self.centralWidget = QtGui.QWidget() self.centralWidget.setLayout(self.mainLayout) # set central widget self.setCentralWidget(self.centralWidget) def addWidget(self): self.scrollLayout.addRow(Test()) class Test(QtGui.QWidget): def __init__( self, parent=None): super(Test, self).__init__(parent) self.lineEdit = QtGui.QLineEdit('I am in Test widget') layout = QtGui.QHBoxLayout() layout.addWidget(self.lineEdit) self.setLayout(layout) def remove_widget(self): self.lineEdit.deleteLater() app = QtGui.QApplication(sys.argv) myWidget = Main() myWidget.show() app.exec_() </code></pre>
0
2016-09-18T21:37:51Z
39,565,252
<p>You created a new class Test, and connected the new Test then the button del it.</p> <p>You could try this.</p> <pre><code>self.kod = [] self.removeButton=QtWidgets.QPushButton("remove widget") self.removeButton.clicked.connect(self.remove_widget) ... def addWidget(self): temp = Test() self.kod.append(temp) self.scrollLayout.addRow(temp) def remove_widget(self): self.kod.pop().deleteLater() </code></pre>
0
2016-09-19T04:12:48Z
[ "python", "qt", "python-3.x", "pyqt", "pyqt4" ]
Error when running TensorFlow image retraining tutorial
39,562,938
<p>I have a very basic question about TensorFlow. I'm following the <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/index.html?index=..%2F..%2Findex#4" rel="nofollow">"TensorFlow for Poets" tutorial</a>, and I'm stuck at the image retraining, when I try to run this command:</p> <pre><code># python tensorflow/examples/image_retraining/retrain.py \ --bottleneck_dir=/tf_files/bottlenecks \ --how_many_training_steps 500 \ --model_dir=/tf_files/inception \ --output_graph=/tf_files/retrained_graph.pb \ --output_labels=/tf_files/retrained_labels.txt \ --image_dir /tf_files/flower_photos </code></pre> <p>I got an error: <code>"--bottleneck_dir=/tf_files/bottlenecks: No such file or directory"</code></p> <p>I have installed TensorFlow using Anaconda installation, and I didn't install Docker as it was recommended in the codelab tutorial. So my question is what am I doing wrong? Is it necessary to install Docker Toolbox? </p>
0
2016-09-18T21:40:07Z
39,563,170
<p>From the error message, it looks like you have pasted the exact command from your question (and from the original tutorial) into the shell, and the <code>#</code> at the beginning was interpreted as a comment, and it's trying to execute the second line as a command.</p> <p>If you paste the command <strong>without the <code>#</code></strong>, it should work:</p> <pre><code>python tensorflow/examples/image_retraining/retrain.py \ --bottleneck_dir=/tf_files/bottlenecks \ --how_many_training_steps 500 \ --model_dir=/tf_files/inception \ --output_graph=/tf_files/retrained_graph.pb \ --output_labels=/tf_files/retrained_labels.txt \ --image_dir /tf_files/flower_photos </code></pre> <p>This looks like a bug in the tutorial&mdash;the second command on the same page doesn't have the <code>#</code>&mdash;so I've filed a <a href="https://github.com/tensorflow/tensorflow/issues/4444" rel="nofollow">GitHub issue</a> to get this fixed.</p>
2
2016-09-18T22:14:25Z
[ "python", "tensorflow" ]
predict external dataset with models from random forest
39,562,939
<p>I used <code>joblib.dump</code> in python to save models from 5 fold cross validation modelling using random forest. As a result I have 5 models for each dataset saved as: <code>MDL_1.pkl, MDL_2.pkl, MDL_3.pkl, MDL_4.pkl, MDL_5.pkl</code>. Now I want to use these models for prediction of external dataset using <code>predict_proba</code> when the final prediction for each line in my external dataset is an average of 5 models. What is the best way to proceed? Thank you for your help </p>
0
2016-09-18T21:40:11Z
39,563,394
<p>First of all, you should not save the result of cross validation. Cross validation <strong>is not</strong> a training method, it is <strong>an evaluation scheme</strong>. You should build <strong>a single model</strong> on your whole dataset and use it to predict.</p> <p>If, for some reason, you can no longer train your model, you can still use this 5 predictions by averaging them (as random forest itself is a simple averagin ensemble of trees), however going back and retraining should give you <strong>bettter</strong> results.</p>
0
2016-09-18T22:54:45Z
[ "python" ]
`Iterable[(int, int)]` tuple is not allowed in type hints
39,562,977
<p>I have this very simple code:</p> <pre><code>from typing import List, Iterable Position = (int, int) IntegerMatrix = List[List[int]] def locate_zeros(matrix: IntegerMatrix) -&gt; Iterable[Position]: """Given an NxM matrix find the positions that contain a zero.""" for row_num, row in enumerate(matrix): for col_num, element in enumerate(row): if element == 0: yield (col_num, row_num) </code></pre> <p>This is the error:</p> <pre><code>Traceback (most recent call last): File "type_m.py", line 6, in &lt;module&gt; def locate_zeros(matrix: IntegerMatrix) -&gt; Iterable[Position]: File "/usr/lib/python3.5/typing.py", line 970, in __getitem__ (len(self.__parameters__), len(params))) TypeError: Cannot change parameter count from 1 to 2 </code></pre> <p>Why can't I have an iterable of Int pairs as the return type?</p> <p>Both <code>-&gt; Position</code> and <code>Iterable[Any]</code> work, just not <code>Iterable</code> and <code>Position</code> together don't.</p>
4
2016-09-18T21:44:15Z
39,563,026
<p>You should use <code>typing.Tuple[int, int]</code> to declare the tuple type <code>Position</code>, not <code>(int, int)</code>.</p>
5
2016-09-18T21:53:04Z
[ "python", "python-3.5", "typing" ]
Counting values using pandas groupby
39,563,028
<p>Here is my data frame</p> <pre><code>data = {'Date' : ['08/20/10','08/20/10','08/20/10','08/21/10','08/22/10','08/24/10','08/25/10','08/26/10'] , 'Receipt' : [10001,10001,10002,10002,10003,10004,10004,10004], 'Product' : ['xx1','xx2','yy1','fff4','gggg4','fsf4','gggh5','hhhg6']} dfTest = pd.DataFrame(data) dfTest </code></pre> <p>This will produce:</p> <pre><code> Date Product Receipt 0 08/20/10 xx1 10001 1 08/20/10 xx2 10001 2 08/20/10 yy1 10002 3 08/21/10 fff4 10002 4 08/22/10 gggg4 10003 5 08/24/10 fsf4 10004 6 08/25/10 gggh5 10004 7 08/26/10 hhhg6 10004 </code></pre> <p>I want to get the number of unique receipts per day.</p> <p>Heres what I did:</p> <pre><code>dfTest.groupby(['Date','Receipt']).count() Product Date Receipt 08/20/10 10001 2 10002 1 08/21/10 10002 1 08/22/10 10003 1 08/24/10 10004 1 08/25/10 10004 1 08/26/10 10004 1 </code></pre> <p>I'm confused with this kind of index presentation so i reset it.</p> <pre><code>df2 = dfTest.groupby(['Date','Receipt']).count().reset_index() df2 Date Receipt Product 0 08/20/10 10001 2 1 08/20/10 10002 1 2 08/21/10 10002 1 3 08/22/10 10003 1 4 08/24/10 10004 1 5 08/25/10 10004 1 6 08/26/10 10004 1 </code></pre> <p>Now I grouped it by Date then showing only the Receipt count.</p> <p>df2.groupby(['Date'])['Receipt'].count()</p> <pre><code>Date 08/20/10 2 08/21/10 1 08/22/10 1 08/24/10 1 08/25/10 1 08/26/10 1 Name: Receipt, dtype: int64 </code></pre> <p>There I got the number of unique receipts per day. I'm thinking the way I came up with my solution is a bit crude. Is there a better way of doing what I intend to do?</p>
2
2016-09-18T21:53:21Z
39,563,053
<p>try this:</p> <pre><code>In [191]: dfTest.groupby('Date').Receipt.nunique() Out[191]: Date 08/20/10 2 08/21/10 1 08/22/10 1 08/24/10 1 08/25/10 1 08/26/10 1 Name: Receipt, dtype: int64 </code></pre> <p>or this, depending on your goal:</p> <pre><code>In [188]: dfTest.groupby(['Date','Receipt']).Product.nunique().reset_index(level=1, drop=True) Out[188]: Date 08/20/10 2 08/20/10 1 08/21/10 1 08/22/10 1 08/24/10 1 08/25/10 1 08/26/10 1 Name: Product, dtype: int64 </code></pre>
2
2016-09-18T21:56:38Z
[ "python", "pandas", "dataframe", "group-by" ]
Downloading dynamically loaded webpage with python
39,563,192
<p>I have this <a href="http://bonusbagging.co.uk/oddsmatching.php#" rel="nofollow">website</a> and I want to download the content of the page.</p> <p>I tried <strong>selenium</strong>, and button clicking with it, but with no success.</p> <pre><code>#!/usr/bin/env python from contextlib import closing from selenium.webdriver import Firefox import time # use firefox to get page with javascript generated content with closing(Firefox()) as browser: # setting the url browser.get("http://bonusbagging.co.uk/oddsmatching.php#") # finding and clicking the button button = browser.find_element_by_id('select_button') button.click() page = browser.page_source time.sleep(5) print(page.encode("utf8")) </code></pre> <p>This code only downloads the source code, where the data are hidden.</p> <p>Can someone show me the right way to do that? Or tell my how can be the hidden data downloaded?</p> <p>Thanks in advance!</p>
1
2016-09-18T22:17:47Z
39,563,753
<p>I always try to avoid selenium like the plague when scraping; it's very slow and is almost never the best way to go about things. You should dig into the source more before scraping; it was clear on this page that the html was coming in and then a separate call was being made to get the table's data. Why not make the same call as the page? It's lightning fast and requires no html parsing; just returns raw data, which seems to be what you're looking for. the python <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> import is perfect for this. Happy Scraping!</p> <pre><code>import requests table_data = requests.get('http://bonusbagging.co.uk/odds-server/getdata_slow.php').content </code></pre> <p>PS: The best way to look for these calls is to open the dev console, and check out the network tab. You can see what calls are being made here. Another way is to go to the sources tab, look for some javascript, and search for ajax calls (that's where I got the url I'm calling to above, the path was: top/odds-server.com/odds-server/js/table_slow.js). The later option is sometimes easier, sometimes it's nearly impossible (if the file is minified/uglified). Do whatever works for you!</p>
1
2016-09-19T00:04:18Z
[ "javascript", "jquery", "python", "html", "selenium" ]
Downloading dynamically loaded webpage with python
39,563,192
<p>I have this <a href="http://bonusbagging.co.uk/oddsmatching.php#" rel="nofollow">website</a> and I want to download the content of the page.</p> <p>I tried <strong>selenium</strong>, and button clicking with it, but with no success.</p> <pre><code>#!/usr/bin/env python from contextlib import closing from selenium.webdriver import Firefox import time # use firefox to get page with javascript generated content with closing(Firefox()) as browser: # setting the url browser.get("http://bonusbagging.co.uk/oddsmatching.php#") # finding and clicking the button button = browser.find_element_by_id('select_button') button.click() page = browser.page_source time.sleep(5) print(page.encode("utf8")) </code></pre> <p>This code only downloads the source code, where the data are hidden.</p> <p>Can someone show me the right way to do that? Or tell my how can be the hidden data downloaded?</p> <p>Thanks in advance!</p>
1
2016-09-18T22:17:47Z
39,563,813
<p>Check out the Network tab in Chrome Dev tools. Nab <a href="http://bonusbagging.co.uk/odds-server/getdata_slow.php?draw=1&amp;columns%5B0%5D%5Bdata%5D=rating&amp;columns%5B0%5D%5Bname%5D=&amp;columns%5B0%5D%5Bsearchable%5D=true&amp;columns%5B0%5D%5Borderable%5D=true&amp;columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B1%5D%5Bdata%5D=sport&amp;columns%5B1%5D%5Bname%5D=&amp;columns%5B1%5D%5Bsearchable%5D=true&amp;columns%5B1%5D%5Borderable%5D=true&amp;columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B2%5D%5Bdata%5D=date&amp;columns%5B2%5D%5Bname%5D=&amp;columns%5B2%5D%5Bsearchable%5D=true&amp;columns%5B2%5D%5Borderable%5D=true&amp;columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B3%5D%5Bdata%5D=event_name&amp;columns%5B3%5D%5Bname%5D=&amp;columns%5B3%5D%5Bsearchable%5D=true&amp;columns%5B3%5D%5Borderable%5D=true&amp;columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B4%5D%5Bdata%5D=competition&amp;columns%5B4%5D%5Bname%5D=&amp;columns%5B4%5D%5Bsearchable%5D=true&amp;columns%5B4%5D%5Borderable%5D=true&amp;columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B5%5D%5Bdata%5D=runner_name&amp;columns%5B5%5D%5Bname%5D=&amp;columns%5B5%5D%5Bsearchable%5D=true&amp;columns%5B5%5D%5Borderable%5D=true&amp;columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B6%5D%5Bdata%5D=market_name&amp;columns%5B6%5D%5Bname%5D=&amp;columns%5B6%5D%5Bsearchable%5D=true&amp;columns%5B6%5D%5Borderable%5D=true&amp;columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B6%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B7%5D%5Bdata%5D=bookmaker_name&amp;columns%5B7%5D%5Bname%5D=&amp;columns%5B7%5D%5Bsearchable%5D=true&amp;columns%5B7%5D%5Borderable%5D=true&amp;columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B8%5D%5Bdata%5D=bookmaker_odds&amp;columns%5B8%5D%5Bname%5D=&amp;columns%5B8%5D%5Bsearchable%5D=true&amp;columns%5B8%5D%5Borderable%5D=true&amp;columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B8%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B9%5D%5Bdata%5D=betfair_odds&amp;columns%5B9%5D%5Bname%5D=&amp;columns%5B9%5D%5Bsearchable%5D=true&amp;columns%5B9%5D%5Borderable%5D=true&amp;columns%5B9%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B9%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B10%5D%5Bdata%5D=exchange&amp;columns%5B10%5D%5Bname%5D=&amp;columns%5B10%5D%5Bsearchable%5D=true&amp;columns%5B10%5D%5Borderable%5D=true&amp;columns%5B10%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B10%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B11%5D%5Bdata%5D=betfair_size&amp;columns%5B11%5D%5Bname%5D=&amp;columns%5B11%5D%5Bsearchable%5D=true&amp;columns%5B11%5D%5Borderable%5D=true&amp;columns%5B11%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B11%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B12%5D%5Bdata%5D=retention&amp;columns%5B12%5D%5Bname%5D=&amp;columns%5B12%5D%5Bsearchable%5D=true&amp;columns%5B12%5D%5Borderable%5D=true&amp;columns%5B12%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B12%5D%5Bsearch%5D%5Bregex%5D=false&amp;order%5B0%5D%5Bcolumn%5D=0&amp;order%5B0%5D%5Bdir%5D=desc&amp;start=0&amp;length=100&amp;search%5Bvalue%5D=&amp;search%5Bregex%5D=false&amp;_=1474243773364" rel="nofollow">the URL</a> out of there.</p> <p><img src="http://i.imgur.com/FQK3hLM.png" alt=""></p> <p>What you're looking at is a <a href="https://datatables.net/" rel="nofollow">DataTable</a>. You can use their API to fetch what you need.</p> <p>Adjust the "start" and/or "length" parameters to fetch the data page-by-page.</p> <p>It's JSON data, so it'll be super easy to parse.</p> <p>But be nice and don't hammer this poor guy's server.</p>
0
2016-09-19T00:14:57Z
[ "javascript", "jquery", "python", "html", "selenium" ]
Unable to delete first row in matrix
39,563,209
<p>I am stuck when trying to delete the first row from the <code>log_returns</code> matrix. Essentially, I'd like to get rid of the first row because it has NaN values. I have tried <code>isnan()</code> without joy, and finally landed on the <code>numpy.delete()</code> method which sounds most promising but still doesn't achieve the purpose.</p> <pre><code>import pandas as pd from pandas_datareader import data as web import numpy as np symbols = ['XOM', 'CVX', 'SLB', 'PXD', 'EOG', 'OXY', 'HAL', 'KMI', 'SE', 'PSX', 'VLO','COP','APC','TSO','WMB','BHI','APA','COG','DVN','MPC','NBL','CXO','NOV','HES','MRO','EQT','XEC','FTI','RRC','OKE','SWN','NFX','HP','MUR','CHK','RIG','DO'] try: h9 = pd.HDFStore('port.h9') data = h9['norm'] h9.close() except: data = pd.DataFrame() for sym in symbols: data[sym] = web.DataReader(sym, data_source='yahoo', start='1/1/2010')['Adj Close'] data = data.dropna() h9 = pd.HDFStore('port.h9') h9['norm'] = data h9.close() data.info() log_returns = np.log(data / data.shift(1)) log_returns.head() np.delete(log_returns, 0, 0) </code></pre> <p>The last line (to delete) above throws the following exception, which doesn't make sense as <code>row = 0</code>, <code>location = 0</code> is surely not out of scope of the <code>log_returns</code> matrix which is of shape (1116,37).</p> <pre><code>ValueError: Shape of passed values is (37, 1115), indices imply (37, 1116) </code></pre>
1
2016-09-18T22:20:20Z
39,563,261
<p>Demo:</p> <pre><code>In [202]: from pandas_datareader import data as web In [218]: df = web.DataReader('XOM', 'yahoo', start='1/1/2010')['Adj Close'] In [219]: pd.options.display.max_rows = 10 In [220]: df Out[220]: Date 2010-01-04 57.203028 2010-01-05 57.426378 2010-01-06 57.922715 2010-01-07 57.740730 2010-01-08 57.509100 ... 2016-09-12 87.290001 2016-09-13 85.209999 2016-09-14 84.599998 2016-09-15 85.080002 2016-09-16 84.029999 Name: Adj Close, dtype: float64 In [221]: np.log(df.head(10).pct_change() + 1) Out[221]: Date 2010-01-04 NaN 2010-01-05 0.003897 2010-01-06 0.008606 2010-01-07 -0.003147 2010-01-08 -0.004020 2010-01-11 0.011157 2010-01-12 -0.004991 2010-01-13 -0.004011 2010-01-14 0.000144 2010-01-15 -0.008214 Name: Adj Close, dtype: float64 </code></pre> <p>Solution:</p> <pre><code>In [224]: np.log(df.pct_change() + 1).dropna() Out[224]: Date 2010-01-05 0.003897 2010-01-06 0.008606 2010-01-07 -0.003147 2010-01-08 -0.004020 2010-01-11 0.011157 ... 2016-09-12 0.005169 2016-09-13 -0.024117 2016-09-14 -0.007185 2016-09-15 0.005658 2016-09-16 -0.012418 Name: Adj Close, dtype: float64 </code></pre> <p>or:</p> <pre><code>In [225]: np.log(df.pct_change() + 1).iloc[1:] Out[225]: Date 2010-01-05 0.003897 2010-01-06 0.008606 2010-01-07 -0.003147 2010-01-08 -0.004020 2010-01-11 0.011157 ... 2016-09-12 0.005169 2016-09-13 -0.024117 2016-09-14 -0.007185 2016-09-15 0.005658 2016-09-16 -0.012418 Name: Adj Close, dtype: float64 </code></pre> <p>or:</p> <pre><code>In [227]: np.log(df.pct_change() + 1).drop(df.index[0]) Out[227]: Date 2010-01-05 0.003897 2010-01-06 0.008606 2010-01-07 -0.003147 2010-01-08 -0.004020 2010-01-11 0.011157 ... 2016-09-12 0.005169 2016-09-13 -0.024117 2016-09-14 -0.007185 2016-09-15 0.005658 2016-09-16 -0.012418 Name: Adj Close, dtype: float64 </code></pre>
0
2016-09-18T22:31:24Z
[ "python", "pandas", "numpy", "dataframe" ]
AI multiple input conversation with if statements in while loop doesn't work?
39,563,226
<p>My AI i am making works in a while loop there are if statements for everything i want it to say for example:</p> <pre><code>`while 1: lis = ("im bored","game","im board","what do you want to do","what should we do","rage","i","I","smashed","broke","destroyed","cracked","grounded","detention","in trouble","nothing","not much","erics number","date","time","no","nope","nah","not","yes","yep","yeah","in deed","bye","gtg","got to go","see you","c u","hi","hello","hello","hia","fuck","crap","shit","bleep","omg","OMG","oh my god","","","","","","look up","email","map","add Note","get Note","joke","rabid donkey","game","quit","help","raging","hurt","fire","","thanos","erics mad","danger","sad","upset","","","creator","thanks","lol","ok","k","yep","report","owner","maker","jarvis","coder","thank you","sup","whats up","what's up","hey","hah") resp2 = input("") esa = "" for word in lis: if word in resp2: esa = word if esa in ("quit","bye","gtg","got to go","see you","c u"): byebro = random.choice(("ok bye Sergei cu later","bye sir","c u later sir","talk to you later then","talk to you later")) print (byebro) os.system("say '"+byebro+"'") exit() if esa in ("look up","web search","search the web for"): c = random.choice(("ok","lets see","let me see","ok sir il get right on that lets see","im looking up and i dont see anything??")) print (c) c1 = ("sorry an error has acurred package missing") print (c1) os.system("say '"+c+"'") os.system("say '"+c1+"'") break if esa == "add note": d = random.choice(("ok sir one sec il pull up the note pad","ok sir one sec","yeah one sec il pull it up","one sec sir","ok","ok sir")) print (d) os.system("say '"+d+"'") note1 = input("") notes.append(note1) break if esa == "get note": e = random.choice(("ok sir one sec il pull up the your recent notes","ok sir one sec","yeah one sec il pull it up","one sec sir","ok","ok sir notes","ok sir")) print (e) os.system("say '"+e+"'") </code></pre> <p>ok so there are hundreds of these if statements but i want to be able to talk to jarvis like this. where i can say something and then he will ask me about it then i will answer then he answers then it breaks out of the if statement and goes through the loop and all the if statements again.</p> <p>me: i am grounded jarvis</p> <p>jarvis: what did you do?</p> <p>me: i smashed a window</p> <p>jarvis: oh ok</p> <p>so i want the code to look like this but it doesn't work</p> <pre><code>if esa in ("im grounded","im in trouble","i got detention"): print "your always getting in trouble its like second nature to you" esa3 = input("what did you do") if esa3 in ("i broke something","i smashed something"): print "your always breaking stuff" </code></pre>
-3
2016-09-18T22:23:58Z
39,968,262
<p>i figured it out you need to put an if statement inside the if statement</p> <pre><code>if esa in ("im grounded","im in trouble","i have detention","i got detention"): punish = random.choice(("your always getting in trouble its like second nature for you lol","to bad i guess no fun for a while well its your fault lol","did you and eric do somthing stupid?!")) print(punish) os.system("say '"+punish+"'") wdydQ = random.choice(("what did you do!!?!!","what did you do this time","can you go one week with out geting exspelled or suspended or in trouble what did you do!!")) print (wdydQ) os.system("say '"+wdydQ+"'") lisgrd = ("i broke","i smashed","i destroyed","i cracked","i hit","i didn't","i hurt","i jumped","i had sex","i went to") respgrd = input("") esagrd = "" for wordgrd in lisgrd: if wordgrd in respgrd: esagrd = wordgrd if esagrd in ("i broke","i smashed","i destroyed","i cracked"): YbsA = random.choice(("your always breaking shit","im not paying for it this time and niether am i taking the blame!")) print (YbsA) os.system("say '"+YbsA+"'") break elif esagrd in ("i hit","i didn't","i hurt","i jumped","i had sex","i went to"): grd33 = random.choice(("i dont know what to say now","oh my god","your fing mental","are you kidding me")) print (grd33) os.system("say '"+grd33+"'") break elif esagrd in ("nothing","i dont know","i don't know","um"): grdq12 = random.choice(("don't bs me whatcha do!!","just tell me what happened","whatever")) print (grdq12) os.system("say '"+grdq12+"'") continue </code></pre>
0
2016-10-10T23:28:10Z
[ "python", "string", "python-3.x", "if-statement", "while-loop" ]
How to write a dict to a csv
39,563,314
<p>I have a CSV file with one column that has a person's first and last name. I am trying to use a CSV to split each name into two columns, first and last. The code below splits all of the first names into one row and all of the last names into one row instead of having a first name into a row and the last name in the next column next the the first name. Thanks for your time.</p> <p>Code: import csv</p> <pre><code>with open('fullnames.csv','r') as f: reader = csv.reader(f) newcsvdict = {"first name": [], "last name": []} for row in reader: first = row[0].split()[0] last = row[0].split()[1] newcsvdict["first name"].append(first) newcsvdict["last name"].append(last) with open('new.csv','w') as f: w = csv.DictWriter(f, newcsvdict.keys()) w.writeheader() w.writerow(newcsvdict) </code></pre> <p>Output: <a href="http://i.stack.imgur.com/5cOcI.png" rel="nofollow"><img src="http://i.stack.imgur.com/5cOcI.png" alt="enter image description here"></a></p>
0
2016-09-18T22:41:18Z
39,563,404
<p>You can use pandas to write your csv (you could actually use pandas for the whole problem), this will automatically transpose you data from a dict of columns to a list of rows:</p> <pre><code>import pandas as pd df = pd.DataFrame(newcsvdict) df.to_csv('new.csv', index=False) </code></pre>
0
2016-09-18T22:56:33Z
[ "python" ]
How to write a dict to a csv
39,563,314
<p>I have a CSV file with one column that has a person's first and last name. I am trying to use a CSV to split each name into two columns, first and last. The code below splits all of the first names into one row and all of the last names into one row instead of having a first name into a row and the last name in the next column next the the first name. Thanks for your time.</p> <p>Code: import csv</p> <pre><code>with open('fullnames.csv','r') as f: reader = csv.reader(f) newcsvdict = {"first name": [], "last name": []} for row in reader: first = row[0].split()[0] last = row[0].split()[1] newcsvdict["first name"].append(first) newcsvdict["last name"].append(last) with open('new.csv','w') as f: w = csv.DictWriter(f, newcsvdict.keys()) w.writeheader() w.writerow(newcsvdict) </code></pre> <p>Output: <a href="http://i.stack.imgur.com/5cOcI.png" rel="nofollow"><img src="http://i.stack.imgur.com/5cOcI.png" alt="enter image description here"></a></p>
0
2016-09-18T22:41:18Z
39,563,477
<p>You're creating a single list associated with key. Either use Pandas, as @maxymoo suggested, or write each line separately.</p> <pre><code>import csv with open(r'~/Documents/names.csv', 'r') as fh: reader = csv.reader(fh) with open(r'~/Documents/output.csv', 'w+') as o: writer = csv.writer(o) for row in reader: output = row[0].split(' ', 1) writer.writerow(output) </code></pre>
0
2016-09-18T23:08:07Z
[ "python" ]
How to write a dict to a csv
39,563,314
<p>I have a CSV file with one column that has a person's first and last name. I am trying to use a CSV to split each name into two columns, first and last. The code below splits all of the first names into one row and all of the last names into one row instead of having a first name into a row and the last name in the next column next the the first name. Thanks for your time.</p> <p>Code: import csv</p> <pre><code>with open('fullnames.csv','r') as f: reader = csv.reader(f) newcsvdict = {"first name": [], "last name": []} for row in reader: first = row[0].split()[0] last = row[0].split()[1] newcsvdict["first name"].append(first) newcsvdict["last name"].append(last) with open('new.csv','w') as f: w = csv.DictWriter(f, newcsvdict.keys()) w.writeheader() w.writerow(newcsvdict) </code></pre> <p>Output: <a href="http://i.stack.imgur.com/5cOcI.png" rel="nofollow"><img src="http://i.stack.imgur.com/5cOcI.png" alt="enter image description here"></a></p>
0
2016-09-18T22:41:18Z
39,563,727
<p>In this simple case there is little benefit in using a <code>csv.DictWriter</code>, just use <code>csv.writer</code>:</p> <pre><code>import csv header = ['first name', 'last name'] with open('fullnames.csv', 'r') as infile, open('new.csv', 'w') as outfile: writer = csv.writer(outfile) writer.writerow(header) writer.writerows(row[0].split() for row in csv.reader(infile)) </code></pre> <p>This works fine provided that the name column in the input CSV always consists of exactly one first name and one surname separated by whitespace. However, if there can be double-barrelled surnames, e.g. Helena Bonham Carter, you need to be more careful about splitting the name. This might work:</p> <pre><code>row[0].split(' ', 1) </code></pre> <p>but it assumes that the separator is exactly one space.</p>
1
2016-09-18T23:58:26Z
[ "python" ]
How to pull discount rate from if statement
39,563,430
<p>I need to calculate the total purchase price of the books. The discount is determined by the amount of books purchased. Those are split within the if statements. How can I have my code fully work? I am currently getting this error message: </p> <p><a href="http://i.stack.imgur.com/GyRhK.png" rel="nofollow"><img src="http://i.stack.imgur.com/GyRhK.png" alt="Error message that is displayed"></a></p> <p>Here's my code:</p> <pre><code>BOOK_PRICE = 100 def main(): numBooks = int(input("Enter the number of books you will be purchasing: ")) discountPrice(numBooks) subTotalPrice(numBooks) #I have a problem getting the returned subTotal price totalPrice(theSubTotalPrice,discountRate) def subTotalPrice (numBooks): theSubTotalPrice = numBooks * BOOK_PRICE print("Your subTotal is: $ ",theSubTotalPrice) return theSubTotalPrice def totalPrice (theSubTotalPrice): theTotalPrice = theSubTotalPrice * discountRate print("Your Total Price is: $ ", theTotalPrice) def discountPrice (numBooks): if numBooks &lt;= 0 and numBooks &lt;= 9: print(" ") discountRate = .00 return discountRate if numBooks &gt;= 10 and numBooks &lt;= 19: print("Since you are ordering",numBooks,"books you will receive a 20% discount!") #how do any of these discountRates get put back to call them in a different module? discountRate = .20 return discountRate if numBooks &gt;= 20 and numBooks &lt;= 49: print("Since you are ordering",numBooks,"books you will receive a 30% discount!") discountRate = .30 return discountRate if numBooks &gt;= 50 and numBooks &lt;= 99: print("Since you are ordering",numBooks,"books you will receive a 40% discount!") discountRate = .40 return discountRate if numBooks &gt;= 100: print("Since you are ordering",numBooks,"books you will receive a 50% discount!") discountRate = .50 return discountRate main() </code></pre>
0
2016-09-18T23:00:46Z
39,563,454
<p>Your last function is currently written as</p> <pre><code>def totalPrice(theTotalPrice): </code></pre> <p>but your argument should be</p> <pre><code>def totalPrice(numBooks): </code></pre> <p>In fact, you appear to pass the correct argument to this function in <code>main</code>, it is just a mistake in the actual function definition.</p> <p>In general, if you see errors like "(some variable) is not defined", ensure that the variable is in scope, by passing the correct function arguments.</p>
0
2016-09-18T23:04:34Z
[ "python", "if-statement", "module" ]
How to pull discount rate from if statement
39,563,430
<p>I need to calculate the total purchase price of the books. The discount is determined by the amount of books purchased. Those are split within the if statements. How can I have my code fully work? I am currently getting this error message: </p> <p><a href="http://i.stack.imgur.com/GyRhK.png" rel="nofollow"><img src="http://i.stack.imgur.com/GyRhK.png" alt="Error message that is displayed"></a></p> <p>Here's my code:</p> <pre><code>BOOK_PRICE = 100 def main(): numBooks = int(input("Enter the number of books you will be purchasing: ")) discountPrice(numBooks) subTotalPrice(numBooks) #I have a problem getting the returned subTotal price totalPrice(theSubTotalPrice,discountRate) def subTotalPrice (numBooks): theSubTotalPrice = numBooks * BOOK_PRICE print("Your subTotal is: $ ",theSubTotalPrice) return theSubTotalPrice def totalPrice (theSubTotalPrice): theTotalPrice = theSubTotalPrice * discountRate print("Your Total Price is: $ ", theTotalPrice) def discountPrice (numBooks): if numBooks &lt;= 0 and numBooks &lt;= 9: print(" ") discountRate = .00 return discountRate if numBooks &gt;= 10 and numBooks &lt;= 19: print("Since you are ordering",numBooks,"books you will receive a 20% discount!") #how do any of these discountRates get put back to call them in a different module? discountRate = .20 return discountRate if numBooks &gt;= 20 and numBooks &lt;= 49: print("Since you are ordering",numBooks,"books you will receive a 30% discount!") discountRate = .30 return discountRate if numBooks &gt;= 50 and numBooks &lt;= 99: print("Since you are ordering",numBooks,"books you will receive a 40% discount!") discountRate = .40 return discountRate if numBooks &gt;= 100: print("Since you are ordering",numBooks,"books you will receive a 50% discount!") discountRate = .50 return discountRate main() </code></pre>
0
2016-09-18T23:00:46Z
39,563,535
<p>Basically, you're not giving your functions all the variables that they need. In <code>eligibleDiscounts</code> you reference a variable <code>totalPrice</code>. Where is that value being defined? Is it meant to be <code>BOOK_PRICE * numBooks</code>?</p> <p>Similar thing in <code>totalPrice</code>. If you want it to know about <code>numBooks</code>, you need to pass <code>numBooks</code> in. </p> <p>I think what you want to do is calculate the <code>totalPrice</code>, and pass that into <code>eligibleDiscount</code>. Then have <code>eligibleDiscount</code> return <code>discountRate</code>. I.e. end with <code>return discountRate</code>. Which should be defined under each <code>if</code>/<code>elif</code> statement. Not just the last one.</p> <p>Then pass everything into <code>totalPrice</code>.</p>
0
2016-09-18T23:18:45Z
[ "python", "if-statement", "module" ]
How to pull discount rate from if statement
39,563,430
<p>I need to calculate the total purchase price of the books. The discount is determined by the amount of books purchased. Those are split within the if statements. How can I have my code fully work? I am currently getting this error message: </p> <p><a href="http://i.stack.imgur.com/GyRhK.png" rel="nofollow"><img src="http://i.stack.imgur.com/GyRhK.png" alt="Error message that is displayed"></a></p> <p>Here's my code:</p> <pre><code>BOOK_PRICE = 100 def main(): numBooks = int(input("Enter the number of books you will be purchasing: ")) discountPrice(numBooks) subTotalPrice(numBooks) #I have a problem getting the returned subTotal price totalPrice(theSubTotalPrice,discountRate) def subTotalPrice (numBooks): theSubTotalPrice = numBooks * BOOK_PRICE print("Your subTotal is: $ ",theSubTotalPrice) return theSubTotalPrice def totalPrice (theSubTotalPrice): theTotalPrice = theSubTotalPrice * discountRate print("Your Total Price is: $ ", theTotalPrice) def discountPrice (numBooks): if numBooks &lt;= 0 and numBooks &lt;= 9: print(" ") discountRate = .00 return discountRate if numBooks &gt;= 10 and numBooks &lt;= 19: print("Since you are ordering",numBooks,"books you will receive a 20% discount!") #how do any of these discountRates get put back to call them in a different module? discountRate = .20 return discountRate if numBooks &gt;= 20 and numBooks &lt;= 49: print("Since you are ordering",numBooks,"books you will receive a 30% discount!") discountRate = .30 return discountRate if numBooks &gt;= 50 and numBooks &lt;= 99: print("Since you are ordering",numBooks,"books you will receive a 40% discount!") discountRate = .40 return discountRate if numBooks &gt;= 100: print("Since you are ordering",numBooks,"books you will receive a 50% discount!") discountRate = .50 return discountRate main() </code></pre>
0
2016-09-18T23:00:46Z
39,563,975
<p>Here is the edited code. The first error was that you were returning the values from the functions, but there was no variable being assigned to the return value. Variables created inside a function lives only inside the function. Study the code below and see what changes I made. Ask if you have questions. Also you had another bug. You have numBooks &lt;=0 as a condition. It should be numBooks >= 0. One last thing, thanks for the copy and paste instead of screenshot.</p> <pre><code>BOOK_PRICE = 100 def main(): numBooks = int(input("Enter the number of books you will be purchasing: ")) discountRate = discountPrice(numBooks) theSubTotalPrice = subTotalPrice(numBooks) #I have a problem getting the returned subTotal price totalPrice(theSubTotalPrice,discountRate) def subTotalPrice (numBooks): theSubTotalPrice = numBooks * BOOK_PRICE print("Your subTotal is: $ ",theSubTotalPrice) return theSubTotalPrice def totalPrice (theSubTotalPrice, discountRate): totalDiscount = theSubTotalPrice * discountRate theTotalPrice = theSubTotalPrice - totalDiscount print("Your Discount is: $ ", totalDiscount) print("Your Total Price is: $ ", theTotalPrice) def discountPrice (numBooks): if numBooks &gt;= 0 and numBooks &lt;= 9: print(" ") discountRate = 0.00 return discountRate if numBooks &gt;= 10 and numBooks &lt;= 19: print("Since you are ordering",numBooks,"books you will receive a 20% discount!") #how do any of these discountRates get put back to call them in a different module? discountRate = .20 return discountRate if numBooks &gt;= 20 and numBooks &lt;= 49: print("Since you are ordering",numBooks,"books you will receive a 30% discount!") discountRate = .30 return discountRate if numBooks &gt;= 50 and numBooks &lt;= 99: print("Since you are ordering",numBooks,"books you will receive a 40% discount!") discountRate = .40 return discountRate if numBooks &gt;= 100: print("Since you are ordering",numBooks,"books you will receive a 50% discount!") discountRate = .50 return discountRate main() </code></pre> <p>Here is what I get when I ran it with various inputs:</p> <pre><code>&gt;&gt;&gt; ===== RESTART: C:\Users\Joe\Desktop\scripts\Stack_overflow\book_price.py ===== Enter the number of books you will be purchasing: 9 Your subTotal is: $ 900 Your Total Price is: $ 0.0 &gt;&gt;&gt; ===== RESTART: C:\Users\Joe\Desktop\scripts\Stack_overflow\book_price.py ===== Enter the number of books you will be purchasing: 9 Your subTotal is: $ 900 Your Total Price is: $ 0.0 &gt;&gt;&gt; ===== RESTART: C:\Users\Joe\Desktop\scripts\Stack_overflow\book_price.py ===== Enter the number of books you will be purchasing: 19 Since you are ordering 19 books you will receive a 20% discount! # I need to take these two values and subtract them. 1900(subtotal) - 380 (discountprice) Your subTotal is: $ 1900 Your Total Price is: $ 380.0 &gt;&gt;&gt; ===== RESTART: C:\Users\Joe\Desktop\scripts\Stack_overflow\book_price.py ===== Enter the number of books you will be purchasing: 50 Since you are ordering 50 books you will receive a 40% discount! Your subTotal is: $ 5000 Your Total Price is: $ 2000.0 &gt;&gt;&gt; </code></pre>
1
2016-09-19T00:47:54Z
[ "python", "if-statement", "module" ]
Pandas tz_localize: Infer dst when localizing timezone in data with duplicates
39,563,507
<p>I want to localize a datetime series with pandas tz_localize. The series crosses a DST date (e.g. 25Oct2015 for Germany CET). I usually do this with</p> <pre><code>import pandas as pd T = ['25/10/2015 02:59:00','25/10/2015 02:00:00','25/10/2015 02:01:00'] pd.to_datetime(T).tz_localize('CET',ambiguous='infer') </code></pre> <p>But when the time series has duplicates - even if they are sorted in an unambiguous way - I get an error:</p> <pre><code>T = ['25/10/2015 02:59:00','25/10/2015 02:59:00','25/10/2015 02:00:00','25/10/2015 02:01:00'] pd.to_datetime(T).tz_localize('CET',ambiguous='infer') AmbiguousTimeError: There are 2 dst switches when there should only be 1. </code></pre> <p>This seems like a unnecessary limitation since the infer should be pretty straight forward. Is there a workaround or solution, or do I need to code my own infer-method?</p>
1
2016-09-18T23:12:33Z
39,570,965
<p>There were a number of DST related bugs fixed in the latest version, 0.19.0rc1 is out now</p> <pre><code>In [1]: pd.__version__ Out[1]: u'0.19.0rc1' In [2]: t = ['25/10/2015 02:59:00', '25/10/2015 02:00:00', '25/10/2015 02:01:00'] In [3]: pd.to_datetime(t).tz_localize('CET',ambiguous='infer') Out[3]: DatetimeIndex(['2015-10-25 02:59:00+02:00', '2015-10-25 02:00:00+01:00', '2015-10-25 02:01:00+01:00'], dtype='datetime64[ns, CET]', freq=None) </code></pre>
0
2016-09-19T10:29:46Z
[ "python", "datetime", "pandas", "timezone" ]
imshow() function displays empty gray image. What do I do?
39,563,656
<p>When I try to use <code>cv2.imshow()</code> it gives a shows the image for a second, then makes the window go gray. I can't seem to find anything about it, except that I should use <code>cv2.waitKey(0)</code>, which I am, and also to use <code>cv2.namedWindow()</code>. My code:</p> <pre><code>import numpy as np import cv2 import sys cv2.namedWindow('img') img = cv2.imread(sys.argv[1]) cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows </code></pre> <p>Again, it shows the image for a second and then grays it out. Thanks in advance.</p>
0
2016-09-18T23:44:46Z
39,702,260
<ol> <li>check your sys.argv[1], try to replace with real path (i.e. "images/1.png")</li> <li>destroyAllWindows() it is the function (use brackets)</li> <li>parameter of waitKey (0 in your example) it is delay in ms, 0 means "forever", default value of delay is 0.</li> <li>in fact you don't need namedWindow and destroyAllWindows here</li> </ol> <p>try this:</p> <pre><code>import cv2 import sys img = cv2.imread(sys.argv[1]) cv2.imshow('img', img) cv2.waitKey() </code></pre>
0
2016-09-26T11:59:09Z
[ "python", "opencv" ]
How does one return a random number from a dictionary every time a key is called?
39,563,672
<p>I am trying to create a weapon that provides random damage. I am doing so using an item database in the form</p> <pre><code>itemsList = { 1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"}, 2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"}, .... 19: {"name": "Dagger", "damage" : int(random.randrange(1, 4)), "value": 2, "Type": "Dagger"}, 20: {"name": "Dagger + 1", "damage" : int(random.randrange(1, 4) + 1), "value": 200, "Type": "Dagger"}, 21: {"name": "Dagger + 2", "damage" : int(random.randrange(1, 4) + 2), "value": 750, "Type": "Dagger"}, 22: {"name": "Dagger + 3", "damage" : int(random.randrange(1, 4) + 3), "value": 2000, "Type": "Dagger"} } </code></pre> <p>Every time I attempt to call <code>"damage"</code> it just returns the same result. I understand that this is because the random number is generated one and then saved to that dictionary key. </p> <p>How would I go about generating a random number every time damage is called?</p>
2
2016-09-18T23:48:32Z
39,563,714
<p>You would store a function that generates a random number, not the random number itself, in the dictionary. (By the way, if your dictionary's keys are just sequential integers, consider using a list instead.) </p> <pre><code>from random import randrange itemsList = [ {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"}, {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"}, .... {"name": "Dagger", "damage": lambda: randrange(1, 4), "value": 2, "Type": "Dagger"}, {"name": "Dagger + 1", "damage": lambda: randrange(1, 4) + 1, "value": 200, "Type": "Dagger"}, {"name": "Dagger + 2", "damage": lambda: randrange(1, 4) + 2, "value": 750, "Type": "Dagger"}, {"name": "Dagger + 3", "damage": lambda: randrange(1, 4) + 3, "value": 2000, "Type": "Dagger"} ] </code></pre> <p>Then, you simply call the function to get an actual damage roll:</p> <pre><code># Roll damage for a dagger + 3 damage = itemsList[22]["damage"]() </code></pre>
3
2016-09-18T23:55:40Z
[ "python", "dictionary", "random", "properties", "python-descriptors" ]
How does one return a random number from a dictionary every time a key is called?
39,563,672
<p>I am trying to create a weapon that provides random damage. I am doing so using an item database in the form</p> <pre><code>itemsList = { 1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"}, 2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"}, .... 19: {"name": "Dagger", "damage" : int(random.randrange(1, 4)), "value": 2, "Type": "Dagger"}, 20: {"name": "Dagger + 1", "damage" : int(random.randrange(1, 4) + 1), "value": 200, "Type": "Dagger"}, 21: {"name": "Dagger + 2", "damage" : int(random.randrange(1, 4) + 2), "value": 750, "Type": "Dagger"}, 22: {"name": "Dagger + 3", "damage" : int(random.randrange(1, 4) + 3), "value": 2000, "Type": "Dagger"} } </code></pre> <p>Every time I attempt to call <code>"damage"</code> it just returns the same result. I understand that this is because the random number is generated one and then saved to that dictionary key. </p> <p>How would I go about generating a random number every time damage is called?</p>
2
2016-09-18T23:48:32Z
39,563,871
<p>I would go to the trouble of making the things in <code>itemsList</code> instances of a class. Although you might think that's overkill, doing it will give you a lot of programming flexibility later. It'll also make a lot of the code easier to write (and read) because you'll be able to refer to things using dot notation instead of via indexing which means you'll not only be able write to now use <code>itemsList[19].damage</code> instead of <code>itemsList[19]["damage"]</code>. You'll also use the same syntax for all other attributes such as <code>itemsList[1].name</code> and <code>itemsList[2].value</code>, as well as be able to write conditional code like this:</p> <pre><code>if hasattr(itemsList[2], 'Class'): # do something based on itemsList[2].Class </code></pre> <p>Here's what I mean:</p> <pre><code>import random class Gear(object): def __init__(self, **kwargs): kwargs['_damage'] = kwargs.pop('damage', False) self.__dict__.update(kwargs) @property def damage(self): return int(random.randrange(*self._damage)) if self._damage else 0 itemsList = { 1: Gear(name="Padded Armor", armor=1, value=5, Class="Light"), 2: Gear(name="Leather Armor", armor=2, value=10, Class="Light"), # ... 19: Gear(name="Dagger", damage=(1, 4), value=2, Type="Dagger"), 20: Gear(name="Dagger + 1", damage=(1, 5), value=200, Type="Dagger"), 21: Gear(name="Dagger + 2", damage=(1, 9), value=750, Type="Dagger"), 22: Gear(name="Dagger + 3", damage=(2, 6), value=2000, Type="Dagger"), } </code></pre> <p>To answer your follow-on questions in one comment below:</p> <p><code>kwargs</code> is a dictionary of all the keyword arguments passed to the <code>__init__()</code> constructor method. (<code>__dict__</code> is the name of a dictionary where each instance stores its attributes.) See <a href="https://docs.python.org/2/faq/programming.html?#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" rel="nofollow">this section</a> in the documentation.</p> <p><code>damage</code> is defined by the class using a <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow"><code>@property</code></a> decorator which is a simple way to actualy make it a "data descriptor". This sets things up so that whenever you reference a class instance's <code>damage</code> attribute, it will call a function to retrieve/determine its current "value". See the <a href="https://docs.python.org/2/howto/descriptor.html?highlight=property" rel="nofollow"><em>Descriptor HowTo Guide</em></a> for more information on Python descriptors.</p>
3
2016-09-19T00:26:50Z
[ "python", "dictionary", "random", "properties", "python-descriptors" ]
How does one return a random number from a dictionary every time a key is called?
39,563,672
<p>I am trying to create a weapon that provides random damage. I am doing so using an item database in the form</p> <pre><code>itemsList = { 1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"}, 2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"}, .... 19: {"name": "Dagger", "damage" : int(random.randrange(1, 4)), "value": 2, "Type": "Dagger"}, 20: {"name": "Dagger + 1", "damage" : int(random.randrange(1, 4) + 1), "value": 200, "Type": "Dagger"}, 21: {"name": "Dagger + 2", "damage" : int(random.randrange(1, 4) + 2), "value": 750, "Type": "Dagger"}, 22: {"name": "Dagger + 3", "damage" : int(random.randrange(1, 4) + 3), "value": 2000, "Type": "Dagger"} } </code></pre> <p>Every time I attempt to call <code>"damage"</code> it just returns the same result. I understand that this is because the random number is generated one and then saved to that dictionary key. </p> <p>How would I go about generating a random number every time damage is called?</p>
2
2016-09-18T23:48:32Z
39,563,986
<p>You may find it reduces the repetition in your code to store just the damage weighting (still called <code>damage</code> in my code) in your dictionary and have a separate function to calculate the actual damage. e.g.</p> <pre><code>from random import randint itemsList = { 1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"}, 2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"}, 19: {"name": "Dagger", "damage" : 0, "value": 2, "Type": "Dagger"}, 20: {"name": "Dagger + 1", "damage" : 1, "value": 200, "Type": "Dagger"}, 21: {"name": "Dagger + 2", "damage" : 2, "value": 750, "Type": "Dagger"}, 22: {"name": "Dagger + 3", "damage" : 3, "value": 2000, "Type": "Dagger"} } def getdamage(item): return randint(1, 4) + item['damage'] # test code for i in range(20): item = randint(19, 21) damage = getdamage(itemsList[item]) print("I used item %d and made damage %d" % (item, damage)) </code></pre> <p>Now your random function is only in one place and if you decide to change it later it will be less work.</p> <p>One thing I don't get though is why have the armour and weapons in one list? You could pass the index of some armour to the damage function and get an error.</p>
3
2016-09-19T00:50:09Z
[ "python", "dictionary", "random", "properties", "python-descriptors" ]
Access values for a dictionary within a list in a column of a pandas dataframe
39,563,719
<p>I have a column in a pandas dataframe, where each row is a list with a dictionary inside, like this:</p> <pre><code>urls --------------------------------------------------------- [{'url': http://t.co, 'expanded_url':http://nytimes.com}] [{'url': http://t.co, 'expanded_url':http://time.com}] [] </code></pre> <p>Some of the rows only have an empty list. So I'm trying to extract the value of just the expanded_url, and when I test the following function on a test list, I'm able to do that:</p> <pre><code>test_list = [{'url': 'https://t.co', 'expanded_url': 'https://nytimes.com'}] def get_expanded_url(outterlist): for item in outterlist: if isinstance(item, dict): return item['expanded_url'] else: return None </code></pre> <p>However when I apply this to a column in the dataframe like this:</p> <pre><code>df.urls.apply(lambda x: get_expanded_url(x)) </code></pre> <p>I only get NaNs, even where I shouldn't (where there isn't just an empty list). First of all can someone explain why my function doesn't work on the dataframe? And secondly, how can I extract just the values for expand_url from the column?</p>
2
2016-09-18T23:56:46Z
39,563,836
<p>You can try this:</p> <pre><code>def get_expanded_url(outterlist): try: return outterlist[0]['expanded_url'] except IndexError: return None df.urls.apply(get_expanded_url) </code></pre> <p>The function will try to obtain the url that you want. If it can't, it will return <code>None</code>.</p> <p>Also, when using <code>apply</code>, you can give only the name of the function. It is not required to create the lambda function.</p>
1
2016-09-19T00:20:48Z
[ "python", "pandas" ]
Python: curl -F equivalent with Requests or other
39,563,786
<p>I want to reproduce the following curl -F request (<a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment" rel="nofollow">from the Messenger API</a>) to send an image file and parameters to Messenger's Send API:</p> <pre><code>curl \ -F recipient='{"id":"USER_ID"}' \ -F message='{"attachment":{"type":"image", "payload":{}}}' \ -F filedata=@/tmp/shirt.png \ "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN" </code></pre> <p>I'm using Requests and I tried many, many things (including with correct recipient IDs, etc.. For instance:</p> <pre><code>recipient = '{"id":"USER_ID"}' message = '{"attachment":{"type":"image", "payload":{}}}' files = [("recipient", recipient), ("message", message), ("filedata", open(imagePath, 'rb'))] r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN', files=files) </code></pre> <p>I also tried:</p> <pre><code>files = {"recipient" : recipient, "message" : message, "filedata" : open(imagePath, "rb")} </code></pre> <p>I almost always get this response error from Messenger:</p> <pre><code>'{"error":{"message":"(#100) param recipient must be non-empty.","type":"OAuthException","code":100,"fbtrace_id":"xxxxx"}}' </code></pre> <p>I'm at a loss here. I'm probably misusing the Requests syntax somehow, or sending a poorly formatted string to the API, but I've read the Requests documentation and browsed through StackOverflow's questions on this and couldn't solve my issue. Thank you.</p>
0
2016-09-19T00:11:09Z
39,574,744
<p>This was the correct format:</p> <pre><code>imgName = "tmp/graph.png" files = { "filedata" : ('filename.png', open(imagePath, 'rb'), 'image/png')} data = { "recipient":'{"id":"' + id + '"}', "message":'{"attachment":{"type":"image", "payload":{}}}' } r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=' + ACCESS_TOKEN, files=files, data=data) </code></pre>
1
2016-09-19T13:44:28Z
[ "python", "facebook", "curl", "python-requests", "messenger" ]
Python: curl -F equivalent with Requests or other
39,563,786
<p>I want to reproduce the following curl -F request (<a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment" rel="nofollow">from the Messenger API</a>) to send an image file and parameters to Messenger's Send API:</p> <pre><code>curl \ -F recipient='{"id":"USER_ID"}' \ -F message='{"attachment":{"type":"image", "payload":{}}}' \ -F filedata=@/tmp/shirt.png \ "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN" </code></pre> <p>I'm using Requests and I tried many, many things (including with correct recipient IDs, etc.. For instance:</p> <pre><code>recipient = '{"id":"USER_ID"}' message = '{"attachment":{"type":"image", "payload":{}}}' files = [("recipient", recipient), ("message", message), ("filedata", open(imagePath, 'rb'))] r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN', files=files) </code></pre> <p>I also tried:</p> <pre><code>files = {"recipient" : recipient, "message" : message, "filedata" : open(imagePath, "rb")} </code></pre> <p>I almost always get this response error from Messenger:</p> <pre><code>'{"error":{"message":"(#100) param recipient must be non-empty.","type":"OAuthException","code":100,"fbtrace_id":"xxxxx"}}' </code></pre> <p>I'm at a loss here. I'm probably misusing the Requests syntax somehow, or sending a poorly formatted string to the API, but I've read the Requests documentation and browsed through StackOverflow's questions on this and couldn't solve my issue. Thank you.</p>
0
2016-09-19T00:11:09Z
39,574,774
<p>I believe the issue is that you are trying to send formdata inside the requests file kwarg, when it should be in data:</p> <pre><code>data = { 'recipient': '{"id":"USER_ID"}', 'message': '{"attachment":{"type":"image", "payload":{}}}' } files = { "filedata": open(imagePath, 'rb') } r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN', data=data, files=files) </code></pre> <p>The one assumption is that imagePath exists.</p> <p>Also in python <code>{}</code> denotes a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">Set</a> if it doesn't have <code>key:value</code> pairs in it, so in your answer, you are passing a Set of a single tuple, which has two items in it, the string <code>filedata</code> and a <code>file object</code>.</p> <pre><code>{("filedata", open(imgName, 'rb'))} # Set of tuple {"filedata": open(imgName, 'rb')} # dictionary </code></pre>
1
2016-09-19T13:45:54Z
[ "python", "facebook", "curl", "python-requests", "messenger" ]
subprocess.CalledProcessError: what *is* the error?
39,563,802
<pre><code>import subprocess cmd = "grep -r * | grep jquery" print cmd subprocess.check_output(cmd, shell=True) </code></pre> <p><strong>subprocess.CalledProcessError: Command 'grep -r * | grep jquery' returned non-zero exit status 1</strong></p> <p>I can execute that command in my shell without issues. How can I see the <strong>actual</strong> error in python?</p> <p><em>The snippet is part of a larger script which takes multiple arguments and chains the grep commands + adds some excludes (I don't need to grep log files or minified JavaScript. Hence the pedantic syntax.</em></p> <p><em>Python 2.7.10</em></p>
1
2016-09-19T00:13:39Z
39,563,839
<p><a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">Quoting docs</a>:</p> <blockquote> <p>If the return code was non-zero it raises a <code>CalledProcessError</code>. The <code>CalledProcessError</code> object will have the return code in the <code>returncode</code> attribute and any output in the <code>output</code> attribute.</p> </blockquote> <pre><code>import subprocess cmd = "grep -r * | grep jquery" print cmd try: subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError as e: print e.returncode print e.output </code></pre> <p>Of error message was printed to stderr, you need keyword argument <code>stderr=subprocess.STDOUT</code>.</p> <p>There is no other source of 'what went wrong' besides return code and stdout / stderr.</p>
2
2016-09-19T00:21:11Z
[ "python", "subprocess" ]
subprocess.CalledProcessError: what *is* the error?
39,563,802
<pre><code>import subprocess cmd = "grep -r * | grep jquery" print cmd subprocess.check_output(cmd, shell=True) </code></pre> <p><strong>subprocess.CalledProcessError: Command 'grep -r * | grep jquery' returned non-zero exit status 1</strong></p> <p>I can execute that command in my shell without issues. How can I see the <strong>actual</strong> error in python?</p> <p><em>The snippet is part of a larger script which takes multiple arguments and chains the grep commands + adds some excludes (I don't need to grep log files or minified JavaScript. Hence the pedantic syntax.</em></p> <p><em>Python 2.7.10</em></p>
1
2016-09-19T00:13:39Z
39,563,842
<p>"non-zero exit status" means that the <em>command you ran</em> indicated a status other than success. For <code>grep</code>, the documentation explicitly indicates that an exit status of 1 indicates no lines were found, whereas an exit status more than 1 indicates that some other error took place.</p> <p>To quote the manual:</p> <blockquote> <p><strong>EXIT STATUS</strong> - The grep utility exits with one of the following values:</p> <pre><code>0 One or more lines were selected. 1 No lines were selected. &gt;1 An error occurred. </code></pre> </blockquote> <hr> <p>By the way -- if you want to look for the string <code>jquery</code> in all files under the current directory (recursively), use <code>grep -r jquery .</code>; <code>grep -r *</code> searches for <em>the name of the first file in your directory</em> inside <em>the contents of all other files in your directory</em>.</p>
3
2016-09-19T00:21:14Z
[ "python", "subprocess" ]
How to include chromedriver with pyinstaller?
39,563,851
<p>I am using pyinstaller to create an executable of my python script.<br> In the script I'm using these imports:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options etc... </code></pre> <p>The problem is, when running <code>pyinstaller myscript.py</code> , it will result in including Firefox, instead of Chrome. In the result folder c:...\dist\myscript\selenium\webdriver there is a firefox folder, so it is simply skipping chromedriver, and it is a serious problem for me, because the script needs to run with Chrome.<br> There is only a few questions around this topic, but there is no answer to solve the issue.<br> I was thinking on adding the <code>--hidden-import MODULENAME</code> tag to the command, but chromedriver.exe is not a module... Thanks</p>
1
2016-09-19T00:23:42Z
39,648,291
<p>It should be added as a binary file, since it is a binary file...<br> So a custom spec file needed where the chromedriver's path on the local system and the desired location relative to the dist\myscript should be defined, so it looks something like this:<br></p> <pre><code>..... a = Analysis(['myscript.py'], pathex=['path\\to\\my\\script'], binaries=[ ('path\\to\\my\\chromedriver.exe', '.\\selenium\\webdriver') ], datas=None, .... </code></pre> <p>And then run the pyinstaller with this spec file: <code>pyinstaller myscript.spec myscript.py</code></p>
0
2016-09-22T20:26:52Z
[ "python", "windows", "selenium", "selenium-chromedriver", "pyinstaller" ]
How to get randomly select n elements from a list using in numpy?
39,563,859
<p>I have a list of vectors:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; num_dim, num_data = 10, 5 &gt;&gt;&gt; data = np.random.rand(num_data, num_dim) &gt;&gt;&gt; data array([[ 0.0498063 , 0.18659463, 0.30563225, 0.99681495, 0.35692358, 0.47759707, 0.85755606, 0.39373145, 0.54677259, 0.5168117 ], [ 0.18034536, 0.25935541, 0.79718771, 0.28604057, 0.17165293, 0.90277904, 0.94016733, 0.15689765, 0.79758063, 0.41250143], [ 0.80716045, 0.84998745, 0.17893211, 0.36206016, 0.69604008, 0.27249491, 0.92570247, 0.446499 , 0.34424945, 0.08576628], [ 0.35311449, 0.67901964, 0.71023927, 0.03120829, 0.72864953, 0.60717032, 0.8020118 , 0.36047207, 0.46362718, 0.12441942], [ 0.1955419 , 0.02702753, 0.76828842, 0.5438226 , 0.69407709, 0.20865243, 0.12783666, 0.81486189, 0.95583274, 0.30157658]]) </code></pre> <p>From the <code>data</code>, I need to randomly pick 3 vectors, I could do it with:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; random.sample(data, 3) [array([ 0.80716045, 0.84998745, 0.17893211, 0.36206016, 0.69604008, 0.27249491, 0.92570247, 0.446499 , 0.34424945, 0.08576628]), array([ 0.18034536, 0.25935541, 0.79718771, 0.28604057, 0.17165293, 0.90277904, 0.94016733, 0.15689765, 0.79758063, 0.41250143]), array([ 0.35311449, 0.67901964, 0.71023927, 0.03120829, 0.72864953, 0.60717032, 0.8020118 , 0.36047207, 0.46362718, 0.12441942])] </code></pre> <p>I've checked the docs at <a href="http://docs.scipy.org/doc/numpy/reference/routines.random.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/routines.random.html</a> and I couldn't figure out whether there is such a functionality in <code>numpy</code> as <code>random.sample()</code>. </p> <p><strong>Is it right that the <code>numpy.random.sample()</code> isn't the same as <code>random.sample()</code>?</strong></p> <p><strong>Is there an equivalence of <code>random.sample()</code> in <code>numpy</code>?</strong></p>
-1
2016-09-19T00:24:50Z
39,563,965
<p>As @ayhan confirmed, it can be done as such:</p> <pre><code>&gt;&gt;&gt; data[np.random.choice(len(data), size=3, replace=False)] array([[ 0.80716045, 0.84998745, 0.17893211, 0.36206016, 0.69604008, 0.27249491, 0.92570247, 0.446499 , 0.34424945, 0.08576628], [ 0.35311449, 0.67901964, 0.71023927, 0.03120829, 0.72864953, 0.60717032, 0.8020118 , 0.36047207, 0.46362718, 0.12441942], [ 0.1955419 , 0.02702753, 0.76828842, 0.5438226 , 0.69407709, 0.20865243, 0.12783666, 0.81486189, 0.95583274, 0.30157658]]) </code></pre> <p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html" rel="nofollow">docs</a>:</p> <blockquote> <p><strong>numpy.random.choice(a, size=None, replace=True, p=None)</strong> </p> <p>Generates a random sample from a given 1-D array</p> </blockquote> <p>The <code>np.random.choice(data, size=3, replace=False)</code> selects 3 elements from the list of indices of the <code>data</code> without replacement.</p> <p>Then <code>data[...]</code> slices the index and retrieve the indices selected with <code>np.random.choice</code>.</p>
2
2016-09-19T00:45:29Z
[ "python", "numpy", "random", "sample", "choice" ]
How to use SMTP header and send SendGrid email?
39,563,869
<p>I'm working on creating a SendGrid python script that sends emails when executed. I followed the example script <a href="https://github.com/sendgrid/smtpapi-python/blob/master/examples/example.py" rel="nofollow">here</a>, but all this does is generate my custom SMTP API Header. How do I actually send the email? Thanks!</p> <p>My code:</p> <pre><code>#sudo pip install smtpapi import time, json if __name__ == '__main__' and __package__ is None: from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from smtpapi import SMTPAPIHeader from smtpapi import SMTPAPIHeader header = SMTPAPIHeader() header.add_to('test@email.com') # Substitutions header.set_substitutions({'key': ['value1', 'value2']}) # Sections header.set_sections({':name':'Michael', 'key2':'section2'}) # Filters header.add_filter('templates', 'enable', 1) header.add_filter('templates', 'template_id', 'a713d6a4-5c3e-4d4c-837f-ffe51b2a3cd2') # Scheduling Parameters header.set_send_at(int(time.time())) # must be a unix timestamp parsed = json.loads(header.json_string()) print json.dumps(parsed, indent=4, sort_keys=True) #display the SMTP API header json </code></pre>
0
2016-09-19T00:26:23Z
39,564,053
<p>That library seems to be for generating SMTP API headers. You would want to use this library for sending emails - <a href="https://github.com/sendgrid/sendgrid-python" rel="nofollow">https://github.com/sendgrid/sendgrid-python</a></p> <pre><code>import sendgrid import os from sendgrid.helpers.mail import * sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("test@example.com") subject = "Hello World from the SendGrid Python Library!" to_email = Email("test@example.com") content = Content("text/plain", "Hello, Email!") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) </code></pre> <p>But personally, I have always preferred SMTP since it allowed me to easily switch providers as necessary.</p>
0
2016-09-19T01:02:01Z
[ "python", "email", "smtp", "sendgrid" ]
How to read the elements as "columns" from a file?
39,563,957
<p>I have the following file that has a number of rows as follows</p> <pre><code>qt1l 1 A B 90 1 3.00 jqlt1l 2 B Z 20 5 6.00 ahyttl 3 F O 45 33 53.00 kqll 4 L L 70 22 22.00 gqlt1l 5 T U 90 6 77.00 with open('c:/test/file.txt','r') as f: inputfile = f.readlines() </code></pre> <p>In this program I take x,y and z input. I read the data row wise. For example, take row[0] for example. Here, I need to compare if "column 4" =! "z", "column 3" -->"A" to "column 4" ---> "B" (col3 =! col4). Check if "column 5" >= x, "column 6" >= y and "column 7" >= 8. If all are yes then I have a count that increments by 1. The following is the code:</p> <pre><code> x = input("Enter value for x: ") # Take x = 1 y = input("Enter value for y: ") # Take x = 1 z = input("Enter value for z: ") # Take x = 1 for line in infile: if[col4] =I "Z": continue if [col3] != [col4]: continue if [col5] &gt;= x: continue if [col6] &gt;= y: continue if [col7] &gt;= z: continue count += 1 print [col2] finalcount.append(count) print "The final count is" + str(finalcount) </code></pre> <p>The problem is that these "columns" can only be accessed as a certain element number --> inputfile[0][8]. So if I need to check if "column 4" > 80..then I run into trouble because I need to check if inputfile[0][something] >= 8 and inputfile[0][something+1] >= 0.</p> <p>Can you think of a easy way to bypass the problem? I also need help to check if my code is running fine in the end with desired output. Here the output should be </p> <pre><code>1 3 5 The final count is 3 </code></pre>
-1
2016-09-19T00:43:40Z
39,564,018
<pre><code>x = 1 # example values y = 1 z = 1 count = 0 for line in inputfile: # This splits on whitespace. # E.g., for the first row: # columns = ['qt1l', '1', 'A', 'B', '90', '1', '3.00'] columns = line.split() # Note that indexes into lists are 0-based, so "column 4" is columns[3] if (columns[3] != "Z" and columns[2] != columns[3] and float(columns[4]) &gt;= x and # Convert from str to float! float(columns[5]) &gt;= y and float(columns[6]) &gt;= z): # If all the conditions are met, increment your counter count += 1 print(columns[1]) if count &gt; 0: print("The final count is {}.".format(count)) else: print("No matches found.") </code></pre> <p>There were a number of issues with your code:</p> <ol> <li><code>=+</code> and <code>=!</code> instead of <code>+=</code> and <code>!=</code>.</li> <li><code>continue</code> means "Go immediately to the next iteration of the loop." With your <code>continue</code> statements, as soon as one condition passed, you were going to skip over that row entirely.</li> <li>There are some missing bits of your code... you show reading the file into <code>inputfile</code> but later use <code>qual</code>. You don't define <code>count</code> or <code>finalcount</code> (which I guess is some sort of list?). In the future, make sure to share complete runnable code.</li> </ol>
3
2016-09-19T00:55:11Z
[ "python", "row", "multiple-columns", "element" ]
VENV : Accessing system packages?
39,564,037
<p>I want to be able to access a module installed system-wide after the venv was created. You can see that I can access bcrypt when outside VENV w/o problem, but not inside it (btw. installation of bcrypt inside VENV fails)</p> <pre><code># apt-get install python-bcrypt $ python -c 'import bcrypt' $ . venv/bin/activate (venv) $ virtualenv env --system-site-packages New python executable in env/bin/python Installing setuptools, pip...done. (venv) $ python -c 'import bcrypt' Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: No module named bcrypt </code></pre>
0
2016-09-19T00:58:35Z
39,564,235
<p>the correct cmd is (venv vs env) :</p> <pre><code>(venv)$ virtualenv venv --system-site-packages </code></pre>
0
2016-09-19T01:35:45Z
[ "python", "package", "virtualenv" ]
django-parsley: uncaught error
39,564,107
<p>I am using python 2.7 &amp; django 1.10.</p> <p>I am also using <a href="https://github.com/agiliq/Django-parsley" rel="nofollow">django-parsley</a> for the client side validation.</p> <p>On each page I have the following error in the parsley.min.js file:</p> <pre><code>Uncaught Error: it is not available in the catalog </code></pre> <p>The error refers to the following code segment in the parsley.min.js file:</p> <pre><code> setLocale: function(a) { if ("undefined" == typeof this.catalog[a]) throw new Error(a + " is not available in the catalog"); return this.locale = a, this }, </code></pre> <p>Here is a screen shot of the issue:</p> <p><a href="http://i.stack.imgur.com/XfPdQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/XfPdQ.png" alt="enter image description here"></a></p> <p><strong>Does anyone have suggestions as to why I have this error?</strong> </p> <p>I have searched SO &amp; Google, but have no real insight.</p>
0
2016-09-19T01:15:00Z
39,564,350
<p>Check your stack trace. Somehow, <code>setLocale</code> is being called with undefined or empty string as argument, instead of <code>'en'</code> or similar.</p>
1
2016-09-19T01:56:02Z
[ "javascript", "python", "django", "parsley.js" ]
Not getting any output in Django for BeautifulSoup
39,564,141
<p>I am trying BeautifulSoup4 in Django and I parsed an XML page with it. When I try the parsing the same XML page in a python interpreter in a different way, it works fine. But in Django, I get a page as shown below.</p> <p><a href="http://i.stack.imgur.com/hPWuk.png" rel="nofollow"><img src="http://i.stack.imgur.com/hPWuk.png" alt="enter image description here"></a></p> <p>views.py:</p> <pre><code>def rssfeed(request): list1=[] xmllink="https://rss.sciencedaily.com/computers_math/computer_programming.xml" soup=BeautifulSoup(urlopen(xmllink),'xml') for items in soup.find_all('item'): list1.append(items.title) context={ "list1":list1 } return render(request,'poll/rssfeed.html',context) </code></pre> <p>rssfeed.html:</p> <pre><code>{% if list1 %} &lt;ul&gt; {% for item in list1 %} &lt;li&gt;{{ item }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} </code></pre> <p>What is that I am doing wrong?</p>
2
2016-09-19T01:19:06Z
39,565,263
<p>From <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#variables-and-lookups" rel="nofollow">documentation</a></p> <blockquote> <p>If any part of the variable is callable, the template system will try calling it.</p> </blockquote> <p>and</p> <blockquote> <p>Occasionally you may want to turn off this feature for other reasons, and tell the template system to leave a variable uncalled no matter what. To do so, set a do_not_call_in_templates attribute on the callable with the value True. </p> </blockquote> <p>And from <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#calling-a-tag-is-like-calling-find-all" rel="nofollow">BeautifulSoup documentation</a></p> <blockquote> <p>Calling a tag is like calling find_all()</p> </blockquote> <p>Eg. <code>tagX('a')</code> returns a list of all the <code>&lt;a&gt;</code> tags found within this <code>tagX</code>.</p> <p>The <code>item</code> in your template refers to instance of <code>bs4.element.Tag</code>, which is callable. So Django is calling the <code>item</code> variable with zero arguments, which means it will return list of all the elements inside <code>item</code>, which is none as it contains only text. Hence the blank lists.</p> <p>So either parse the context before passing it to the template</p> <pre><code>list1 = [item.title.text for item in soup.find_all('item')] </code></pre> <p>Or if you want to pass the instance for some reason, you can set the <code>do_not_call_in_templates</code> attribute to to</p> <pre><code>for item in soup.find_all('item'): title = item.title title.do_not_call_in_templates = True list1.append(title) </code></pre>
0
2016-09-19T04:14:16Z
[ "python", "django", "beautifulsoup", "render" ]
Not getting any output in Django for BeautifulSoup
39,564,141
<p>I am trying BeautifulSoup4 in Django and I parsed an XML page with it. When I try the parsing the same XML page in a python interpreter in a different way, it works fine. But in Django, I get a page as shown below.</p> <p><a href="http://i.stack.imgur.com/hPWuk.png" rel="nofollow"><img src="http://i.stack.imgur.com/hPWuk.png" alt="enter image description here"></a></p> <p>views.py:</p> <pre><code>def rssfeed(request): list1=[] xmllink="https://rss.sciencedaily.com/computers_math/computer_programming.xml" soup=BeautifulSoup(urlopen(xmllink),'xml') for items in soup.find_all('item'): list1.append(items.title) context={ "list1":list1 } return render(request,'poll/rssfeed.html',context) </code></pre> <p>rssfeed.html:</p> <pre><code>{% if list1 %} &lt;ul&gt; {% for item in list1 %} &lt;li&gt;{{ item }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} </code></pre> <p>What is that I am doing wrong?</p>
2
2016-09-19T01:19:06Z
39,578,490
<p>To get text from XML, you need to call get_text() function.</p> <p>Don't use:</p> <pre><code>items.title </code></pre> <p>Use:</p> <pre><code>items.title.get_text() </code></pre> <p>Also, it's recommended to use <strong>lxml</strong> for parsing. Install lxml python and use:</p> <pre><code>soup = BeautifulSoup(urlopen(xmllink), 'lxml-xml') </code></pre>
1
2016-09-19T17:07:07Z
[ "python", "django", "beautifulsoup", "render" ]
Using a column of one DataFrame in a function - Python
39,564,168
<p>I have a DataFrame which has a column with unique IDs. That same ID is used elsewhere for functions I use. I have no problem using one of the individual IDs in my function, however, I would like to use a subset of those IDs in the function and then append that to a new DataFrame. </p> <p>This is what my base DataFrame looks like:</p> <pre><code>First_Df +---+------------+-------------+-------------+ | | Unique ID | A | B | +---+------------+-------------+-------------+ | 1 | 123456 | xxxxx | aaaaa | | 2 | 234567 | yyyyy | bbbbb | | 3 | 345678 | zzzzz | ccccc | | 4 | 456789 | uuuuu | ddddd | | 5 | 567890 | vvvvv | eeeee | | 6 | 678901 | wwwww | fffff | +---+------------+-------------+-------------+ </code></pre> <p>I have a subset of those values in a separate DatFrame like so:</p> <pre><code>Subset_Df +---+------------+-------------+-------------+ | | Unique ID | A | B | +---+------------+-------------+-------------+ | 2 | 234567 | yyyyy | bbbbb | | 3 | 345678 | zzzzz | ccccc | | 5 | 567890 | vvvvv | eeeee | +---+------------+-------------+-------------+ </code></pre> <p>If I run my function using one ID, my function will return a DF with the right values, however, if I try to give it my subset list of IDs, I get ValueError: No JSON object could be decoded.</p> <pre><code>Function123(Subset_Df['Unique ID'],arg1,arg2) </code></pre> <p>Thanks in advance, I can provide specific lines of code if needed.</p> <p>EDIT:</p> <p>This is what my base DataFrame looks like:</p> <pre><code>all_players_df.head(6) +---+------------+---------------+-------------+-------------+ | | PERSON_ID |DISPLAY_LAST.. |TEAM_CITY |TEAM_CITY | +---+------------+---------------+-------------+-------------+ | 1 | 123456 |Adams, Jordan | Memphis | Grizzlies | | 2 | 234567 |Anderson, Alan | LA | Clippers | | 3 | 345678 |Ayres, Jeff | LA | Clippers | | 4 | 456789 |Aldrich, Cole | Minnesota | Timberwolves| | 5 | 567890 |Albrines,Alex |Oklahoma City| Thunder | | 6 | 678901 |Bass,Brandon | LA | Clippers | +---+------------+---------------+-------------+-------------+ </code></pre> <p>I have a subset of those values in a separate DataFrame like so:</p> <pre><code>clippers_players_df.head(3) +---+------------+---------------+-------------+-------------+ | | PERSON_ID |DISPLAY_LAST.. |TEAM_CITY |TEAM_CITY | +---+------------+---------------+-------------+-------------+ | 2 | 234567 |Anderson, Alan | LA | Clippers | | 3 | 345678 |Ayres, Jeff | LA | Clippers | | 5 | 678901 |Bass,Brandon | LA | Clippers | +---+------------+---------------+-------------+-------------+ </code></pre> <p>Then I'll run a function:</p> <pre><code>player_shooting_stats_overall_df(234567,'2015-16','Playoffs') </code></pre> <p>Running this, I'll get the correct returned DF for that function but I want to run the PERSON_ID for the clippers through my function. I'll try:</p> <pre><code>player_shooting_stats_overall_df(clippers_players_df['PERSONID'],'2015-16','Playoffs') </code></pre> <p>but this is where I get the error ValueError: No JSON object could be decoded.</p>
0
2016-09-19T01:24:01Z
39,564,578
<p>Most likely your function takes scalars as input while you pass in a pandas series (i.e., column of a dataframe). Consider a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow">pandas.Series.apply()</a> for element-wise operations. For the other positional arguments, use <code>args</code> keyword. </p> <pre><code>dfSeries = clippers_players_df['PERSONID'].apply(player_shooting_stats_overall_df, args=('2015-16','Playoffs')) </code></pre> <p>Do note the above will create a series of multiple data frames, assuming a df is the returned value of function. To combine all into single data frame, use <code>pd.concat()</code> after converting series to a list:</p> <pre><code>clippersdf = pd.concat(dfSeries.tolist()) </code></pre>
0
2016-09-19T02:30:35Z
[ "python", "python-2.7" ]
How to deal with Python long import
39,564,280
<p>This is about python long import like this:</p> <p>from aaa.bbb.ccc.ddd.eee.fff.ggg.hhh.iii.jjj.kkk.lll.mmm.nnn.ooo import xxx</p> <p>The length between 'from' and 'import' is already above than 80 characters, is there any better pythonic ways to deal with it?</p>
0
2016-09-19T01:45:39Z
39,568,827
<p>You can always wrap lines using the <code>\</code> character at the end of the line.</p> <pre><code>from a.very.long.and.unconventional.structure.\ and.name import foo </code></pre> <p>For multiple statements to import after the <code>from x import</code> statement, you can use parentheses and wrap inside these parentheses without a newline escape:</p> <pre><code>from foo.bar import (test, and, others) </code></pre>
0
2016-09-19T08:41:50Z
[ "python", "python-import" ]
How to write a fit_transformer with two inputs and include it in a pipeline in python sklearn?
39,564,355
<p>Given some fake data:</p> <pre><code>X = pd.DataFrame( np.random.randint(1,10,28).reshape(14,2) ) y = pd.Series( np.repeat([0,1], [10,4]) ) # imbalanced with more 0s than 1s </code></pre> <p>I write a sklearn fit-transformer that under-samples the majority of y to match the length of the minority label. I want to use it in a pipeline. </p> <pre><code>from sklearn.base import BaseEstimator, TransformerMixin class UnderSampling(BaseEstimator, TransformerMixin): def fit(self, X, y): # I don't need fit to do anything return self def transform(self, X, y): is_pos = y == 1 idx_pos = y[is_pos].index random.seed(random_state) idx_neg = random.sample(y[~is_pos].index, is_pos.sum()) idx = sorted(list(idx_pos) + list(idx_neg)) X_resampled = X.loc[idx] y_resampled = y.loc[idx] return X_resampled, y_resampled def fit_transform(self, X, y): return self.transform(X,y) </code></pre> <p>Most unfortunately, I cannot use it in a pipeline. </p> <pre><code>from sklearn.pipeline import make_pipeline us = UnderSampling() rfc = RandomForestClassifier() model = make_pipeline(us, rfc) model.fit(X,y) </code></pre> <p>How can I make this pipeline work?</p>
1
2016-09-19T01:56:34Z
39,564,442
<p>You're not meant to call the estimator methods on the class directly, you're meant to call it on a class instance; this is because estimators often to have some type of stored state (the model coefficients for example):</p> <pre><code>u = UnderSampling() a,b = u.fit(X, y) a,b = u.fit_transform(X, y) </code></pre>
0
2016-09-19T02:09:49Z
[ "python", "scikit-learn", "pipeline", "transformer" ]
Beautiful Soup has extra </body> before actual end
39,564,359
<p>I am trying to scrape poems from PoetryFoundation.org. I have found in one of my test cases that when I pull the html from a specific poem it includes an extra <code>&lt;/body&gt;</code> before the end of the actual poem. I can look at the source code for the poem online and there is no in the middle of the poem (as to be expected). I created an example with the url of a specific case such that others can try to replicate the problem:</p> <pre><code>from bs4 import BeautifulSoup from urllib.request import urlopen poem_page = urlopen("https://www.poetryfoundation.org/poems-and-poets/poems/detail/57956") poem_soup = BeautifulSoup(poem_page.read(), "html5lib") print(poem_soup) </code></pre> <p>I'm running Python 3.5.1. I've tried this with the default parsers <code>html.parser</code> as well as <code>html5lib</code> and <code>lxml</code>.</p> <p>In the print out, if you search for 'in the poem' you'll find this snippet of html, which makes no sense because it ends the entire html document midway through the poem with <code>&lt;/body&gt;&lt;/html&gt;</code> and then continues on with the rest of document:</p> <pre><code>in the poem&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;. But when we met,&lt;br/&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;&lt;br/&gt; </code></pre> <p>I've looked at the source code online and this is what it should be:</p> <pre><code>in the poem&lt;/em&gt;. But when we met,&lt;br&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt; </code></pre> <p>I have no idea why when I scrape it it's closing the entire html document partway through the page.</p>
1
2016-09-19T01:57:33Z
39,564,953
<p>When I try to get the poem with your url with <code>html.parser</code>,I got the same problem as you.The html was truncated at the <code>in the poem</code> position.</p> <pre><code>import requests from bs4 import BeautifulSoup poem_page = requests.get("https://www.poetryfoundation.org/poems-and-poets/poems/detail/57956") poem_soup = BeautifulSoup(poem_page.text, "html.parser") poem_div = poem_soup.find('div', class_='poem') print poem_div </code></pre> <p>OUTPUT:</p> <pre><code>&lt;div class="poem" data-view="ContentView"&gt; &lt;div style="text-indent: -1em; padding-left: 1em;"&gt;It seems a certain fear underlies everything. &lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;If I were to tell you something profound&lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt; it would be useless, as every single thing I know&lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt; is not timeless. I am particularly risk-averse.&lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;&lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;I choose someone else over me every time, &lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;as I'm sure they'll finish the task at hand, &lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;which is to say that whatever is in front of us&lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt; will get done if I'm not in charge of it.&lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;&lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;There is a limit to the number of times &lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;I can practice every single kind of mortification &lt;br/&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;(of the flesh?). I can turn toward you and say &lt;em&gt;yes, &lt;br/&gt;&lt;/em&gt;&lt;/div&gt;&lt;div style="text-indent: -1em; padding-left: 1em;"&gt;it was you in the poem&lt;/div&gt;&lt;/div&gt; </code></pre> <p>But changing the parser to <code>lxml</code>,everything is ok.</p> <pre><code>import requests from bs4 import BeautifulSoup poem_page = requests.get("https://www.poetryfoundation.org/poems-and-poets/poems/detail/57956") poem_soup = BeautifulSoup(poem_page.text, "lxml") poem_div = poem_soup.find('div', class_='poem') # print poem_div for s in poem_div.find_all('div'): print list(s.children)[0] </code></pre> <p>OUTPUT:</p> <pre><code>It seems a certain fear underlies everything. If I were to tell you something profound it would be useless, as every single thing I know is not timeless. I am particularly risk-averse. &lt;br/&gt; I choose someone else over me every time, as I'm sure they'll finish the task at hand, which is to say that whatever is in front of us will get done if I'm not in charge of it. &lt;br/&gt; There is a limit to the number of times I can practice every single kind of mortification (of the flesh?). I can turn toward you and say it was you in the poem. But when we met, &lt;br/&gt; you were actually wearing a shirt, and the poem wasn't about you or your indecipherable tattoo. The poem is always about me, but that one time I was in love with the memory of my twenties &lt;br/&gt; so I was, for a moment, in love with you because you remind me of an approaching subway brushing hair off my face with its hot breath. Darkness. And then light, &lt;br/&gt; the exact goldness of dawn fingering that brick wall out my bedroom window on Smith Street mornings when I'd wake next to godknowswho but always someone &lt;br/&gt; who wasn't a mistake, because what kind of mistakes are that twitchy and joyful even if they're woven with a particular thread of regret: the guy who used &lt;br/&gt; my toothbrush without asking, I walked to the end of a pier with him, would have walked off anywhere with him until one day we both landed in California &lt;br/&gt; when I was still young, and going West meant taking a laptop and some clothes in a hatchback and learning about produce. I can turn toward you, whoever you are, &lt;br/&gt; and say you are my lover simply because I say you are, and that is, I realize, a tautology, but this is my poem. I claim nothing other than what I write, and even that, &lt;br/&gt; I'd leave by the wayside, since the only thing to pack would be the candlesticks, and even those are burned through, thoroughly replaceable. Who am I kidding? I don't &lt;br/&gt; own anything worth packing into anything. We are cardboard boxes, you and I, stacked nowhere near each other and humming different tunes. It is too late to be writing this. &lt;br/&gt; I am writing this to tell you something less than neutral, which is to say I'm sorry. It was never you. It was always you: your unutterable name, this growl in my throat. &lt;br/&gt; </code></pre>
0
2016-09-19T03:31:49Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Create new column in pandas based on value of another column
39,564,372
<p>I have some dataset about genders of various individuals. Say, the dataset looks like this:</p> <pre><code>Male Female Male and Female Male Male Female Trans Unknown Male and Female </code></pre> <p>Some identify themselves as Male, some female and some identify themselves as both male and female.</p> <p>Now, what I want to do is create a new column in Pandas which maps </p> <pre><code>Males to 1, Females to 2, Others to 3 </code></pre> <p>I wrote some code </p> <pre><code>def gender(x): if x.str.contains("Male") return 1 elif x.str.contains("Female") return 2 elif return 3 df["Gender Values"] = df["Gender"].apply(gender) </code></pre> <p>But I was getting errors that function doesn't contain any attribute contains. I tried removing str:</p> <pre><code>x.contains("Male") </code></pre> <p>and I was getting same error</p> <p>Is there a better way to do this?</p>
1
2016-09-19T01:58:44Z
39,564,558
<p>Create a mapping function, and use that to map the values.</p> <pre><code>def map_identity(identity): if gender.lower() == 'male': return 1 elif gender.lower() == 'female': return 2 else: return 3 df["B"] = df["A"].map(map_identity) </code></pre>
0
2016-09-19T02:28:13Z
[ "python", "pandas" ]
Create new column in pandas based on value of another column
39,564,372
<p>I have some dataset about genders of various individuals. Say, the dataset looks like this:</p> <pre><code>Male Female Male and Female Male Male Female Trans Unknown Male and Female </code></pre> <p>Some identify themselves as Male, some female and some identify themselves as both male and female.</p> <p>Now, what I want to do is create a new column in Pandas which maps </p> <pre><code>Males to 1, Females to 2, Others to 3 </code></pre> <p>I wrote some code </p> <pre><code>def gender(x): if x.str.contains("Male") return 1 elif x.str.contains("Female") return 2 elif return 3 df["Gender Values"] = df["Gender"].apply(gender) </code></pre> <p>But I was getting errors that function doesn't contain any attribute contains. I tried removing str:</p> <pre><code>x.contains("Male") </code></pre> <p>and I was getting same error</p> <p>Is there a better way to do this?</p>
1
2016-09-19T01:58:44Z
39,566,156
<p>You can use:</p> <pre><code>def gender(x): if "Female" in x and "Male" in x: return 3 elif "Male" in x: return 1 elif "Female" in x: return 2 else: return 4 df["Gender Values"] = df["Gender"].apply(gender) print (df) Gender Gender Values 0 Male 1 1 Female 2 2 Male and Female 3 3 Male 1 4 Male 1 5 Female 2 6 Trans 4 7 Unknown 4 8 Male and Female 3 </code></pre>
1
2016-09-19T05:51:13Z
[ "python", "pandas" ]
How can I use a 2D array of boolean rows to filter another 2D array?
39,564,421
<p>I have some data in a (3, m) array.</p> <p>I have another array of masks in (n, 3) shape. The rows of this mask are boolean filters that need to be applied on the data array before performing some function. Is there a vectorized way to apply the filter and compute the function?</p> <p>Here's an example using a loop for clarity, assuming the function is a mean(). I'd like to do this using purely Numpy (without the list comprehension).</p> <p>(Obviously, the sizes of the arrays are much larger in reality.)</p> <pre><code>import numpy as np data = np.array([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11] ]) masks = np.array([ [True, True, False], [False, True, False], [False, True, True], [True, False, False], [True, False, True] ]) means = np.array([data[mask].mean(axis=0) for mask in masks]) # means array([[ 2., 3., 4., 5.], [ 4., 5., 6., 7.], [ 6., 7., 8., 9.], [ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]) </code></pre>
4
2016-09-19T02:06:38Z
39,564,738
<p>This feels a bit crude and messy, but it does work without a loop.</p> <p>There are two main tasks:</p> <ul> <li>expand <code>data</code> so it can be indexed with <code>masks</code> - from (5,4) to (5,3,4) </li> <li>apply <code>means</code> to groups of rows; the closest I can find is <code>np.sum.reduceat</code>.</li> </ul> <hr> <p>construct <code>reduceat</code> indices:</p> <pre><code>In [253]: cnt = masks.sum(axis=1) In [254]: cnt1=np.concatenate(([0],np.cumsum(cnt)[:-1])) In [255]: cnt Out[255]: array([2, 1, 2, 1, 2]) # True count per row In [256]: cnt1 Out[256]: array([0, 2, 3, 5, 6]) # reduceat index positions </code></pre> <p>expand <code>data</code> and <code>mask</code>:</p> <pre><code>In [257]: mdata=data[None,...].repeat(masks.shape[0],0)[masks,:] </code></pre> <p><code>add</code> rows and divide by the row count for each group</p> <pre><code>In [258]: np.add.reduceat(mdata,cnt1,0)/cnt[:,None] Out[258]: array([[ 2., 3., 4., 5.], [ 4., 5., 6., 7.], [ 6., 7., 8., 9.], [ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]) </code></pre> <p>In case it helps:</p> <pre><code>In [263]: mdata Out[263]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 4, 5, 6, 7], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [ 0, 1, 2, 3], [ 0, 1, 2, 3], [ 8, 9, 10, 11]]) </code></pre> <p>A possibly better way to get this <code>mdata</code> is</p> <pre><code>In [285]: data[np.where(masks)[1],:] Out[285]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 4, 5, 6, 7], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [ 0, 1, 2, 3], [ 0, 1, 2, 3], [ 8, 9, 10, 11]]) </code></pre> <p>The <code>where(...)[1]</code> are the column positions of the True in <code>masks</code>, which are the rows that we want to select from <code>data</code>.</p> <p>===========================</p> <p><code>@capitalistcuttle</code> creates a (5,3,4) array as well, but avoids the need for <code>reduceat</code> by zeroing out the <code>False</code> rows. That way the can enter into the <code>mean</code> or <code>sum</code> without affecting value. That reminds me of how masked arrays perform tasks like this. They <code>fill</code> the masked values with a value like 0 or 1 that doesn't affect the calculation.</p> <p>Inspired by that here's a MaskedArray solution</p> <p>Expand both <code>data</code> and <code>masks</code> to the (5,3,4) size:</p> <pre><code>In [322]: data1=data[None,:,:].repeat(5,0) In [323]: masks1=masks[:,:,None].repeat(4,-1) In [324]: data1.shape, masks1.shape Out[324]: ((5, 3, 4), (5, 3, 4)) </code></pre> <p>Make masked array from that:</p> <pre><code>In [325]: madata=np.ma.MaskedArray(data1,~masks1) In [326]: madata Out[326]: masked_array(data = [[[0 1 2 3] [4 5 6 7] [-- -- -- --]] [[-- -- -- --] [4 5 6 7] [-- -- -- --]] ... [[0 1 2 3] [-- -- -- --] [8 9 10 11]]], mask = [[[False False False False] [False False False False] [ True True True True]] [[ True True True True] [False False False False] [ True True True True]] ...], fill_value = 999999) </code></pre> <p>Now we can simply use the <code>mean</code> method, letting it take care of 0 fill and adjusting for the number of valid rows.</p> <pre><code>In [327]: madata.mean(axis=1) Out[327]: masked_array(data = [[2.0 3.0 4.0 5.0] [4.0 5.0 6.0 7.0] [6.0 7.0 8.0 9.0] [0.0 1.0 2.0 3.0] [4.0 5.0 6.0 7.0]], mask = [[False False False False] [False False False False] [False False False False] [False False False False] [False False False False]], fill_value = 1e+20) </code></pre> <p>That the <code>.data</code> attribute to convert back to regular array.</p> <p>This MaskedArray approach is probably slower, since it creates a larger array, but it may be more general - it can be used operations, as long as they are defined in <code>np.ma</code> or its methods.</p>
0
2016-09-19T02:59:33Z
[ "python", "performance", "numpy", "vectorization" ]
How can I use a 2D array of boolean rows to filter another 2D array?
39,564,421
<p>I have some data in a (3, m) array.</p> <p>I have another array of masks in (n, 3) shape. The rows of this mask are boolean filters that need to be applied on the data array before performing some function. Is there a vectorized way to apply the filter and compute the function?</p> <p>Here's an example using a loop for clarity, assuming the function is a mean(). I'd like to do this using purely Numpy (without the list comprehension).</p> <p>(Obviously, the sizes of the arrays are much larger in reality.)</p> <pre><code>import numpy as np data = np.array([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11] ]) masks = np.array([ [True, True, False], [False, True, False], [False, True, True], [True, False, False], [True, False, True] ]) means = np.array([data[mask].mean(axis=0) for mask in masks]) # means array([[ 2., 3., 4., 5.], [ 4., 5., 6., 7.], [ 6., 7., 8., 9.], [ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]) </code></pre>
4
2016-09-19T02:06:38Z
39,565,286
<p>So, after playing with it for a while, seems this kind of broadcasting works for mean() as the function specifically:</p> <pre><code>means = (masks[:, :, np.newaxis] * data).sum(axis=1) / masks.sum(axis=1)[:, np.newaxis] # means array([[ 2., 3., 4., 5.], [ 4., 5., 6., 7.], [ 6., 7., 8., 9.], [ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]) </code></pre> <p>And for other functions more generally, you could use this format (where mean() can be replaced with desired function):</p> <pre><code>means = (masks[:, :, np.newaxis] * data).mean(axis=1) * masks.shape[1] / masks.sum(axis=1)[:, np.newaxis] # means array([[ 2., 3., 4., 5.], [ 4., 5., 6., 7.], [ 6., 7., 8., 9.], [ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]) </code></pre>
0
2016-09-19T04:16:58Z
[ "python", "performance", "numpy", "vectorization" ]
How can I use a 2D array of boolean rows to filter another 2D array?
39,564,421
<p>I have some data in a (3, m) array.</p> <p>I have another array of masks in (n, 3) shape. The rows of this mask are boolean filters that need to be applied on the data array before performing some function. Is there a vectorized way to apply the filter and compute the function?</p> <p>Here's an example using a loop for clarity, assuming the function is a mean(). I'd like to do this using purely Numpy (without the list comprehension).</p> <p>(Obviously, the sizes of the arrays are much larger in reality.)</p> <pre><code>import numpy as np data = np.array([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11] ]) masks = np.array([ [True, True, False], [False, True, False], [False, True, True], [True, False, False], [True, False, True] ]) means = np.array([data[mask].mean(axis=0) for mask in masks]) # means array([[ 2., 3., 4., 5.], [ 4., 5., 6., 7.], [ 6., 7., 8., 9.], [ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]) </code></pre>
4
2016-09-19T02:06:38Z
39,582,944
<p>That problem is easily solvable with <code>matrix-multiplication</code> using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow"><code>np.dot</code></a> and as such must be really efficient. Here's the implementation -</p> <pre><code>np.true_divide(masks.dot(data),masks.sum(1)[:,None]) </code></pre>
0
2016-09-19T22:17:46Z
[ "python", "performance", "numpy", "vectorization" ]
Adding a column to a Multiindex Dataframe
39,564,433
<blockquote> <blockquote> <p>I would like to add a column SUM to the df1 below. It's a Datetime MultiIndex and the new column SUM should return the sum of the price row.</p> </blockquote> </blockquote> <pre><code>&gt; multex = pd.MultiIndex.from_product([['price', 'weight','quantity','portfolio'] ,df1.index],names=['Date', 'Stats']) &gt; &gt; new_df = pd.DataFrame(index=multex, columns= df1.columns.values.tolist()) </code></pre> <blockquote> <p>Subsequently would like to add a row SUM as well that returns the same value. I've tried the following so far:</p> </blockquote> <pre><code>df1['SUM']= df1.ix['price'].sum(axis=1) A B C D E 2006-04-28 00:00:00 price 69.62 69.62 6.518 65.09 69.62 weight std 2006-05-01 00:00:00 price 71.5 71.5 6.522 65.16 71.5 weight std 2006-05-02 00:00:00 price 72.34 72.34 6.669 66.55 72.34 weight std </code></pre>
1
2016-09-19T02:08:11Z
39,565,969
<p>You can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>DataFrame.sort_index</code></a>, because error:</p> <blockquote> <p>KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'</p> </blockquote> <p>Then use <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow">slicers</a>:</p> <pre><code>df1 = df1.sort_index() idx = pd.IndexSlice df1['SUM'] = df1.loc[idx[:,'price'],:].sum(axis=1) print (df1) A B C D E SUM Date Stats 2006-04-28 00:00:00 price 69.62 69.62 6.518 65.09 69.62 280.468 std NaN NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN NaN 2006-05-01 00:00:00 price 71.50 71.50 6.522 65.16 71.50 286.182 std NaN NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN NaN 2006-05-02 00:00:00 price 72.34 72.34 6.669 66.55 72.34 290.239 std NaN NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN NaN </code></pre> <hr> <pre><code>df1['SUM'] = df1.loc[(slice(None), slice('price')),:].sum(axis=1) print (df1) A B C D E SUM Date Stats 2006-04-28 00:00:00 price 69.62 69.62 6.518 65.09 69.62 280.468 std NaN NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN NaN 2006-05-01 00:00:00 price 71.50 71.50 6.522 65.16 71.50 286.182 std NaN NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN NaN 2006-05-02 00:00:00 price 72.34 72.34 6.669 66.55 72.34 290.239 std NaN NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN NaN </code></pre>
1
2016-09-19T05:30:49Z
[ "python", "pandas", "numpy", "dataframe" ]
Python's Popen + communicate only returning the first line of stdout
39,564,455
<p>I'm trying to use my command-line git client and Python's I/O redirection in order to automate some common operations on a lot of git repos. (Yes, this is hack-ish. I might go back and use a Python library to do this later, but for now it seems to be working out ok :) )</p> <p>I'd like to be able to capture the output of calling git. Hiding the output will look nicer, and capturing it will let me log it in case it's useful.</p> <p><strong>My problem is that I can't get more than the first line of output when I run a 'git clone' command</strong>. Weirdly, the same code with 'git status' seems to work just fine.</p> <p>I'm running Python 2.7 on Windows 7 and I'm using the cmd.exe command interpreter.</p> <p>My sleuthing so far:</p> <ol> <li><p>When I call subprocess.call() with "git clone" it runs fine and I see the output on the console (which confirms that git is producing output, even though I'm not capturing it). This code:</p> <pre><code>dir = "E:\\Work\\etc\\etc" os.chdir(dir) git_cmd = "git clone git@192.168.56.101:Mike_VonP/bit142_assign_2.git" #print "SUBPROCESS.CALL" + "="*20 #ret = subprocess.call(git_cmd.split(), shell=True) </code></pre> <p>will produce this output on the console:</p> <pre><code>SUBPROCESS.CALL==================== Cloning into 'bit142_assign_2'... remote: Counting objects: 9, done. remote: Compressing objects: 100% (4/4), done. remote: Total 9 (delta 0), reused 0 (delta 0) Receiving objects: 100% (9/9), done. Checking connectivity... done. </code></pre></li> <li><p>If I do the same thing with POpen directly, I see the same output on the console (which is also <em>not</em> being captured). This code:</p> <pre><code># (the dir = , os.chdir, and git_cmd= lines are still executed here) print "SUBPROCESS.POPEN" + "="*20 p=subprocess.Popen(git_cmd.split(), shell=True) p.wait() </code></pre> <p>will produce this (effectively identical) output:</p> <pre><code>SUBPROCESS.POPEN==================== Cloning into 'bit142_assign_2'... remote: Counting objects: 9, done. remote: Compressing objects: 100% (4/4), done. remote: Total 9 (delta 0), reused 0 (delta 0) Receiving objects: 100% (9/9), done. Checking connectivity... done. </code></pre> <p>(Obviously I'm deleting the cloned repo between runs, otherwise I'd get a 'Everything is up to date' message)</p></li> <li><p><strong>If I use the communicate() method what I expect is to get a string that contains all the output that I'm seeing above. Instead I only see the line</strong> <code>Cloning into 'bit142_assign_2'...</code>.<br> This code:</p> <pre><code>print "SUBPROCESS.POPEN, COMMUNICATE" + "="*20 p=subprocess.Popen(git_cmd.split(), shell=True,\ bufsize = 1,\ stderr=subprocess.PIPE,\ stdout=subprocess.PIPE) tuple = p.communicate() p.wait() print "StdOut:\n" + tuple[0] print "StdErr:\n" + tuple[1] </code></pre> <p>will produce this output:</p> <pre><code>SUBPROCESS.POPEN, COMMUNICATE==================== StdOut: StdErr: Cloning into 'bit142_assign_2'... </code></pre> <p>On the one hand I've redirected the output (as you can see from the fact that it's not in the output) but I'm also only capturing that first line.</p></li> </ol> <p>I've tried lots and lots of stuff (calling <code>check_output</code> instead of popen, using pipes with subprocess.call, using pipes with subprocess.popen, and probably other stuff I've forgotten about) but nothing works - I only ever capture that first line of output.</p> <p>Interestingly, <strong>the exact same code <em>does</em> work correctly with 'git status'</strong>. Once the repo has been cloned calling git status produces three lines of output (which collectively say 'everything is up to date') and that third example (the POpen+communicate code) does capture all three lines of output.</p> <p>If anyone has any ideas about what I'm doing wrong or any thoughts on anything I could try in order to better diagnose this problem I would greatly appreciate it.</p>
1
2016-09-19T02:12:03Z
39,564,562
<p>Try adding the <code>--progress</code> option to your git command. This forces git to emit the progress status to stderr even when the the git process is not attached to a terminal - which is the case when running git via the <code>subprocess</code> functions.</p> <pre><code>git_cmd = "git clone --progress git@192.168.56.101:Mike_VonP/bit142_assign_2.git" print "SUBPROCESS.POPEN, COMMUNICATE" + "="*20 p = subprocess.Popen(git_cmd.split(), stderr=subprocess.PIPE, stdout=subprocess.PIPE) tuple = p.communicate() p.wait() print "StdOut:\n" + tuple[0] print "StdErr:\n" + tuple[1] </code></pre> <p>N.B. I am unable to test this on Windows, but it is effective on Linux.</p> <p>Also, it should not be necessary to specify <code>shell=True</code> and this might be a security problem, so it's best avoided.</p>
1
2016-09-19T02:28:43Z
[ "python", "git", "popen", "communicate" ]
Python's Popen + communicate only returning the first line of stdout
39,564,455
<p>I'm trying to use my command-line git client and Python's I/O redirection in order to automate some common operations on a lot of git repos. (Yes, this is hack-ish. I might go back and use a Python library to do this later, but for now it seems to be working out ok :) )</p> <p>I'd like to be able to capture the output of calling git. Hiding the output will look nicer, and capturing it will let me log it in case it's useful.</p> <p><strong>My problem is that I can't get more than the first line of output when I run a 'git clone' command</strong>. Weirdly, the same code with 'git status' seems to work just fine.</p> <p>I'm running Python 2.7 on Windows 7 and I'm using the cmd.exe command interpreter.</p> <p>My sleuthing so far:</p> <ol> <li><p>When I call subprocess.call() with "git clone" it runs fine and I see the output on the console (which confirms that git is producing output, even though I'm not capturing it). This code:</p> <pre><code>dir = "E:\\Work\\etc\\etc" os.chdir(dir) git_cmd = "git clone git@192.168.56.101:Mike_VonP/bit142_assign_2.git" #print "SUBPROCESS.CALL" + "="*20 #ret = subprocess.call(git_cmd.split(), shell=True) </code></pre> <p>will produce this output on the console:</p> <pre><code>SUBPROCESS.CALL==================== Cloning into 'bit142_assign_2'... remote: Counting objects: 9, done. remote: Compressing objects: 100% (4/4), done. remote: Total 9 (delta 0), reused 0 (delta 0) Receiving objects: 100% (9/9), done. Checking connectivity... done. </code></pre></li> <li><p>If I do the same thing with POpen directly, I see the same output on the console (which is also <em>not</em> being captured). This code:</p> <pre><code># (the dir = , os.chdir, and git_cmd= lines are still executed here) print "SUBPROCESS.POPEN" + "="*20 p=subprocess.Popen(git_cmd.split(), shell=True) p.wait() </code></pre> <p>will produce this (effectively identical) output:</p> <pre><code>SUBPROCESS.POPEN==================== Cloning into 'bit142_assign_2'... remote: Counting objects: 9, done. remote: Compressing objects: 100% (4/4), done. remote: Total 9 (delta 0), reused 0 (delta 0) Receiving objects: 100% (9/9), done. Checking connectivity... done. </code></pre> <p>(Obviously I'm deleting the cloned repo between runs, otherwise I'd get a 'Everything is up to date' message)</p></li> <li><p><strong>If I use the communicate() method what I expect is to get a string that contains all the output that I'm seeing above. Instead I only see the line</strong> <code>Cloning into 'bit142_assign_2'...</code>.<br> This code:</p> <pre><code>print "SUBPROCESS.POPEN, COMMUNICATE" + "="*20 p=subprocess.Popen(git_cmd.split(), shell=True,\ bufsize = 1,\ stderr=subprocess.PIPE,\ stdout=subprocess.PIPE) tuple = p.communicate() p.wait() print "StdOut:\n" + tuple[0] print "StdErr:\n" + tuple[1] </code></pre> <p>will produce this output:</p> <pre><code>SUBPROCESS.POPEN, COMMUNICATE==================== StdOut: StdErr: Cloning into 'bit142_assign_2'... </code></pre> <p>On the one hand I've redirected the output (as you can see from the fact that it's not in the output) but I'm also only capturing that first line.</p></li> </ol> <p>I've tried lots and lots of stuff (calling <code>check_output</code> instead of popen, using pipes with subprocess.call, using pipes with subprocess.popen, and probably other stuff I've forgotten about) but nothing works - I only ever capture that first line of output.</p> <p>Interestingly, <strong>the exact same code <em>does</em> work correctly with 'git status'</strong>. Once the repo has been cloned calling git status produces three lines of output (which collectively say 'everything is up to date') and that third example (the POpen+communicate code) does capture all three lines of output.</p> <p>If anyone has any ideas about what I'm doing wrong or any thoughts on anything I could try in order to better diagnose this problem I would greatly appreciate it.</p>
1
2016-09-19T02:12:03Z
39,565,119
<p>There are two parts of interest here, one being Python-specific and one being Git-specific.</p> <h3>Python</h3> <p>When using the <code>subprocess</code> module, you can elect to control up to three I/O channels of the program you run: stdin, stdout, and stderr. This is true for <code>subprocess.call</code> and <code>subprocess.check_call</code> as well as <code>subprocess.Popen</code>, but both <code>call</code> and <code>check_call</code> immediately call the new process object's <code>wait</code> method, so for various reasons, it's unwise to supply <code>subprocess.PIPE</code> for the stdout and/or stderr with these two operations.<sup>1</sup></p> <p>Other than that, using <code>subprocess.call</code> is equivalent to using <code>subprocess.Popen</code>. In fact, the code for <code>call</code> is a one-liner:</p> <pre><code>def call(*popenargs, **kwargs): return Popen(*popenargs, **kwargs).wait() </code></pre> <p>If you choose not to redirect any of the I/O channels, programs that read input get it from the same place Python would, programs that write output to stdout write it to the same place your own Python code would,<sup>2</sup> and programs that write output to stderr write it to the same place Python would.</p> <p>You can, of course, redirect stdout and/or stderr to actual files, as well as to <code>subprocess.PIPE</code>s. Files and pipes are <em>not</em> interactive "terminal" or "tty" devices (i.e., are not seen as being directly connected to a human being). This leads us to Git.</p> <h3>Git</h3> <p>Git programs may generally read from stdin and/or write to stdout and/or stderr. Git may also invoke additional programs, which may do the same, or may bypass these standard I/O channels.</p> <p>In particular, <code>git clone</code> mainly writes to its stderr, as you have observed. Moreover, as <a href="http://stackoverflow.com/a/39564562/1256452">mhawke answered</a>, you must add <code>--progress</code> to make Git write progress messages to stderr Git is not talking to an interactive tty device.</p> <p>If Git needs a password or other authentication when cloning via <code>https</code> or <code>ssh</code>, Git will run an auxiliary program to get this. These programs, for the most part, <em>bypass</em> stdin entirely (by opening <code>/dev/tty</code> on POSIX systems, or the equivalent on Windows), so as to interact with the user. How well this will work, or whether it will work at all, in your automated environment is a good question (but again outside the scope of this answer). But this does bring us back to Python, because ...</p> <h3>Python</h3> <p>Besides the <code>subprocess</code> module, there are some external libraries, <a href="https://amoffat.github.io/sh/" rel="nofollow"><code>sh</code></a> and <a href="https://pypi.python.org/pypi/pexpect/" rel="nofollow"><code>pexpect</code></a>, and some facilities built into Python itself <a href="https://docs.python.org/2/library/pty.html" rel="nofollow">via the <code>pty</code> module</a>, that can open a pseudo-tty: an interactive tty device that, instead of being connected directly to a human, is connected to your program.</p> <p>When using ptys, you can have Git behave identically to when it is talking directly to a human—in fact, "talking to a human" today is actually done with ptys (or equivalent) anyway, since there are programs running the various windowing systems. Moreover, programs that ask a human for a password may<sup>3</sup> now interact with your own Python code. This can be good or bad (or even both), so consider whether you want that to happen.</p> <hr> <p><sup>1</sup>Specifically, the point of the <code>communicate</code> method is to manage I/O traffic between the up-to-three streams, if any or all of them are <code>PIPE</code>, without having the subprocess wedge. Imagine, if you will, a subprocess that prints 64K of text to stdout, then 64K of text to stderr, then another 64K of text to stdout, and then reads from stdin. If you try to read or write any of these in any specific order, the subprocess will "get stuck" waiting for you to clear something else, while you'll get stuck waiting for the subprocess to finish whichever one you chose to complete first. What <code>communicate</code> does instead is to use threads or OS-specific non-blocking I/O methods to feed the subprocess input <em>while</em> reading its stdout and stderr, all simultaneously.</p> <p>In other words, it handled <em>multiplexing</em>. Thus, if you are not supplying <code>subprocess.PIPE</code> for at least <em>two</em> of the three I/O channels, it's safe to bypass the <code>communicate</code> method. If you <em>are</em>, it is not (unless you implement your own multiplexing).</p> <p>There's a somewhat curious edge case here: if you supply <code>subprocess.STDOUT</code> for the stderr output, this tells Python to direct the two outputs of the subprocess into a single communications channel. This counts as only one pipe, so if you combine the subprocess's stdout and stderr, and supply no input, you can bypass the <code>communicate</code> method.</p> <p><sup>2</sup>In fact, the subprocess inherits the <em>process</em>'s stdin, stdout, and stderr, which may not match Python's <code>sys.stdin</code>, <code>sys.stdout</code>, and <code>sys.stderr</code> if you've over-ridden those. This gets into details probably best ignored here. :-)</p> <p><sup>3</sup>I say "may" instead of "will" because <code>/dev/tty</code> accesses the <em>controlling terminal</em>, and not all ptys are controlling terminals. This also gets complicated and OS-specific and is also beyond the scope of this answer.</p>
1
2016-09-19T03:56:36Z
[ "python", "git", "popen", "communicate" ]
Cleaning string from scraping webpage python
39,564,456
<p>I scraped the content of a website via Python and the requests library and I tried to clean out all the html and javascript.</p> <pre><code>from lxml.html.clean import Cleaner import lxml.html as html text = html.document_fromstring(r.text).text_content() cleaner = Cleaner(kill_tags=['noscript', 'img', 'a', 'h1'], remove_tags=['p'], style=True) text = cleaner.clean_html(text) text = ' '.join(text.split()) </code></pre> <p>But I'm still getting a lot of stuff that looks like this (*** replacing identifying info):</p> <pre><code>var STYLEID = \'9\', STATICURL = \'static/\', IMGDIR = \'comiis_xzs19lou\', VERHASH = \'wRx\', charset = \'gbk\', cookiepre = \'bdRb_a91d_\', cookiedomain = \'.***\', cookiepath = \'/\', showusercard = \'1\', attackevasive = \'0\', disallowfloat = \'login|newthread\', creditnotice = \'****\', defaultstyle = \'\', REPORTURL = \'***==\', SITEURL = \'http://****/\', JSPATH = \'data/cache/\', CSSPATH = \'data/cache/style_\', DYNAMICURL = \'\'; body{background:#EBDFC5;} </code></pre> <p>and</p> <pre><code>var fid = parseInt(\'12\'), tid = parseInt(\'2474591\'); zoomstatus = parseInt(1);var imagemaxwidth = \'600\';var aimgcount = new Array(); #framesbO97X { margin:0px !important;border:0px !important;}#portal_block_1251 { margin:0px !important;border:0px !important;}#portal_block_1251 .dxb_bc { margin:0px !important;}#frameJo3fOn { margin:0px !important;border:0px !important;}#portal_block_1252 { margin:0px !important;border:0px !important;}#portal_block_1252 .dxb_bc { margin:0px !important;}#framerU9V5m { margin:0px !important;border:0px !important;}#portal_block_1253 { margin:0px !important;border:0px !important;}#portal_block_1253 .dxb_bc { margin:0px !important;}#frameRCK99J { margin:10px 0px 5px !important;}#frameJ7YGtB { margin:0px !important;border:0px !important;}#portal_block_1255 { margin:0px !important;border:0px !important;}#portal_block_1255 .dxb_bc { margin:0px !important;}#framerVqc7m { margin:0px !important;border:0px !important;}#portal_block_1256 { margin:0px !important;border:0px !important;}#portal_block_1256 .dxb_bc { margin:0px !important;}#frameFW5eQe { margin:0px !important;border:0px !important;}#frameKBtrA1 { margin:0px !important;border:0px !important;}#portal_block_1257 { margin:0px !important;border:0px !important;}#portal_block_1257 .dxb_bc { margin:0px !important;}#portal_block_1258 { margin:0px !important;border:0px !important;}#portal_block_1258 .dxb_bc { margin:0px !important;} </code></pre> <p>and</p> <pre><code>function succeedhandle_followmod(url, msg, values) { var fObj = $(\'followmod_\'+values[\'fuid\']); if(values[\'type\'] == \'add\') { fObj.innerHTML = \***\'; fObj.href = \'home.php?mod=spacecp&amp;amp;ac=follow&amp;amp;op=del&amp;amp;fuid=\'+values[\'fuid\']; } else if(values[\'type\'] == \'del\') { fObj.innerHTML = \***\'; fObj.href = \'home.php?mod=spacecp&amp;amp;ac=follow&amp;amp;op=add&amp;amp;hash=6a62d013&amp;amp;fuid=\'+values[\'fuid\']; } } _***(null, $C("t_f", null, "td"), "", "***", "***"); var rel_tid = "2474591"; var rel_title = "%C9%BD%B6%AB%CA%AF%BB%AF%BE%AD%C0%ED%B7%EB%B6%AB%C7%E0%B4%FE%B2%B6%EE%BF%D1%BA%C6%DA%BC%E4%CB%C0%CD%F6%A1%AA%A1%AA%CA%C7%B7%F1%B1%BB%C9%BD%B6%AB%CA%A1%BC%EC%B2%EC%D4%BA%BC%EC%B2%EC%B3%A4%CE%E2%C5%F4%B7%C9%C3%F0%BF%DA"; var rel_reltid = "0"; var rel_prepos = ""; var my_siteid = "7149150"; var rel_uid = "0"; var rel_views = "3909"; var rel_replies = "11"; var rel_page = "1"; var rel_show = "0"; _attachEvent(window, \'load\', getForbiddenFormula, document); function getForbiddenFormula() { var toGetForbiddenFormulaFIds = function () { ajaxget(\'plugin.php?id=cloudsearch&amp;amp;formhash=6a62d013\'); }; var a = document.body.getElementsByTagName(\'a\'); for(var i = 0;i document.documentElement.clientWidth) { $(\'***').style.cssFloat = \'right\'; $(\'***').style.left = \'auto\'; $(\'***\').style.right = 0; } else { $(\'***\').style.cssFloat = \'left\'; $(\'***\').style.left = (qrleft) + \'px\'; $(\'***\').style.right = \'auto\'; } } _attachEvent(window, \'scroll\', function () { ***; }) _attachEvent(window, \'load\', function() { ***; }, document); #scrolltop { display: none; } ul#navmenu ul { display: none; position: absolute; left: -233px; bottom: 5px; } ul#navmenu li:hover ul ul, ul#navmenu li.iehover ul ul, { display: none; } ul#navmenu li:hover ul, ul#navmenu ul li:hover ul, ul#navmenu ul ul li:hover ul, ul#navmenu li.iehover ul, ul#navmenu ul li.iehover ul, ul#navmenu ul ul li.iehover ul { display: block; } #jz52top a {margin: 6px 0;} #jz52top { visibility: visible; right: 10px; } #jz52topa { visibility: hidden;} #jz52top, #jz52top a { border: none;} #jz52top { position: fixed; bottom: 40px; display: block; width: 40px; background: none repeat scroll 0% 0% transparent; border: 0px #cdcdcd solid; border-radius: 3px; border-top: 0; cursor: pointer; } #jz52top:hover { text-decoration: none; } #jz52top a { display: block; width: 40px; height: 40px; padding: 0; line-height: 12px; text-align: center; color: #787878; text-decoration: none; background: #00a398 url(\'source/plugin/jz52_top/template/jz52top.png\') no-repeat 0 0; border-top: 0px #cdcdcd solid; } a.jz52topa:hover { background-position: -40px 0px !important;} a.replyfast { background-position: 0 -40px !important; } a.replyfast:hover { background-position: -40px -40px !important;} a.returnlist { background-position: 0 -80px !important; } a.returnlist:hover { background-position: -40px -80px !important;} a.returnboard { background-position: -80px -240px !important; } a.returnboard:hover { background-position: -120px -240px !important;} a.jzqr { background-position: 0 -120px !important; } a.jzqr:hover { background-position: -40px -120px !important;} a.jzwx { background-position: 0 -320px !important; } a.jzwx:hover { background-position: -40px -320px !important;} a.jzkf { background-position: -80px 0px !important; } a.jzkf:hover { background-position: -120px -0px !important;} a.jzfx { background-position: -80px -40px !important; } a.jzfx:hover { background-position: -120px -40px !important;} .jzfxn { background: #fff !important; width: 231px !important; height: 260px !important; } a.jzlast { background-position: -80px -80px !important; } a.jzlast:hover { background-position: -120px -80px !important;} a.jznext { background-position: -80px -120px !important; } a.jznext:hover { background-position: -120px -120px !important;} a.jzsct { background-position: 0px -160px !important; } a.jzsct:hover { background-position: -40px -160px !important;} a.jzscb { background-position: -80px -160px !important; } a.jzscb:hover { background-position: -120px -160px !important;} a.jzqqq { background-position: 0px -200px !important; } a.jzqqq:hover { background-position: -40px -200px !important;} a.jzwo { background-position: -80px -200px !important; } a.jzwo:hover { background-position: -120px -200px !important;} a.jzzdy { background-position: 0px -240px !important; } a.jzzdy:hover { background-position: -40px -240px !important;} a.jzfbzt { background-position: 0px -280px !important; } a.jzfbzt:hover { background-position: -40px -280px !important;} #jzqrn { background: #fff !important; width: 231px !important; height: 260px !important; } #jzqrn { border: 1px solid rgb(210, 210, 210); } #jzqrn p { font-size: 15px; padding-bottom: 15px; text-align: center; color: #999; font-family: Microsoft YaHei; } #jzwon { background: #fff !important; width: 231px !important; height: 260px !important; } #jzwon { border: 1px solid rgb(210, 210, 210); } #jzfxn { border: 1px solid rgb(210, 210, 210); } #jzfxn h3 { height: 23px; background: none repeat scroll 0% 0% rgb(250, 250, 250); border-bottom: 1px solid rgb(236, 236, 236); padding: 10px 0px 0px 10px; } #jzfxn .bdsharebuttonbox { padding: 13px 0px 0px 20px; } #jzfxn .bdsharebuttonbox a, #jzfxn .bdsharebuttonbox .bds_more { float: left; font-size: 12px; padding-left: 25px; line-height: 16px; text-align: left; height: 16px; background: url("***") no-repeat scroll 0px 0px ; background-repeat: no-repeat; cursor: pointer; margin: 6px 6px 6px 0px; text-indent: 0; overflow: hidden; width: 68px; } #jzfxn .bdsharebuttonbox .bds_qzone { background-position: 0px -52px !important; } #jzfxn .bdsharebuttonbox .bds_tsina { background-position: 0px -104px !important; } #jzfxn .bdsharebuttonbox .bds_tqq { background-position: 0px -260px !important; } #jzfxn .bdsharebuttonbox .bds_renren { background-position: 0px -208px !important; } #jzfxn .bdsharebuttonbox .bds_tqf { background-position: 0px -364px !important; } #jzfxn .bdsharebuttonbox .bds_tieba { background-position: 0px -728px !important; } #jzfxn .bdsharebuttonbox .bds_sqq { background-position: 0px -2652px !important; } #jzfxn .bdsharebuttonbox .bds_hi { background-position: 0px -416px !important; } #jzfxn .bdsharebuttonbox .bds_isohu { background-position: 0px -3016px !important; } #jzfxn .bdsharebuttonbox .bds_weixin { background-position: 0px -1612px !important; } #jzfxn .bdsharebuttonbox .bds_t163 { background-position: 0px -832px !important; } #jzfxn .bdsharebuttonbox .bds_tsohu { background-position: 0px -520px !important; } #jzfxn .bdsharebuttonbox .bds_baidu { background-position: 0px -2600px !important; } #jzfxn .bdsharebuttonbox .bds_qq { background-position: 0px -624px !important; } #jz52top a b { visibility: hidden; font-weight: normal; } // JavaScript Document function goTopEx(){ var obj=document.getElementById("goTopBtn"); function getScrollTop(){ return document.documentElement.scrollTop || document.body.scrollTop; } function setScrollTop(value){ if(document.documentElement.scrollTop){ document.documentElement.scrollTop=value; }else{ document.body.scrollTop=value; } } window.onscroll=function(){getScrollTop()&amp;gt;0?obj.style.display="":obj.style.display="none"; var h=document.body.scrollHeight - getScrollTop() - obj.offsetTop - obj.offsetHeight; obj.style.bottom=0+"px"; </code></pre> <p>Any idea how to get rid of all of that?</p>
1
2016-09-19T02:12:12Z
39,564,568
<p>You need to clean <code>&lt;script&gt;</code> tags if you want to get rid of javascript. The only thing <code>&lt;noscript&gt;</code> tags are for is displaying an image or text if the browser has scripts disabled.</p> <pre><code>cleaner = Cleaner(kill_tags=['script', 'noscript', 'img', 'a', 'h1'], remove_tags=['p'], style=True) </code></pre>
1
2016-09-19T02:29:46Z
[ "javascript", "python" ]
Cleaning string from scraping webpage python
39,564,456
<p>I scraped the content of a website via Python and the requests library and I tried to clean out all the html and javascript.</p> <pre><code>from lxml.html.clean import Cleaner import lxml.html as html text = html.document_fromstring(r.text).text_content() cleaner = Cleaner(kill_tags=['noscript', 'img', 'a', 'h1'], remove_tags=['p'], style=True) text = cleaner.clean_html(text) text = ' '.join(text.split()) </code></pre> <p>But I'm still getting a lot of stuff that looks like this (*** replacing identifying info):</p> <pre><code>var STYLEID = \'9\', STATICURL = \'static/\', IMGDIR = \'comiis_xzs19lou\', VERHASH = \'wRx\', charset = \'gbk\', cookiepre = \'bdRb_a91d_\', cookiedomain = \'.***\', cookiepath = \'/\', showusercard = \'1\', attackevasive = \'0\', disallowfloat = \'login|newthread\', creditnotice = \'****\', defaultstyle = \'\', REPORTURL = \'***==\', SITEURL = \'http://****/\', JSPATH = \'data/cache/\', CSSPATH = \'data/cache/style_\', DYNAMICURL = \'\'; body{background:#EBDFC5;} </code></pre> <p>and</p> <pre><code>var fid = parseInt(\'12\'), tid = parseInt(\'2474591\'); zoomstatus = parseInt(1);var imagemaxwidth = \'600\';var aimgcount = new Array(); #framesbO97X { margin:0px !important;border:0px !important;}#portal_block_1251 { margin:0px !important;border:0px !important;}#portal_block_1251 .dxb_bc { margin:0px !important;}#frameJo3fOn { margin:0px !important;border:0px !important;}#portal_block_1252 { margin:0px !important;border:0px !important;}#portal_block_1252 .dxb_bc { margin:0px !important;}#framerU9V5m { margin:0px !important;border:0px !important;}#portal_block_1253 { margin:0px !important;border:0px !important;}#portal_block_1253 .dxb_bc { margin:0px !important;}#frameRCK99J { margin:10px 0px 5px !important;}#frameJ7YGtB { margin:0px !important;border:0px !important;}#portal_block_1255 { margin:0px !important;border:0px !important;}#portal_block_1255 .dxb_bc { margin:0px !important;}#framerVqc7m { margin:0px !important;border:0px !important;}#portal_block_1256 { margin:0px !important;border:0px !important;}#portal_block_1256 .dxb_bc { margin:0px !important;}#frameFW5eQe { margin:0px !important;border:0px !important;}#frameKBtrA1 { margin:0px !important;border:0px !important;}#portal_block_1257 { margin:0px !important;border:0px !important;}#portal_block_1257 .dxb_bc { margin:0px !important;}#portal_block_1258 { margin:0px !important;border:0px !important;}#portal_block_1258 .dxb_bc { margin:0px !important;} </code></pre> <p>and</p> <pre><code>function succeedhandle_followmod(url, msg, values) { var fObj = $(\'followmod_\'+values[\'fuid\']); if(values[\'type\'] == \'add\') { fObj.innerHTML = \***\'; fObj.href = \'home.php?mod=spacecp&amp;amp;ac=follow&amp;amp;op=del&amp;amp;fuid=\'+values[\'fuid\']; } else if(values[\'type\'] == \'del\') { fObj.innerHTML = \***\'; fObj.href = \'home.php?mod=spacecp&amp;amp;ac=follow&amp;amp;op=add&amp;amp;hash=6a62d013&amp;amp;fuid=\'+values[\'fuid\']; } } _***(null, $C("t_f", null, "td"), "", "***", "***"); var rel_tid = "2474591"; var rel_title = "%C9%BD%B6%AB%CA%AF%BB%AF%BE%AD%C0%ED%B7%EB%B6%AB%C7%E0%B4%FE%B2%B6%EE%BF%D1%BA%C6%DA%BC%E4%CB%C0%CD%F6%A1%AA%A1%AA%CA%C7%B7%F1%B1%BB%C9%BD%B6%AB%CA%A1%BC%EC%B2%EC%D4%BA%BC%EC%B2%EC%B3%A4%CE%E2%C5%F4%B7%C9%C3%F0%BF%DA"; var rel_reltid = "0"; var rel_prepos = ""; var my_siteid = "7149150"; var rel_uid = "0"; var rel_views = "3909"; var rel_replies = "11"; var rel_page = "1"; var rel_show = "0"; _attachEvent(window, \'load\', getForbiddenFormula, document); function getForbiddenFormula() { var toGetForbiddenFormulaFIds = function () { ajaxget(\'plugin.php?id=cloudsearch&amp;amp;formhash=6a62d013\'); }; var a = document.body.getElementsByTagName(\'a\'); for(var i = 0;i document.documentElement.clientWidth) { $(\'***').style.cssFloat = \'right\'; $(\'***').style.left = \'auto\'; $(\'***\').style.right = 0; } else { $(\'***\').style.cssFloat = \'left\'; $(\'***\').style.left = (qrleft) + \'px\'; $(\'***\').style.right = \'auto\'; } } _attachEvent(window, \'scroll\', function () { ***; }) _attachEvent(window, \'load\', function() { ***; }, document); #scrolltop { display: none; } ul#navmenu ul { display: none; position: absolute; left: -233px; bottom: 5px; } ul#navmenu li:hover ul ul, ul#navmenu li.iehover ul ul, { display: none; } ul#navmenu li:hover ul, ul#navmenu ul li:hover ul, ul#navmenu ul ul li:hover ul, ul#navmenu li.iehover ul, ul#navmenu ul li.iehover ul, ul#navmenu ul ul li.iehover ul { display: block; } #jz52top a {margin: 6px 0;} #jz52top { visibility: visible; right: 10px; } #jz52topa { visibility: hidden;} #jz52top, #jz52top a { border: none;} #jz52top { position: fixed; bottom: 40px; display: block; width: 40px; background: none repeat scroll 0% 0% transparent; border: 0px #cdcdcd solid; border-radius: 3px; border-top: 0; cursor: pointer; } #jz52top:hover { text-decoration: none; } #jz52top a { display: block; width: 40px; height: 40px; padding: 0; line-height: 12px; text-align: center; color: #787878; text-decoration: none; background: #00a398 url(\'source/plugin/jz52_top/template/jz52top.png\') no-repeat 0 0; border-top: 0px #cdcdcd solid; } a.jz52topa:hover { background-position: -40px 0px !important;} a.replyfast { background-position: 0 -40px !important; } a.replyfast:hover { background-position: -40px -40px !important;} a.returnlist { background-position: 0 -80px !important; } a.returnlist:hover { background-position: -40px -80px !important;} a.returnboard { background-position: -80px -240px !important; } a.returnboard:hover { background-position: -120px -240px !important;} a.jzqr { background-position: 0 -120px !important; } a.jzqr:hover { background-position: -40px -120px !important;} a.jzwx { background-position: 0 -320px !important; } a.jzwx:hover { background-position: -40px -320px !important;} a.jzkf { background-position: -80px 0px !important; } a.jzkf:hover { background-position: -120px -0px !important;} a.jzfx { background-position: -80px -40px !important; } a.jzfx:hover { background-position: -120px -40px !important;} .jzfxn { background: #fff !important; width: 231px !important; height: 260px !important; } a.jzlast { background-position: -80px -80px !important; } a.jzlast:hover { background-position: -120px -80px !important;} a.jznext { background-position: -80px -120px !important; } a.jznext:hover { background-position: -120px -120px !important;} a.jzsct { background-position: 0px -160px !important; } a.jzsct:hover { background-position: -40px -160px !important;} a.jzscb { background-position: -80px -160px !important; } a.jzscb:hover { background-position: -120px -160px !important;} a.jzqqq { background-position: 0px -200px !important; } a.jzqqq:hover { background-position: -40px -200px !important;} a.jzwo { background-position: -80px -200px !important; } a.jzwo:hover { background-position: -120px -200px !important;} a.jzzdy { background-position: 0px -240px !important; } a.jzzdy:hover { background-position: -40px -240px !important;} a.jzfbzt { background-position: 0px -280px !important; } a.jzfbzt:hover { background-position: -40px -280px !important;} #jzqrn { background: #fff !important; width: 231px !important; height: 260px !important; } #jzqrn { border: 1px solid rgb(210, 210, 210); } #jzqrn p { font-size: 15px; padding-bottom: 15px; text-align: center; color: #999; font-family: Microsoft YaHei; } #jzwon { background: #fff !important; width: 231px !important; height: 260px !important; } #jzwon { border: 1px solid rgb(210, 210, 210); } #jzfxn { border: 1px solid rgb(210, 210, 210); } #jzfxn h3 { height: 23px; background: none repeat scroll 0% 0% rgb(250, 250, 250); border-bottom: 1px solid rgb(236, 236, 236); padding: 10px 0px 0px 10px; } #jzfxn .bdsharebuttonbox { padding: 13px 0px 0px 20px; } #jzfxn .bdsharebuttonbox a, #jzfxn .bdsharebuttonbox .bds_more { float: left; font-size: 12px; padding-left: 25px; line-height: 16px; text-align: left; height: 16px; background: url("***") no-repeat scroll 0px 0px ; background-repeat: no-repeat; cursor: pointer; margin: 6px 6px 6px 0px; text-indent: 0; overflow: hidden; width: 68px; } #jzfxn .bdsharebuttonbox .bds_qzone { background-position: 0px -52px !important; } #jzfxn .bdsharebuttonbox .bds_tsina { background-position: 0px -104px !important; } #jzfxn .bdsharebuttonbox .bds_tqq { background-position: 0px -260px !important; } #jzfxn .bdsharebuttonbox .bds_renren { background-position: 0px -208px !important; } #jzfxn .bdsharebuttonbox .bds_tqf { background-position: 0px -364px !important; } #jzfxn .bdsharebuttonbox .bds_tieba { background-position: 0px -728px !important; } #jzfxn .bdsharebuttonbox .bds_sqq { background-position: 0px -2652px !important; } #jzfxn .bdsharebuttonbox .bds_hi { background-position: 0px -416px !important; } #jzfxn .bdsharebuttonbox .bds_isohu { background-position: 0px -3016px !important; } #jzfxn .bdsharebuttonbox .bds_weixin { background-position: 0px -1612px !important; } #jzfxn .bdsharebuttonbox .bds_t163 { background-position: 0px -832px !important; } #jzfxn .bdsharebuttonbox .bds_tsohu { background-position: 0px -520px !important; } #jzfxn .bdsharebuttonbox .bds_baidu { background-position: 0px -2600px !important; } #jzfxn .bdsharebuttonbox .bds_qq { background-position: 0px -624px !important; } #jz52top a b { visibility: hidden; font-weight: normal; } // JavaScript Document function goTopEx(){ var obj=document.getElementById("goTopBtn"); function getScrollTop(){ return document.documentElement.scrollTop || document.body.scrollTop; } function setScrollTop(value){ if(document.documentElement.scrollTop){ document.documentElement.scrollTop=value; }else{ document.body.scrollTop=value; } } window.onscroll=function(){getScrollTop()&amp;gt;0?obj.style.display="":obj.style.display="none"; var h=document.body.scrollHeight - getScrollTop() - obj.offsetTop - obj.offsetHeight; obj.style.bottom=0+"px"; </code></pre> <p>Any idea how to get rid of all of that?</p>
1
2016-09-19T02:12:12Z
39,564,596
<p>My mistake, it was a typo in my code, but thanks for the hint! Correct code:</p> <pre><code>from lxml.html.clean import Cleaner import lxml.html as html text = html.document_fromstring(r.text) cleaner = Cleaner(kill_tags=['script', 'noscript', 'img', 'a', 'h1'], remove_tags=['p'], style=True) cleaner(text) text = text.text_content() text = ' '.join(text.split()) </code></pre>
0
2016-09-19T02:33:37Z
[ "javascript", "python" ]
How do I run an method async inside a class that is being used with asyncio.create_server?
39,564,565
<p>I'm using autobahn with asyncio and I'm trying to make a method inside a class that extends WebSocketServerFactory run every x seconds.</p> <p>This is how the documentation on the autobahn website does it:</p> <pre><code>from autobahn.asyncio.websocket import WebSocketServerFactory factory = WebSocketServerFactory() factory.protocol = MyServerProtocol loop = asyncio.get_event_loop() coro = loop.create_server(factory, '127.0.0.1', 9000) server = loop.run_until_complete(coro) </code></pre> <p>I have simply replaced the WebSocketServerFactory class with a class that extends it, and I want to run a method inside it every x seconds.</p> <p>I found an example of this on the autobahn website, but it uses twisted and not asyncio.</p> <p>Here is an short example(<a href="https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/broadcast/server.py" rel="nofollow">original and full version</a>) of what I want, but the example uses twisted:</p> <pre><code>class CustomServerFactory(WebSocketServerFactory): def __init__(self, url): WebSocketServerFactory.__init__(self, url) self.tick() def tick(self): print("tick!") self.do_something() reactor.callLater(1, self.tick) </code></pre> <p>How can I achive the same thing using asyncio?</p>
0
2016-09-19T02:29:21Z
39,566,070
<p>Based on your example, the same functionality with asyncio can be done using the asyncio event loop: <a href="https://docs.python.org/3/library/asyncio-eventloop.html#delayed-calls" rel="nofollow">Asyncio delayed calls</a>.</p> <p>So in your example that would mean something like this:</p> <pre><code>def tick(self): print("tick!") self.do_something() loop.call_later(1, self.tick) </code></pre> <p>where loop is the asyncio event loop variable you create earlier in:</p> <pre><code>loop = asyncio.get_event_loop() </code></pre>
2
2016-09-19T05:42:07Z
[ "python", "python-asyncio", "autobahn" ]
PyQt/PySide Get Decimal Place of selected value in QSpinBOX
39,564,574
<p>How to query Decimal Place of selected value in QSpinBox(PyQt) ?</p> <p>Let say QSpinBox contain value 631.1205 and user select 3 then answer should be tens.(i.e 6=Hundreds, 3=Tens, 1=Ones, 1=Tenths, 2=Hundredths, 0=Thousandths, 5=Ten-Thousandths).</p>
0
2016-09-19T02:30:17Z
39,584,802
<p>Let's assume you have two lists that contain the text you want to return (expand beyond thousand*s if appropriate for your use case): big = ['Ones', 'Tens', Hundreds', 'Thousands'] small = ['Tenths', 'Hundredths', 'Thousandths'] </p> <p>First you need to get a reference to the <code>QLineEdit</code> in the <code>QSpinBox</code> with:</p> <pre><code>line_edit = spinBox.findChild(QLineEdit) </code></pre> <p>Then find the index of where the selection starts:</p> <pre><code>selectionStart = line_edit.selectionStart() </code></pre> <p>Next find the index of the decimal point:</p> <pre><code>try: decimalPoint = str(line_edit.text()).index('.') except ValueError: # no decimal point found so assume the number is an integer decimalPoint = len(str(line_edit.text())) </code></pre> <p>Then work out what you need to return:</p> <pre><code># If something is selected if selectionStart &gt; -1: # if we have selected text starting on the left of the decimal if selectionStart &lt; decimalPoint: return big[decimalPoint-selectionStart-1] # else we selected text starting on the right of the decimal else: return small[selectionStart-decimalPoint-1] </code></pre> <p>I'd recommend putting this in a function and calling it when appropriate as I have no context of what you are trying to do!</p>
0
2016-09-20T02:27:00Z
[ "python", "pyqt", "pyside" ]
Beautiful soup: Insert HTML5 Tag between two paragraphs
39,564,687
<p>I want to automate the insertion of a html tag between two paragraphs for thousand of similar pages. The snippet is something like this (the new tag must be inserted after the paragraph of header class) :</p> <pre><code>&lt;p align="center"&gt;&lt;span class="header"&gt;My Title&lt;/span&gt;&lt;/p&gt; {insert new tag &lt;article&gt; here} &lt;p align="center"&gt;bla-bla-bla&lt;/p&gt; </code></pre> <p>I am using Python and Beautiful soup. My difficulty is to locate the place to insert and how to insert between two paragraphs. Here is my code that so far did not work well yet. Any help?</p> <pre><code>soup = BeautifulSoup(page, 'html.parser') cells = soup.findAll('p', attrs={"class":"header"}) index=str(cells).index('&lt;/p&gt;&lt;p&gt;') # search location between two paragraphs output_line = cells[:index] + '&lt;article&gt; ' + cells[index:] </code></pre>
0
2016-09-19T02:50:37Z
39,565,038
<p>Try this:</p> <pre><code>soup = BeautifulSoup(page, 'html.parser') p = soup.find('span', {'class': 'header'}).parent p.insert_after(soup.new_tag('article')) </code></pre> <p>A quick look at the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup documentation</a> yields lots of useful helper methods for these sort of things.</p>
0
2016-09-19T03:44:35Z
[ "python", "html", "soap" ]
Beautiful soup: Insert HTML5 Tag between two paragraphs
39,564,687
<p>I want to automate the insertion of a html tag between two paragraphs for thousand of similar pages. The snippet is something like this (the new tag must be inserted after the paragraph of header class) :</p> <pre><code>&lt;p align="center"&gt;&lt;span class="header"&gt;My Title&lt;/span&gt;&lt;/p&gt; {insert new tag &lt;article&gt; here} &lt;p align="center"&gt;bla-bla-bla&lt;/p&gt; </code></pre> <p>I am using Python and Beautiful soup. My difficulty is to locate the place to insert and how to insert between two paragraphs. Here is my code that so far did not work well yet. Any help?</p> <pre><code>soup = BeautifulSoup(page, 'html.parser') cells = soup.findAll('p', attrs={"class":"header"}) index=str(cells).index('&lt;/p&gt;&lt;p&gt;') # search location between two paragraphs output_line = cells[:index] + '&lt;article&gt; ' + cells[index:] </code></pre>
0
2016-09-19T02:50:37Z
39,565,075
<p>Wow, as the core code is showed by Trombone.I'd like to give a more complete demo.</p> <pre><code>from bs4 import BeautifulSoup page = """ &lt;p align="center"&gt;&lt;span class="header"&gt;My Title1&lt;/span&gt;&lt;/p&gt; &lt;p align="center"&gt;bla-bla-bla&lt;/p&gt; &lt;p align="center"&gt;&lt;span class="header"&gt;My Title2&lt;/span&gt;&lt;/p&gt; &lt;p align="center"&gt;bla-bla-bla&lt;/p&gt; &lt;p align="center"&gt;&lt;span class="header"&gt;My Title3&lt;/span&gt;&lt;/p&gt; &lt;p align="center"&gt;bla-bla-bla&lt;/p&gt; """ soup = BeautifulSoup(page, "html.parser") for header in soup.find_all('span', class_='header'): article = soup.new_tag('article') article.string = 'article content' header.insert_after(article) print soup.prettify() </code></pre> <p>OUTPUT:</p> <pre><code>&lt;p align="center"&gt; &lt;span class="header"&gt; My Title1 &lt;/span&gt; &lt;/p&gt; &lt;article&gt; article content &lt;/article&gt; &lt;p align="center"&gt; bla-bla-bla &lt;/p&gt; &lt;p align="center"&gt; &lt;span class="header"&gt; My Title2 &lt;/span&gt; &lt;/p&gt; &lt;article&gt; article content &lt;/article&gt; &lt;p align="center"&gt; bla-bla-bla &lt;/p&gt; &lt;p align="center"&gt; &lt;span class="header"&gt; My Title3 &lt;/span&gt; &lt;/p&gt; &lt;article&gt; article content &lt;/article&gt; &lt;p align="center"&gt; bla-bla-bla &lt;/p&gt; </code></pre>
0
2016-09-19T03:50:22Z
[ "python", "html", "soap" ]
How to modify .split function to to apply to different alpha numeric inputs?
39,564,741
<p>I have the following two types of input:</p> <pre><code>## Case 1 (a) # Input #1(a) &gt;qrst ABC 10 9 7 &gt;qqqq ACC 2 5 3 # Case 1 (b) --&gt; Simplified form of Case 1(a) # Input #1() &gt;qrst A 10 &gt;qqqq A 2 # After reading in the file and making it a list I store the above in l l = ['ABC 10 9 7', 'ACC 2 5 3'] # Case 1(a) l = ['A 10', 'A 2'] # Case 1(b) #In the following code I split the alpha-numeric elements above and #create separate lists where I store the alphabets alone (in list "sequences") and #numeric alone (in list "qualities") ll = len(l) all_inputs = [] for i in range(0,ll): sq = l[i] sequence = sq.split(" ")[0] ## Stores only the alphabets qualities = sq.split(" ")[1:] ## Stores only the numeric qualities = filter(None, qualities) for sub in sequence: if sub == "-": idx = list(sequence).index(sub) qualities.insert(idx,"0") all_inputs.append((sequence, qualities)) print #Case1(a) Output reads currently reads as A #print sequence ['2'] #print qualities </code></pre> <p>I encounter another type of input file as follows:</p> <pre><code>## Case 2 # Input #2 &gt;qrst A #No space after A 10 &gt;qqqq A #No space after A 2 Here l = ['A10', 'A2'] I use the same code as above #Case2 Output reads currently reads as A2 #print sequences [] #print qualities </code></pre> <p>I need #Case 2 to also have the output A #print sequence ['2'] #print qualities</p> <p>How do I modify the code above such that it can accommodate both ['ABC 10 9 7', 'ACC 2 5 3'] or ['A 10','A 2'] or['A10','A2'] types of input file/ 'l'? I need Case 2 to have the same output as Case 1(b), so that I can apply the same line of code later on. But remember, it has to be a generalized code for Case 1 and Case 2. </p>
0
2016-09-19T03:00:07Z
39,565,248
<p>A regex would be a good approach for this, you're looking for a letter <code>([A-Z])</code> followed by an optional space <code>?</code> followed by one or more digits <code>(\d+)</code>:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.match('([A-Z]) ?(\d+)', 'A10').groups() ('A', '10') &gt;&gt;&gt; re.match('([A-Z]) ?(\d+)', 'A 10').groups() ('A', '10') </code></pre>
0
2016-09-19T04:12:20Z
[ "python", "split", "alphanumeric" ]
How to modify .split function to to apply to different alpha numeric inputs?
39,564,741
<p>I have the following two types of input:</p> <pre><code>## Case 1 (a) # Input #1(a) &gt;qrst ABC 10 9 7 &gt;qqqq ACC 2 5 3 # Case 1 (b) --&gt; Simplified form of Case 1(a) # Input #1() &gt;qrst A 10 &gt;qqqq A 2 # After reading in the file and making it a list I store the above in l l = ['ABC 10 9 7', 'ACC 2 5 3'] # Case 1(a) l = ['A 10', 'A 2'] # Case 1(b) #In the following code I split the alpha-numeric elements above and #create separate lists where I store the alphabets alone (in list "sequences") and #numeric alone (in list "qualities") ll = len(l) all_inputs = [] for i in range(0,ll): sq = l[i] sequence = sq.split(" ")[0] ## Stores only the alphabets qualities = sq.split(" ")[1:] ## Stores only the numeric qualities = filter(None, qualities) for sub in sequence: if sub == "-": idx = list(sequence).index(sub) qualities.insert(idx,"0") all_inputs.append((sequence, qualities)) print #Case1(a) Output reads currently reads as A #print sequence ['2'] #print qualities </code></pre> <p>I encounter another type of input file as follows:</p> <pre><code>## Case 2 # Input #2 &gt;qrst A #No space after A 10 &gt;qqqq A #No space after A 2 Here l = ['A10', 'A2'] I use the same code as above #Case2 Output reads currently reads as A2 #print sequences [] #print qualities </code></pre> <p>I need #Case 2 to also have the output A #print sequence ['2'] #print qualities</p> <p>How do I modify the code above such that it can accommodate both ['ABC 10 9 7', 'ACC 2 5 3'] or ['A 10','A 2'] or['A10','A2'] types of input file/ 'l'? I need Case 2 to have the same output as Case 1(b), so that I can apply the same line of code later on. But remember, it has to be a generalized code for Case 1 and Case 2. </p>
0
2016-09-19T03:00:07Z
39,565,997
<p>would this work:</p> <pre><code>import re input_seq = "A10 B 20 C30 D1 Z 67" input_raw = re.split(r'([A-Z]) *(\d+)' , input_seq) input_clean = [x for x in input_raw if x and not x.isspace()] print zip(input_clean[::2], input_clean[1::2]) </code></pre> <p><em>gives</em>:</p> <pre><code>[('A', '10'), ('B', '20'), ('C', '30'), ('D', '1'), ('Z', '67')] </code></pre> <p>if you change the last expression:</p> <pre><code>print [ "{} {}".format(*x) for x in zip(input_clean[::2], input_clean[1::2]) ] </code></pre> <p>you get:</p> <pre><code>['A 10', 'B 20', 'C 30', 'D 1', 'Z 67'] </code></pre> <p>alternatively, you can try normalizing the input:</p> <pre><code>input_seq = "A10 B 20 C30 D1 Z 67" print re.sub(r'([A-Z]) *(\d+)', r'\1 \2', input_seq) </code></pre> <p>this will print:</p> <pre><code>A 10 B 20 C 30 D 1 Z 67 </code></pre> <p>if you only want to modify the list of inputs:</p> <pre><code>l = ['A10', 'A2'] l = [ re.sub(r'([A-Z]) *(\d+)', r'\1 \2', x) for x in l] print l </code></pre> <p>this prints:</p> <pre><code>['A 10', 'A 2'] </code></pre>
0
2016-09-19T05:34:08Z
[ "python", "split", "alphanumeric" ]
Python 3.5.1, the global variable is not destroyed when delete the module
39,564,909
<p>I have a app loading python35.dll. Use python API PyImport_AddModule to run a py file. And use PyDict_DelItemString to delete the module. There is a global vailable in the py file. The global variable is not destroyed when calling PyDict_DelItemString to delete the module. The global variable is destroyed when calling Py_Finalize. It's too late. That cause the memory leak. Because the Py_Initialize is called at the app startup, the Py_Finalize is called at the app shutdown. </p> <p>But it is ok with python33.dll, the global variable can be destroyed when calling PyDict_DelItemString to delete the module.</p> <p>How to resolve the problem? Is there a workaround? I need to use python35.dll and wish the global variable in a module can be released automatically when call PyDict_DelItemString to delete the module.</p> <p>Here is the python test code:</p> <pre><code>class Simple: def __init__( self ): print('Simple__init__') def __del__( self ): print('Simple__del__') simple = Simple() </code></pre>
2
2016-09-19T03:25:15Z
39,628,866
<p>This problem is resolved. Need to call PyGC_Collect after PyDict_DelItemString with Python post 3.4 versions.</p> <p>For detailed info, please read <a href="http://bugs.python.org/issue28202" rel="nofollow">http://bugs.python.org/issue28202</a>.</p>
0
2016-09-22T01:28:19Z
[ "python", "python-3.x", "pyobject" ]
MODBUS RTU CRC16 calculation
39,564,916
<p>I'm coding a MODBUS CRC16 calculator in C. What I have before is a python that do this, I wanted to convert it to C. I found some codes online but it's not giving me the correct answer.</p> <p>For my python code, I have this as my CRC16.py</p> <pre><code>#!/usr/bin/env python def calc(data): crc_table=[0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,0xC601,0x06C0,0x0780,0xC741,0x0500,0xC5C1,0xC481,0x0440,0xCC01,0x0CC0,0x0D80,0xCD41,0x0F00,0xCFC1,0xCE81,0x0E40,0x0A00,0xCAC1,0xCB81,0x0B40,0xC901,0x09C0,0x0880,0xC841,0xD801,0x18C0,0x1980,0xD941,0x1B00,0xDBC1,0xDA81,0x1A40,0x1E00,0xDEC1,0xDF81,0x1F40,0xDD01,0x1DC0,0x1C80,0xDC41,0x1400,0xD4C1,0xD581,0x1540,0xD701,0x17C0,0x1680,0xD641,0xD201,0x12C0,0x1380,0xD341,0x1100,0xD1C1,0xD081,0x1040,0xF001,0x30C0,0x3180,0xF141,0x3300,0xF3C1,0xF281,0x3240,0x3600,0xF6C1,0xF781,0x3740,0xF501,0x35C0,0x3480,0xF441,0x3C00,0xFCC1,0xFD81,0x3D40,0xFF01,0x3FC0,0x3E80,0xFE41,0xFA01,0x3AC0,0x3B80,0xFB41,0x3900,0xF9C1,0xF881,0x3840,0x2800,0xE8C1,0xE981,0x2940,0xEB01,0x2BC0,0x2A80,0xEA41,0xEE01,0x2EC0,0x2F80,0xEF41,0x2D00,0xEDC1,0xEC81,0x2C40,0xE401,0x24C0,0x2580,0xE541,0x2700,0xE7C1,0xE681,0x2640,0x2200,0xE2C1,0xE381,0x2340,0xE101,0x21C0,0x2080,0xE041,0xA001,0x60C0,0x6180,0xA141,0x6300,0xA3C1,0xA281,0x6240,0x6600,0xA6C1,0xA781,0x6740,0xA501,0x65C0,0x6480,0xA441,0x6C00,0xACC1,0xAD81,0x6D40,0xAF01,0x6FC0,0x6E80,0xAE41,0xAA01,0x6AC0,0x6B80,0xAB41,0x6900,0xA9C1,0xA881,0x6840,0x7800,0xB8C1,0xB981,0x7940,0xBB01,0x7BC0,0x7A80,0xBA41,0xBE01,0x7EC0,0x7F80,0xBF41,0x7D00,0xBDC1,0xBC81,0x7C40,0xB401,0x74C0,0x7580,0xB541,0x7700,0xB7C1,0xB681,0x7640,0x7200,0xB2C1,0xB381,0x7340,0xB101,0x71C0,0x7080,0xB041,0x5000,0x90C1,0x9181,0x5140,0x9301,0x53C0,0x5280,0x9241,0x9601,0x56C0,0x5780,0x9741,0x5500,0x95C1,0x9481,0x5440,0x9C01,0x5CC0,0x5D80,0x9D41,0x5F00,0x9FC1,0x9E81,0x5E40,0x5A00,0x9AC1,0x9B81,0x5B40,0x9901,0x59C0,0x5880,0x9841,0x8801,0x48C0,0x4980,0x8941,0x4B00,0x8BC1,0x8A81,0x4A40,0x4E00,0x8EC1,0x8F81,0x4F40,0x8D01,0x4DC0,0x4C80,0x8C41,0x4400,0x84C1,0x8581,0x4540,0x8701,0x47C0,0x4680,0x8641,0x8201,0x42C0,0x4380,0x8341,0x4100,0x81C1,0x8081,0x4040] crc_hi=0xFF crc_lo=0xFF for w in data: index=crc_lo ^ ord(w) crc_val=crc_table[index] crc_temp=crc_val/256 crc_val_low=crc_val-(crc_temp*256) crc_lo=crc_val_low ^ crc_hi crc_hi=crc_temp crc=crc_hi*256 +crc_lo return crc </code></pre> <p>Next, I'll use a script to input my variables:</p> <pre><code>import math import subprocess import serial import time from time import sleep import struct import CRC16 import sys address = chr(0x01) function_code = chr(0x04) start_at_reg = chr(0x10) + chr(0x06) num_of_reg = chr(0x00) + chr(0x02) read_device = address + function_code + start_at_reg + num_of_reg crc = CRC16.calc(read_device) crc_hi = crc/256 crc_lo = crc &amp; 0xFF print "meter add: " +str(ord(address)) print "crc_lo: " +str(hex(crc_lo)) print "crc_hi: " +str(hex(crc_hi)) </code></pre> <p>This will give me:</p> <pre><code>&gt;&gt; meter add: 1 crc_lo: 0x95 crc_hi: 0xa </code></pre> <p>Now, I found this C code online that to calculate CRC16:</p> <pre><code>WORD CRC16 (const BYTE *nData, WORD wLength) { static const WORD wCRCTable[] = {0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,0xC601,0x06C0,0x0780,0xC741,0x0500,0xC5C1,0xC481,0x0440,0xCC01,0x0CC0,0x0D80,0xCD41,0x0F00,0xCFC1,0xCE81,0x0E40,0x0A00,0xCAC1,0xCB81,0x0B40,0xC901,0x09C0,0x0880,0xC841,0xD801,0x18C0,0x1980,0xD941,0x1B00,0xDBC1,0xDA81,0x1A40,0x1E00,0xDEC1,0xDF81,0x1F40,0xDD01,0x1DC0,0x1C80,0xDC41,0x1400,0xD4C1,0xD581,0x1540,0xD701,0x17C0,0x1680,0xD641,0xD201,0x12C0,0x1380,0xD341,0x1100,0xD1C1,0xD081,0x1040,0xF001,0x30C0,0x3180,0xF141,0x3300,0xF3C1,0xF281,0x3240,0x3600,0xF6C1,0xF781,0x3740,0xF501,0x35C0,0x3480,0xF441,0x3C00,0xFCC1,0xFD81,0x3D40,0xFF01,0x3FC0,0x3E80,0xFE41,0xFA01,0x3AC0,0x3B80,0xFB41,0x3900,0xF9C1,0xF881,0x3840,0x2800,0xE8C1,0xE981,0x2940,0xEB01,0x2BC0,0x2A80,0xEA41,0xEE01,0x2EC0,0x2F80,0xEF41,0x2D00,0xEDC1,0xEC81,0x2C40,0xE401,0x24C0,0x2580,0xE541,0x2700,0xE7C1,0xE681,0x2640,0x2200,0xE2C1,0xE381,0x2340,0xE101,0x21C0,0x2080,0xE041,0xA001,0x60C0,0x6180,0xA141,0x6300,0xA3C1,0xA281,0x6240,0x6600,0xA6C1,0xA781,0x6740,0xA501,0x65C0,0x6480,0xA441,0x6C00,0xACC1,0xAD81,0x6D40,0xAF01,0x6FC0,0x6E80,0xAE41,0xAA01,0x6AC0,0x6B80,0xAB41,0x6900,0xA9C1,0xA881,0x6840,0x7800,0xB8C1,0xB981,0x7940,0xBB01,0x7BC0,0x7A80,0xBA41,0xBE01,0x7EC0,0x7F80,0xBF41,0x7D00,0xBDC1,0xBC81,0x7C40,0xB401,0x74C0,0x7580,0xB541,0x7700,0xB7C1,0xB681,0x7640,0x7200,0xB2C1,0xB381,0x7340,0xB101,0x71C0,0x7080,0xB041,0x5000,0x90C1,0x9181,0x5140,0x9301,0x53C0,0x5280,0x9241,0x9601,0x56C0,0x5780,0x9741,0x5500,0x95C1,0x9481,0x5440,0x9C01,0x5CC0,0x5D80,0x9D41,0x5F00,0x9FC1,0x9E81,0x5E40,0x5A00,0x9AC1,0x9B81,0x5B40,0x9901,0x59C0,0x5880,0x9841,0x8801,0x48C0,0x4980,0x8941,0x4B00,0x8BC1,0x8A81,0x4A40,0x4E00,0x8EC1,0x8F81,0x4F40,0x8D01,0x4DC0,0x4C80,0x8C41,0x4400,0x84C1,0x8581,0x4540,0x8701,0x47C0,0x4680,0x8641,0x8201,0x42C0,0x4380,0x8341,0x4100,0x81C1,0x8081,0x4040}; BYTE nTemp; WORD wCRCWord = 0xFFFF; while (wLength--) { nTemp = *nData++ ^ wCRCWord; wCRCWord &gt;&gt;= 8; wCRCWord ^= wCRCTable[nTemp]; } return wCRCWord; } </code></pre> <p>I saved that code as header file, "CRC.h". So I can input the data that I have:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; #include &lt;errno.h&gt; #include &lt;termios.h&gt; #include &lt;stdint.h&gt; #include &lt;inttypes.h&gt; #include &lt;stdlib.h&gt; #ifdef WIN32 /*windows stuff*/ #else typedef unsigned long WORD; typedef unsigned char BYTE; #endif #include "CRC.h" int main(){ char query_m[6]; char add = 0x01; char fnc_code = 0x04; char reg_hi = 0x10; char reg_lo = 0x06; char num_hi = 0x00; char num_lo = 0x02; query_m[0] = add; query_m[1] = fnc_code; query_m[2] = reg_hi; query_m[3] = reg_lo; query_m[4] = num_hi; query_m [5] = num_lo; int i; for(i=0;i&lt;7; i++){ printf("this is query_m[%d]: %d\n", i, query_m[i]); } int size_m = 7; char crc_data; crc_data = CRC16(query_m, sizeof(query_m)); printf("this is CRC: %d\n", crc_data); return 0; } </code></pre> <p>This gives me a value of -107. I'm relatively new to C, and I'm still doing some experiments on this</p> <p>Thank you.</p>
0
2016-09-19T03:25:54Z
39,566,555
<ul> <li><p><code>WORD</code> should be <code>unsigned short</code> (2 bytes), not <code>unsigned long</code> (4 or 8 bytes depended on platform)</p> <pre><code>typedef unsigned short WORD; </code></pre></li> <li><p>As @paddy said, loop from 0 to 6 in the for loop:</p> <pre><code>for (i=0; i&lt;6; i++) { ... } </code></pre></li> <li><p><code>crc_data</code> should be of type <code>WORD</code>, not <code>char</code></p> <pre><code>WORD crc_data; </code></pre></li> <li><p>use <code>%04x</code> in last <code>printf()</code></p> <pre><code>printf("this is CRC: %04x\n", crc_data); </code></pre></li> </ul>
1
2016-09-19T06:21:16Z
[ "python", "c", "checksum", "modbus", "crc16" ]
Return Pandas DataFrame references/names to a list?
39,564,956
<p>I've defined a function that cleans a data frame and returns a new dataframe. I have many data frames that I want to run this function on. I had a list of my DFs, <code>namelist=[a,b,c]</code> and passed them in a loop through my function. I want to return a similar list, <code>cleanDFs=[aClean, bClean, cClean]</code>. I tried to do this like so:</p> <pre><code>for i in range(0, len(Names)): c = dataCleaning(catDFs[i]) cleanDFs.append(pd.DataFrame(c)) </code></pre> <p>However, this makes <code>cleanDFs</code> be a list of the <em>contents</em> of each data frame, not a list of names. How can I accomplish what I'm trying to do?</p>
0
2016-09-19T03:32:41Z
39,565,351
<p>I'd do</p> <pre><code>cleadDFs = [dataCleaning(d) for d in catDFs] </code></pre>
0
2016-09-19T04:26:10Z
[ "python", "pandas" ]
How to install Python 2.7.10 installation without root/sudo permission and internet connection?
39,564,982
<p>I have been trying to install Python 2.7.10 along with more than 15 supporting packages in the following environment.</p> <pre><code>LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch Red Hat Enterprise Linux Server release 6.4 (Santiago) Red Hat Enterprise Linux Server release 6.4 (Santiago) </code></pre> <p>But I don't have root root, sudo permission. I don't even have internet connection on that. I can only copy the package files from Windows to Linux machine. And then I have to install everything.</p> <p>Can anyone help me complete this task?</p>
1
2016-09-19T03:36:08Z
39,565,060
<p>Use <a href="http://conda.pydata.org/miniconda.html" rel="nofollow">miniconda</a> to install a standalone python. Then create environments as needed using the miniconda tool (conda).</p> <p>See <a href="http://stackoverflow.com/a/19170873/3586654">this answer</a> for example usage. </p> <p>If you already have a python installed (maybe the system python), you can skip downloading miniconda and use <a href="https://virtualenv.pypa.io/en/stable/installation/" rel="nofollow">virtualenv</a> to create standalone environments instead.</p> <p>You can then use <code>pip</code> to install the packages that you need.</p>
1
2016-09-19T03:47:47Z
[ "python" ]
URL template tag causing NoReverseMatch when URL name from an include is used
39,565,046
<p>With the following definitions:</p> <p><strong>urls.py</strong></p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), # Homepage url(r'^$', projects.homepage, name='homepage'), url(r'^create_new_project/$', projects.create_new_project), # Project page url(r'^(?P&lt;project_path&gt;\w+)/', include('projects.urls')), ] </code></pre> <p><strong>projects/urls.py</strong></p> <pre><code>from . import views as projects from gpuz import views as gpuz # gpuz as a sample tool from models import views as models urlpatterns = [ url(r'^$', projects.projectpage, name='project-page'), url(r'^gpuz/$', gpuz.page), url(r'^settings/$', models.settings_new), ] </code></pre> <p>I am able to resolve URLs such as <code>localhost/myproject/</code> and <code>localhost/myproject/gpuz/</code> but generating the URLs through templates gives me NoReverseMatch errors.</p> <p>Example:</p> <p><strong>base.html</strong></p> <pre><code>&lt;div class="navbar-collapse collapse "&gt; &lt;ul id="menu-top" class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;a href="{% url 'homepage' %}" class="navbar-btn-home"&gt;Home&lt;/a&gt;&lt;/li&gt; {% if project %} &lt;!-- NoReverseMatch --&gt; &lt;li&gt;&lt;a href="{% url 'project-page' %}"&gt;{{ project.name }}&lt;/a&gt;&lt;/li&gt; {% endif %} {% if project_tools %} {% for tool in project_tools %} &lt;!-- Expected URL: /myproject/gpuz/ --&gt; &lt;li&gt;&lt;a href="{% url 'project-page' tool.name %}" class="navbar-btn-{{tool.name}}"&gt;{{ tool.name }}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;li&gt;&lt;a href="/settings" class="navbar-btn-settings"&gt;Settings&lt;/a&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I am following the example here: <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url</a> but it doesn't seem to be working for me and I can't figure out what's wrong. I am not using <code>reverse()</code> anywhere in my code.</p> <p>Error message:</p> <p><strong>NoReverseMatch</strong></p> <pre><code>{% if project %} &lt;li&gt;&lt;a href="{% url 'project-page' %}"&gt;{{ project.name }}&lt;/a&gt;&lt;/li&gt; {% endif %} Exception Type: NoReverseMatch Exception Value: Reverse for 'project-page' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre> <p><strong>Temporary workaround</strong></p> <p>I've been spending too much time trying to fix this so my current workaround is to chain variables to form a pseudo hard-coded URL e.g. <code>href="/{{ project.url_path }}/{{ tool.name }}/"</code>. </p>
0
2016-09-19T03:46:09Z
39,565,129
<p>Try this:</p> <pre><code>&lt;li&gt;&lt;a href="{% url 'projects:project-page' %}"&gt;{{ project.name }}&lt;/a&gt;&lt;/li&gt; </code></pre>
0
2016-09-19T03:57:20Z
[ "python", "django", "django-urls" ]
URL template tag causing NoReverseMatch when URL name from an include is used
39,565,046
<p>With the following definitions:</p> <p><strong>urls.py</strong></p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), # Homepage url(r'^$', projects.homepage, name='homepage'), url(r'^create_new_project/$', projects.create_new_project), # Project page url(r'^(?P&lt;project_path&gt;\w+)/', include('projects.urls')), ] </code></pre> <p><strong>projects/urls.py</strong></p> <pre><code>from . import views as projects from gpuz import views as gpuz # gpuz as a sample tool from models import views as models urlpatterns = [ url(r'^$', projects.projectpage, name='project-page'), url(r'^gpuz/$', gpuz.page), url(r'^settings/$', models.settings_new), ] </code></pre> <p>I am able to resolve URLs such as <code>localhost/myproject/</code> and <code>localhost/myproject/gpuz/</code> but generating the URLs through templates gives me NoReverseMatch errors.</p> <p>Example:</p> <p><strong>base.html</strong></p> <pre><code>&lt;div class="navbar-collapse collapse "&gt; &lt;ul id="menu-top" class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;a href="{% url 'homepage' %}" class="navbar-btn-home"&gt;Home&lt;/a&gt;&lt;/li&gt; {% if project %} &lt;!-- NoReverseMatch --&gt; &lt;li&gt;&lt;a href="{% url 'project-page' %}"&gt;{{ project.name }}&lt;/a&gt;&lt;/li&gt; {% endif %} {% if project_tools %} {% for tool in project_tools %} &lt;!-- Expected URL: /myproject/gpuz/ --&gt; &lt;li&gt;&lt;a href="{% url 'project-page' tool.name %}" class="navbar-btn-{{tool.name}}"&gt;{{ tool.name }}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;li&gt;&lt;a href="/settings" class="navbar-btn-settings"&gt;Settings&lt;/a&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I am following the example here: <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url</a> but it doesn't seem to be working for me and I can't figure out what's wrong. I am not using <code>reverse()</code> anywhere in my code.</p> <p>Error message:</p> <p><strong>NoReverseMatch</strong></p> <pre><code>{% if project %} &lt;li&gt;&lt;a href="{% url 'project-page' %}"&gt;{{ project.name }}&lt;/a&gt;&lt;/li&gt; {% endif %} Exception Type: NoReverseMatch Exception Value: Reverse for 'project-page' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre> <p><strong>Temporary workaround</strong></p> <p>I've been spending too much time trying to fix this so my current workaround is to chain variables to form a pseudo hard-coded URL e.g. <code>href="/{{ project.url_path }}/{{ tool.name }}/"</code>. </p>
0
2016-09-19T03:46:09Z
39,565,284
<pre><code>url(r'^(?P&lt;project_path&gt;\w+)/', include('projects.urls')) </code></pre> <p>if you put this url in main urls.py you need to pass the project path from the Html page other wise it will raise the exception like no reverse match so right way is </p> <p>Main urls.py</p> <pre><code>url(r'^$', include('projects.urls')), </code></pre> <p>projects urls.py </p> <p>add the project path url ( note: pass the project path from the template like <code>{% url 'project-page' project.path %}</code> )</p>
0
2016-09-19T04:16:49Z
[ "python", "django", "django-urls" ]
Fit regression line to exponential function in python
39,565,073
<p>I am trying to learn how to interpret a linear regression model for an exponential function created with Python. I create a model by first transforming the exponential Y data into a straight line by taking the natural log. I then create a linear model and note the slope and intercept. Lastly, I try to compute a sample value using the slope and intercept. Specifically, I try to compute the Y when X = 1.1. Y should be ~2.14 but my model interpretation produces a Y value of 3.78. </p> <p>Question 1: What am I doing wrong in interpreting the model.</p> <p>Question 2: I have to reshape the X array or I get an error in regr.fit. Why do I have to reshape the X array.</p> <p>The code follows:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model # create some exponential data X = np.arange(1, 10, 0.1) print(X) Y = np.power(2, X) print(Y) # transform the exponential Y data to make it a straight line ln_Y = np.log(Y) # show the exponential plot plt.scatter(X, Y) plt.show() # Create linear regression object regr = linear_model.LinearRegression() # reshape the X to avoid regr.fit errors X = np.reshape(X, (X.size, 1)) # Train the model using the training sets regr.fit(X,ln_Y) # The coefficients print('Slope: \n', regr.coef_) print('Intercept: \n', regr.intercept_) # predict Y when X = 1.1 (should be approximately 2.14354693) # equation = e^(0.00632309*1.1) + 2.7772517886 print("predicted val = ", np.exp(0.00632309*1.1) + 2.7772517886) </code></pre>
0
2016-09-19T03:49:42Z
39,565,148
<p>Make sure you've got the latest version of scikit; I got different coeffiecients to you: </p> <pre><code>Slope: [ 0.69314718] Intercept: 4.4408920985e-16 </code></pre> <p>And you'll need to take the <code>exp</code> of the whole expression, not just the x term:</p> <pre><code>In [17]: np.exp(0.69314718*1.1 + 4.4408920985e-16) Out[17]: 2.1435469237522917 </code></pre>
1
2016-09-19T04:00:13Z
[ "python", "python-3.x", "numpy", "machine-learning", "linear-regression" ]
Scp with subprocess python with a private key
39,565,106
<p>How do i get this scp command converted for python subprocess.</p> <pre><code> scp -i /home/ramesh7128/Downloads/&lt;private_key&gt;.pem /home/ramesh7128/Downloads/testing_transfer.py &lt;remote_add&gt;:&lt;remote_file_path&gt; </code></pre> <p>esp the part to include the private key path is where i am having issues. </p>
0
2016-09-19T03:54:56Z
39,565,158
<p>Make sure you're including the user on the remote machine and that you've formatted things correctly:</p> <pre><code>scp -i /home/ramesh7128/Downloads/&lt;private_key&gt;.pem /home/ramesh7128/Downloads/testing_transfer.py &lt;remote_user&gt;@&lt;remote_add&gt;:&lt;remote_file_path&gt; scp -i private_key.pem /path/to/the/local/file root@server.com:/path/to/the/remote/file </code></pre> <p>EDIT: (from comments)</p> <pre><code>subprocess.Popen(["scp", "-i", "path/to/private_key.pem", myfile, destination]) </code></pre> <p>This syntax lets Popen know about the <code>-i</code> option.</p>
2
2016-09-19T04:00:51Z
[ "python", "django", "subprocess", "scp" ]
How are conditional statements with multiple conditions evaluated?
39,565,195
<p>I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case.</p> <pre><code>if True or False and False: print('True') else: print('False') </code></pre> <p>True is printed</p> <pre><code>if (True or False) and False: print('True') else: print('False') </code></pre> <p>False is printed </p> <p>Here's my breakdown of the logic:</p> <p>True or False => True</p> <p>True and False => False</p> <p>By substitution, (True or False) and False => True and False => False </p> <p>Why does this happen? </p>
1
2016-09-19T04:04:56Z
39,565,216
<p>This is because of <a href="https://docs.python.org/2.7/reference/expressions.html#operator-precedence" rel="nofollow">operator precedence</a>. Per the Python 2.x and 3.x docs, the <code>and</code> operator has higher precedence than the <code>or</code> operator. Also, have a look at the boolean truth table:</p> <p><a href="http://i.stack.imgur.com/nl0W8.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/nl0W8.jpg" alt="enter image description here"></a></p> <p>That means in your expression:</p> <pre><code>if True or False and False: </code></pre> <p>In the expression, <code>False and False</code> is grouped together because of precedence. That means Python evaluates it as:</p> <pre><code>if True or (False and False): </code></pre> <p>Now, it's evaluated left to right. Since the first condition is <code>True</code>, it short-circuits and skips the second condition and evaluates to <code>True</code> printing 'True'. (This short-circuits because if the first side is true, it <em>has to be true</em>.)</p> <p>Now in your second example:</p> <pre><code>if (True or False) and False: </code></pre> <p>This makes <code>True or False</code> evaluate first, which gives <code>True</code>. Then it does <code>True and False</code> which is <code>False</code>, printing 'False'.</p> <pre><code>&gt;&gt;&gt; print(True or False) True &gt;&gt;&gt; print(True and False) False </code></pre>
3
2016-09-19T04:07:53Z
[ "python" ]
How are conditional statements with multiple conditions evaluated?
39,565,195
<p>I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case.</p> <pre><code>if True or False and False: print('True') else: print('False') </code></pre> <p>True is printed</p> <pre><code>if (True or False) and False: print('True') else: print('False') </code></pre> <p>False is printed </p> <p>Here's my breakdown of the logic:</p> <p>True or False => True</p> <p>True and False => False</p> <p>By substitution, (True or False) and False => True and False => False </p> <p>Why does this happen? </p>
1
2016-09-19T04:04:56Z
39,565,234
<p><code>(True or False)</code> evaluates to <code>True</code>. Therefore <code>(True or False) and False</code> evaluates to <code>True and False</code>, which evaluates to <code>False</code>.</p> <p>This answer explains the rules for boolean evaluation quite well: <a href="http://stackoverflow.com/a/16069560/1470749">http://stackoverflow.com/a/16069560/1470749</a></p>
1
2016-09-19T04:09:42Z
[ "python" ]
How are conditional statements with multiple conditions evaluated?
39,565,195
<p>I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case.</p> <pre><code>if True or False and False: print('True') else: print('False') </code></pre> <p>True is printed</p> <pre><code>if (True or False) and False: print('True') else: print('False') </code></pre> <p>False is printed </p> <p>Here's my breakdown of the logic:</p> <p>True or False => True</p> <p>True and False => False</p> <p>By substitution, (True or False) and False => True and False => False </p> <p>Why does this happen? </p>
1
2016-09-19T04:04:56Z
39,578,170
<p>Standard Order of operations gives <code>and</code> precedence over <code>or</code>, so the first statement <code>True or False and False</code> is logically equivalent to </p> <pre><code>True or (False and False) </code></pre> <p>This evaluates to <code>True</code>.</p> <p>The second statement is </p> <pre><code>(True or False) and False </code></pre> <p>This evaluates to <code>False</code>.</p>
1
2016-09-19T16:47:20Z
[ "python" ]
How to specialize documenters in sphinx autodoc
39,565,203
<p>I am documenting a project with Sphinx I want to create a specialized version of the <code>autoclass::</code> directive that allows me to modify the documentation string for certain classes.</p> <p>Here is one thing I have tried: searching the sphinx source, I found that the <code>autoclass</code> directive is created via the <a href="https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/autodoc.py#L1216" rel="nofollow"><code>ClassDocumenter</code> object</a>. Following this, my idea was to register a subclass of <code>ClassDocumenter</code> for the classes of interest, and then override <code>get_doc</code> to modify the docstring.</p> <p>Here's my attempt at such an extension:</p> <pre><code>from six import class_types from sphinx.ext.autodoc import ClassDocumenter from testmodule import Foo # the class that needs modified documentation class MyClassDocumenter(ClassDocumenter): objtype = 'myclass' priority = 20 # higher priority than ClassDocumenter @classmethod def can_document_member(cls, member, membername, isattr, parent): return isinstance(member, class_types) and issubclass(member, Foo) def get_doc(self, encoding=None, ignore=1): doc = super(MyClassDocumenter, self).get_doc(encoding, ignore) # do something to modify the output documentation doc[0].insert(0, "ADD SOMETHING TO THE DOC") return doc def setup(app): app.add_autodocumenter(MyClassDocumenter) </code></pre> <p>The problem is, when I run this I get an error: <code>ERROR: Unknown directive type "py:myclass".</code> It seems that registering a documenter is not enough to register the associated directive, but I've not been able to find any clues in the sphinx source to tell me how such a registration is supposed to happen. It's not as simple as using the standard <code>add_directive()</code> methods, because I have no explicit directive to register.</p> <p>How can I correctly accomplish such a specialization of an auto-documenter in sphinx?</p> <p>(note: the full set of files to reproduce the error is available <a href="https://gist.github.com/jakevdp/34a57475bce1bf210667630aa622f407" rel="nofollow">in this gist</a>)</p>
0
2016-09-19T04:06:05Z
39,565,337
<p>I have found something in <a href="http://www.sphinx-doc.org/en/stable/extdev/markupapi.html#directives" rel="nofollow">Docutils markup API</a></p> <blockquote> <p>Directives are handled by classes derived from docutils.parsers.rst.Directive. They have to be registered by an extension using Sphinx.add_directive() or Sphinx.add_directive_to_domain().</p> </blockquote> <p>Is it what you are looking for?</p>
0
2016-09-19T04:24:19Z
[ "python", "python-sphinx" ]
How to specialize documenters in sphinx autodoc
39,565,203
<p>I am documenting a project with Sphinx I want to create a specialized version of the <code>autoclass::</code> directive that allows me to modify the documentation string for certain classes.</p> <p>Here is one thing I have tried: searching the sphinx source, I found that the <code>autoclass</code> directive is created via the <a href="https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/autodoc.py#L1216" rel="nofollow"><code>ClassDocumenter</code> object</a>. Following this, my idea was to register a subclass of <code>ClassDocumenter</code> for the classes of interest, and then override <code>get_doc</code> to modify the docstring.</p> <p>Here's my attempt at such an extension:</p> <pre><code>from six import class_types from sphinx.ext.autodoc import ClassDocumenter from testmodule import Foo # the class that needs modified documentation class MyClassDocumenter(ClassDocumenter): objtype = 'myclass' priority = 20 # higher priority than ClassDocumenter @classmethod def can_document_member(cls, member, membername, isattr, parent): return isinstance(member, class_types) and issubclass(member, Foo) def get_doc(self, encoding=None, ignore=1): doc = super(MyClassDocumenter, self).get_doc(encoding, ignore) # do something to modify the output documentation doc[0].insert(0, "ADD SOMETHING TO THE DOC") return doc def setup(app): app.add_autodocumenter(MyClassDocumenter) </code></pre> <p>The problem is, when I run this I get an error: <code>ERROR: Unknown directive type "py:myclass".</code> It seems that registering a documenter is not enough to register the associated directive, but I've not been able to find any clues in the sphinx source to tell me how such a registration is supposed to happen. It's not as simple as using the standard <code>add_directive()</code> methods, because I have no explicit directive to register.</p> <p>How can I correctly accomplish such a specialization of an auto-documenter in sphinx?</p> <p>(note: the full set of files to reproduce the error is available <a href="https://gist.github.com/jakevdp/34a57475bce1bf210667630aa622f407" rel="nofollow">in this gist</a>)</p>
0
2016-09-19T04:06:05Z
39,574,132
<p><code>Documenter</code> classes require an existing directive to apply, when appropriate. This can either be a "built in" directive, or it can be a custom directive you create and register. Either way, the directive to use is specified by the <code>directivetype</code> class attribute. You can specify this value explicitly:</p> <pre><code>class MyClassDocumenter(ClassDocumenter): directivetype = 'foo' # corresponds to :foo: in the doc source objtype = 'bar' priority = 20 </code></pre> <p>Or, it looks like you can omit <code>directivetype</code> and it will use the same value as <code>objtype</code> by default. (This is an educated guess)</p> <p>So then the question is: have you registered a new directive for <code>:myclass:</code>? If not I think that is the problem. Alternatively, if there is some other directive that you want to be used (whether built-in, or custom) the answer is probably to specify it explicitly by including a value for <code>directivetype</code> in your <code>Documenter</code> class definition. </p>
0
2016-09-19T13:14:21Z
[ "python", "python-sphinx" ]
pymongo+MongoDB: How to find _id in pymongo?
39,565,253
<p>I want to find the <code>_id</code> of a document of a collection <code>(mycol)</code> where <code>"name":"John"</code>. I have inserted the document but want to find the <code>_id</code> of document. Is it possible ? I am trying as </p> <pre><code>result = db.mycol.find({"_id": {"name": "John"}}) </code></pre> <p>But it is returning a cursor object.</p> <blockquote> <p>pymongo.cursor.Cursor object at 0x00000000030E3DD8></p> </blockquote> <p>Then I tried as </p> <pre><code>for itm in result: print (itm) </code></pre> <p>But it is not printing anything.</p>
2
2016-09-19T04:12:53Z
39,565,444
<p>Try it like that </p> <pre><code>result = db.mycol.find({"name": "John"}) for item in result: print(item['_id']) </code></pre> <p>Just have a look at the <a href="http://api.mongodb.com/python/current/tutorial.html#querying-for-more-than-one-document" rel="nofollow">docs</a> to see how to use pymongo</p>
0
2016-09-19T04:36:20Z
[ "python", "mongodb", "mongodb-query", "pymongo" ]
pandas dataframe look ahead optimization
39,565,298
<p>What's the best way to do this with pandas dataframe? I want to loop through a dataframe, and find the nearest next index that has at least +/-2 value difference. For example: [100, 99, 102, 98, 103, 103] will create a new column with this [2, 2, 3, 0, N/A], 0 means not find.</p> <p>My solution performance is n * log(n). Any brilliant people could please show me a better performance solution?</p>
2
2016-09-19T04:18:19Z
39,620,425
<p>When all the elements are integers, it is possible to do so in linear time. The following solution is complicated, and of algorithmic interest (if at that) only. Since it uses loops and data structures, any real implementation would need to be in C/C++/Cython (otherwise, the constants would be so high, that a tremendously long sequence would be needed to start seeing an improvement, even though it's linear).</p> <p>Since the solution is complicated, I'll first make some simplifying assumptions, then show how to get rid of them. The initial assumptions are:</p> <ol> <li><p>What's needed is to find the index of the next position that is 2 or greater.</p></li> <li><p>All the integers are distinct.</p></li> </ol> <p>Given these assumptions, it's possible to use a variant of a well known interview question (it's so common, I think it's folklore). The idea is to keep a stack of the positions of the array where the next positions have not yet been found. While looping over the elements and the positions, loop invariants are maintained: </p> <ul> <li><p>The indices in the stack are increasing.</p></li> <li><p>The stack does not contain positions <em>i</em>, <em>j</em> such that <em>a[i] + 2 &lt;= a[j]</em> and <em>i &lt; j</em>. </p></li> </ul> <p>The invariants are initially trivially satisfied, and I'll show how they're maintained.</p> <p>Say at iteration <em>j</em>, the stack's top is <em>i</em>: I'll mark this as <em>&lt;..., i></em> (the stack goes to the right). While <em>a[j] >= a[i] + 2</em>, we can pop the stack and set the next position of <em>i</em> to be <em>j</em>. While this happens, we can pop the stack until the condition fails. As some point, though, the stack can be <em>&lt;..., k, i></em>, with <em>a[i] + 2 > a[j]</em>. Some thought on the invariants is enough to see, that in this case, if there is an element in the stack that needs to be popped, it must be <em>k</em> (if it exists). That is the only item that needs to be checked - any other item before the last one cannot be one that needs to be popped. So, we just need to check <em>k</em>, and pop it too if necessary. At the end of the iteration, we just need to push <em>j</em> itself.</p> <p>The following code does this:</p> <pre><code>def plus2_detector(a, verbose=False): if verbose: print 'starting with', a remaining, out = [], [None] * len(a) for i, e in enumerate(a): if verbose: print 'it begin', i, e, remaining while remaining and e &gt;= a[remaining[-1]] + 2: if verbose: print 'setting', i, remaining[-1], a[remaining[-1]] out[remaining[-1]] = i del remaining[-1] if len(remaining) &gt; 1 and e &gt;= a[remaining[-2]] + 2: if verbose: print 'back setting', i, remaining[-2], a[remaining[-2]] out[remaining[-2]] = i del remaining[-2] remaining.append(i) if verbose: print 'it end', i, e, remaining return out </code></pre> <p>You can run it, e.g., </p> <pre><code>&gt;&gt;&gt; plus2_detector([1, 2, 3, 5, 4, -1, -2, 10, 9, 8, 7, 11], False) [2, 3, 3, 7, 7, 7, 7, None, 11, 11, 11, None] </code></pre> <p>To get an intuitive feeling of what it does, you can run it on different (distinct integers!) with <code>verbose=True</code>, and see what it does.</p> <hr> <p>Now to get rid of the simplifications. </p> <p>The first simplification riddance is easy: run two copies of this algorithm: one checking for <em>>= 2</em>, and one checking for <em>&lt;= -2</em>, and combine the results.</p> <p>The second simplification riddance is more tricky. The problem is that if the top of the stack doesn't need to be popped, we might need to search many items back to see if anyone needs to be popped - it's not necessarily true that this potential item is right under the top. This can happen if the elements along the top of the stack are identical.</p> <p>Dealing with this problem is tedious, but not that difficult conceptually. The stack now needs to contain lists of integers of consecutive undealt indices of equivalent elements. This means that when you push a new index, you need to check if it continues a run. If it does, append it to the list at the top; if it does not, create a new tuple. Now all consecutive equivalent undealt items are grouped together (similar to what <code>itertools.groupby</code> does). </p> <p>There are technical complications (when popping the penultimate list, we might need to combine the top and the new penultimate tuple), but the idea is the same.</p> <p>The complexity is linear using a standard argument from amortized analysis (each element is inserted and popped once, the non-popping operations are constants).</p> <p>Here is the code for the general case of finding +2 or above indices, without the restriction that elements are unique:</p> <pre><code>def general_plus2_detector(a, verbose=False): if verbose: print 'starting with', a remaining, out = [], [None] * len(a) for i, e in enumerate(a): if verbose: print 'it begin', i, '(', e, ')', remaining while remaining and e &gt;= a[remaining[-1][0]] + 2: for j in remaining[-1]: if verbose: print 'setting', j, '(', a[j], ') to', i, '(', a[i], ')' out[j] = i del remaining[-1] if len(remaining) &gt; 1 and e &gt;= a[remaining[-2][0]] + 2: for j in remaining[-2]: if verbose: print 'back setting', j, '(', a[j], ') to', i, '(', a[i], ')' out[j] = i del remaining[-2] if len(remaining) &gt; 1 and a[remaining[-2][0]] == a[remaining[-1][0]]: if verbose: print 'joining', remaining[-2], remaining[-1] remaining[-1].extend(remaining[-2]) del remaining[-2] if not remaining or a[remaining[-1][0]] != e: remaining.append([i]) else: remaining[-1].append(i) if verbose: print 'it end', i, '(', e, ')', remaining return out </code></pre> <p>Running it shows:</p> <pre><code>a = [-1, -2, 3, 2, 2, 3, 2, 2, 4, 5, 4, 5, 2, 3, 4, 5, 5, 4, 4, 7] &gt;&gt;&gt; general_plus2_detector(a, False) [2, 2, 9, 8, 8, 9, 8, 8, 19, 19, 19, 19, 14, 15, 19, 19, 19, 19, 19, None] </code></pre>
1
2016-09-21T15:14:01Z
[ "python", "algorithm" ]
Regex: match only outside parenthesis (so that the text isn't split within parenthesis)?
39,565,349
<p>I have a target string which looks like this:</p> <pre><code>"foo (foo, foofoo), bar (foobar), foo, bar (barbar, foo), bar, foo" </code></pre> <p>and I want:</p> <pre><code>["foo (foo, foofoo)", "bar (foobar)", "foo", "bar (barbar, foo)", "bar", "foo"] </code></pre> <p>by splitting the target at <code>", "</code> <em>only outside the parenthesis</em>. What is the regex to match the commas outside the parenthesis? In my case, nested parenthesis do not appear and I don't have to consider them.</p> <p>I personally use Python but any language example is fine.</p>
1
2016-09-19T04:25:36Z
39,565,427
<pre><code>,(?![^(]*\)) </code></pre> <p>You can use this to split.See demo.This holds true as u said there are no nested <code>()</code>.</p> <p><a href="https://regex101.com/r/wV5bD0/1" rel="nofollow">https://regex101.com/r/wV5bD0/1</a></p>
2
2016-09-19T04:34:31Z
[ "python", "regex" ]
Regex: match only outside parenthesis (so that the text isn't split within parenthesis)?
39,565,349
<p>I have a target string which looks like this:</p> <pre><code>"foo (foo, foofoo), bar (foobar), foo, bar (barbar, foo), bar, foo" </code></pre> <p>and I want:</p> <pre><code>["foo (foo, foofoo)", "bar (foobar)", "foo", "bar (barbar, foo)", "bar", "foo"] </code></pre> <p>by splitting the target at <code>", "</code> <em>only outside the parenthesis</em>. What is the regex to match the commas outside the parenthesis? In my case, nested parenthesis do not appear and I don't have to consider them.</p> <p>I personally use Python but any language example is fine.</p>
1
2016-09-19T04:25:36Z
39,565,496
<p>You can use this to extract the matches. Assuming there are no nested <code>()</code></p> <pre><code>(\w+(?: \([^\)]*\))?) </code></pre> <p><a href="https://www.regex101.com/r/gR6jF1/1" rel="nofollow">https://www.regex101.com/r/gR6jF1/1</a></p>
1
2016-09-19T04:41:37Z
[ "python", "regex" ]
call next iteration in list after first comparision loop
39,565,354
<p>i have a situation where i have to loop over a list, grab info from a file, write a new file, send an email, and then go back to the list for the next iteration to start the process over again.<br> i'll try to write it out and then put my code in for you to look at.<br> the list is a list of ipaddresses and both files are text.</p> <p>def grab info from a file1<br> def build my list1 (first code block)<br> def take list1[0] apply it to file1 and build file2 from it (second code block)<br> def get email address from list1[0]<br> def send email with file2<br> (i can do all of this, it's just getting back to list1[1] that i can't do)<br> go to list1[1] apply to file1 build file2 send email, etc... until end of list</p> <pre><code> 2 import re 3 4 def one_ip_each(): 5 one_ip_each = [] 6 global ipAddr 7 with open('Invalid_names_file') as Invalid_names_file: 8 a = [re.search(r'((\d+\.)+\d+)', line).group() for line in \ 9 Invalid_names_file] 10 for x in a: 11 if x not in one_ip_each: 12 one_ip_each.append(x) 13 ipAddr = x 14 return ipAddr 15 ## makes an iterator that interpreter can step through, yet other funciton 16 ## complains that it's not a string 17 # ipAddr = iter(one_ip_each) 18 # return ipAddr 19 20 one_ip_each() </code></pre> <p>here's code that returns what i want (without ipAddr being an iter) and not looping)</p> <pre><code> 5 def isp_email_names(): 6 with open('Invalid_names_file') as Invalid_names_file: 7 with open('ISP_names_file', 'w') as ISP_names_file: 8 for line in Invalid_names_file: 9 if one_ip_each.ipAddr in line: 10 ISP_names_file.write(str(line)) 11 ISP_names_file.flush() </code></pre> <p>hopefully with the line numbers this will help some. </p> <p>i made the ipAddr a global so that i can call it from the email function to know that file2 is going to the proper people.<br> i don't know if this matters or not. </p> <p>if i make the ipAddr into an iter (as line 17 and 18) i get -> </p> <pre><code>TypeError: 'in &lt;string&gt;' requires string as left operand, not list_iterator </code></pre> <p>i enjoy learning while i read, yet i'm stuck. point me in the proper direction and i will read and come back to answer the question.<br> yet with what i have read people want to build filters, def more functions.</p> <p>i would think that it should be pretty easy i just can't grasp it.<br> (post is kind of long, yet wanted to be thourough)</p>
0
2016-09-19T04:26:29Z
39,567,677
<pre><code> 0 def isp_email_names(): 1 with open('Invalid_names_file') as Invalid_names_file: 2 with open('ISP_names_file', 'w') as ISP_names_file: 3 for line in Invalid_names_file: 4 if one_ip_each.ipAddr in line: </code></pre> <p>Line 4, one_ip_each.ipAddr is a list_iter, line is a str. String never contains list_iter.</p> <p>You could try this:</p> <pre><code>if line in one_ip_each.ipAddr </code></pre>
0
2016-09-19T07:34:17Z
[ "python", "python-3.x" ]
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more?
39,565,357
<p>The exact question to this problem is: *Create a file with a 20 lines of text and name it “lines.txt”. Write a program to read this a file “lines.txt” and write the text to a new file, “numbered_lines.txt”, that will also have line numbers at the beginning of each line. Example: Input file: “lines.txt”</p> <pre><code>Line one Line two </code></pre> <p>Expected output file:</p> <pre><code>1 Line one 2 Line two </code></pre> <p>I am stuck, and this is what I have so far. I am a true beginner to Python and my instructor does not make things very clear. Critique and help much appreciated.</p> <pre><code>file_object=open("lines.txt",'r') for ln in file_object: print(ln) count=1 file_input=open("numbered_lines.txt",'w') for Line in file_object: print(count,' Line',(str)) count=+1 file_object.close file_input.close </code></pre> <p>All I get for output is the .txt file I created stating lines 1-20. I am very stuck and honestly have very little idea about what I am doing. Thank you</p>
0
2016-09-19T04:26:36Z
39,565,442
<p>You have all the right parts, and you're almost there:</p> <p>When you do</p> <pre><code>for ln in file_object: print(ln) </code></pre> <p>you've exhausted the contents of that file, and you won't be able to read them again, like you try to do later on.</p> <p>Also, <code>print</code> does not write to a file, you want <code>file_input.write(...)</code></p> <p>This should fix all of that:</p> <pre><code>infile = open("lines.txt", 'r') outfile = open("numbered_lines.txt", 'w') line_number = 1 for line in infile: outfile.write(str(line_number) + " " + line) infile.close() outfile.close() </code></pre> <p>However, here is a more pythonic way to do it:</p> <pre><code>with open("lines.txt") as infile, open("numbered_lines.txt", 'w') as outfile: for i, line in enumerate(infile, 1): outfile.write("{} {}".format(i, line)) </code></pre>
1
2016-09-19T04:35:54Z
[ "python", "file" ]
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more?
39,565,357
<p>The exact question to this problem is: *Create a file with a 20 lines of text and name it “lines.txt”. Write a program to read this a file “lines.txt” and write the text to a new file, “numbered_lines.txt”, that will also have line numbers at the beginning of each line. Example: Input file: “lines.txt”</p> <pre><code>Line one Line two </code></pre> <p>Expected output file:</p> <pre><code>1 Line one 2 Line two </code></pre> <p>I am stuck, and this is what I have so far. I am a true beginner to Python and my instructor does not make things very clear. Critique and help much appreciated.</p> <pre><code>file_object=open("lines.txt",'r') for ln in file_object: print(ln) count=1 file_input=open("numbered_lines.txt",'w') for Line in file_object: print(count,' Line',(str)) count=+1 file_object.close file_input.close </code></pre> <p>All I get for output is the .txt file I created stating lines 1-20. I am very stuck and honestly have very little idea about what I am doing. Thank you</p>
0
2016-09-19T04:26:36Z
39,565,464
<p>The right way to open a file is using a <code>with</code> statement:</p> <pre><code>with open("lines.txt",'r') as file_object: ... # do something </code></pre> <p>That way, the context manager introduced by <code>with</code> will close your file at the end of "something " or in case of exception.</p> <p>Of course, you can close the file yourself if you are not familiar with that. Not that <code>close</code> is a method: to call it you need parenthesis:</p> <pre><code>file_object.close() </code></pre> <p>See the chapter 7.2. <a href="https://docs.python.org/3.5/tutorial/inputoutput.html" rel="nofollow">Reading and Writing Files</a>, in the official documentation. </p>
0
2016-09-19T04:38:26Z
[ "python", "file" ]
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more?
39,565,357
<p>The exact question to this problem is: *Create a file with a 20 lines of text and name it “lines.txt”. Write a program to read this a file “lines.txt” and write the text to a new file, “numbered_lines.txt”, that will also have line numbers at the beginning of each line. Example: Input file: “lines.txt”</p> <pre><code>Line one Line two </code></pre> <p>Expected output file:</p> <pre><code>1 Line one 2 Line two </code></pre> <p>I am stuck, and this is what I have so far. I am a true beginner to Python and my instructor does not make things very clear. Critique and help much appreciated.</p> <pre><code>file_object=open("lines.txt",'r') for ln in file_object: print(ln) count=1 file_input=open("numbered_lines.txt",'w') for Line in file_object: print(count,' Line',(str)) count=+1 file_object.close file_input.close </code></pre> <p>All I get for output is the .txt file I created stating lines 1-20. I am very stuck and honestly have very little idea about what I am doing. Thank you</p>
0
2016-09-19T04:26:36Z
39,565,586
<ol> <li><p>In the first loop you're printing the contents of the input file. This means that the file contents have already been consumed when you get to the second loop. (Plus the assignment didn't ask you to print the file contents.)</p></li> <li><p>In the second loop you're using <code>print()</code> instead of writing to a file. Try <code>file_input.write(str(count) + " " + Line)</code> (And <code>file_input</code> seems like a bad name for a file that you will be <em>writing</em> to.)</p></li> <li><p><code>count=+1</code> sets count to <code>+1</code>, i.e. <em>positive one</em>. I think you meant <code>count += 1</code> instead.</p></li> <li><p>At the end of the program you're calling <code>.close</code> instead of <code>.close()</code>. The parentheses are important!</p></li> </ol>
0
2016-09-19T04:51:08Z
[ "python", "file" ]
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more?
39,565,357
<p>The exact question to this problem is: *Create a file with a 20 lines of text and name it “lines.txt”. Write a program to read this a file “lines.txt” and write the text to a new file, “numbered_lines.txt”, that will also have line numbers at the beginning of each line. Example: Input file: “lines.txt”</p> <pre><code>Line one Line two </code></pre> <p>Expected output file:</p> <pre><code>1 Line one 2 Line two </code></pre> <p>I am stuck, and this is what I have so far. I am a true beginner to Python and my instructor does not make things very clear. Critique and help much appreciated.</p> <pre><code>file_object=open("lines.txt",'r') for ln in file_object: print(ln) count=1 file_input=open("numbered_lines.txt",'w') for Line in file_object: print(count,' Line',(str)) count=+1 file_object.close file_input.close </code></pre> <p>All I get for output is the .txt file I created stating lines 1-20. I am very stuck and honestly have very little idea about what I am doing. Thank you</p>
0
2016-09-19T04:26:36Z
39,565,656
<p>Good first try, and with that, I can go through your code and explain what you did right (or wrong)</p> <pre><code>file_object=open("lines.txt",'r') for ln in file_object: print(ln) </code></pre> <p>This is fine, though generally you want to put a space before and after assignments (you are assigning the results of <code>open</code> to <code>file_object) and add a space after a</code>,` when separating arguments, so you might want to write that like so:</p> <pre><code>file_object = open("lines.txt", 'r') for ln in file_object: print(ln) </code></pre> <p>However, at this point the internal reference in the <code>file_object</code> have reached the end of the file, so if you wish to reuse the same object, you need to <a href="https://docs.python.org/3/library/io.html#io.IOBase.seek" rel="nofollow"><code>seek</code></a> back to the beginning position, which is <code>0</code>. As your assignment only states write to the file (and not on the screen), the above loop should be omitted from the file (but I get what you want to do, you want to see the contents of the file immediately though sometimes instructors are pretty strict on what they accept). Moving on:</p> <pre><code>count=1 file_input=open("numbered_lines.txt",'w') for Line in file_object: </code></pre> <p>Looks pretty normal so far, again, minor formatting issues. In Python, typically we name all variables lower-case, as names with Capitalization are generally reserved for class names (if you wish to, you may <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">read about them</a>). Now we enter into the loop you got</p> <pre><code> print(count,' Line',(str)) </code></pre> <p>This prints not quite what you want. as <code>' Line'</code> is enclosed inside a quote, it is treated as a string literal - so it's treated literally as text and not code. Given that you had assigned <code>Line</code>, you want to take out the quotes. The <code>(str)</code> at the end simply just print out the string object and it definitely is not what you want. Also, you forgot to specify the <code>file</code> you want to print to. By default it will print to the screen, but you want to print it to the the <code>numbered_lines.txt</code> file which you had opened and assigned to <code>file_input</code>. We will correct this later.</p> <pre><code> count=+1 </code></pre> <p>If you format this differently, you are assigning <code>+1</code> to <code>count</code>. I am guessing you wanted to use the <code>+=</code> operator to increment it. Remember this on your quiz/tests.</p> <p>Finally:</p> <pre><code>file_object.close file_input.close </code></pre> <p>They are meant to be called as functions, you need to invoke them by adding parentheses at the end with arguments, but as <code>close</code> takes no arguments, there will be nothing inside the parentheses. Putting everything together, the complete corrected code for your program should look like this</p> <pre><code>file_object = open("lines.txt", 'r') count = 1 file_input = open("numbered_lines.txt", 'w') for line in file_object: print(count, line, file=file_input) count += 1 file_object.close() file_input.close() </code></pre> <p>Run the program. You will notice that there is an extra empty line between every line of text. This is because by default the <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow"><code>print</code></a> function adds a new line <code>end</code> character; the line you got from the file included a new-line character at the end (that's what make them lines, right?) so we don't have to add our own here. You can of course change it to an empty string. That line will look like this.</p> <pre><code> print(count, line, file=file_input, end='') </code></pre> <p>Naturally, other Python programmers will tell you that there are Pythonic ways, but you are just starting out, don't worry too much about them (although you can definitely pick up on this later and I highly encourage you to!)</p>
0
2016-09-19T04:59:00Z
[ "python", "file" ]
Basic Loop/Python
39,565,379
<p>I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!</p> <pre><code> def main(): while (num &gt;= 100) and (num &lt;= 200): for (num % 5 == 0) or (num % 6 == 0) print (num) main() </code></pre>
-3
2016-09-19T04:28:35Z
39,565,553
<p>You should init every variable using in the code While (condition) will break when the condition false. Since your condition depends on num, but num is never changed in your code, infinity loop will happen. You need to add <code>num = num + 1</code> at the end of your loop block. It's supposed to use if not for for each iterator here. And the condition you used for your problem is wrong to.</p> <p>Should be like this:</p> <pre><code>def main(): num = 100 while (num &gt;= 100) and (num &lt;= 200): if ((num % 5 == 0) or (num % 6 == 0)) and (num % 30 != 0): print (num) num = num + 1 main() </code></pre>
0
2016-09-19T04:47:39Z
[ "python", "python-3.x" ]
Basic Loop/Python
39,565,379
<p>I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!</p> <pre><code> def main(): while (num &gt;= 100) and (num &lt;= 200): for (num % 5 == 0) or (num % 6 == 0) print (num) main() </code></pre>
-3
2016-09-19T04:28:35Z
39,565,559
<p>This is how I would go about it. I would recommend using a for loop over a while loop if you know the range you need. You are less likely to get into an endless loop. The reason for the n variable is since you said you needed 10 numbers per line. The n variable will track how many correct numbers you find so that you know when you have ten results and can use a normal print statement which automatically includes a newline. The second print statement will not add a newline.</p> <pre><code>n = 0 for i in range(100,201): if (i%5 == 0 or i%6 == 0) and not (i%5 == 0 and i%6 == 0): n += 1 if n%10 == 0: print(i) else: print(str(i) + ", ", end="") </code></pre>
1
2016-09-19T04:48:18Z
[ "python", "python-3.x" ]
How to get a field value from one model to another model
39,565,489
<p>I created a new module which depends on sales. I also created a sales commission tab in sales order. I would like to add <code>amount_total</code> from the <code>sale.order</code> to <code>sales_value</code> in my new model <code>commission.sale</code> but nothing happens.</p> <p>In commission.py</p> <pre><code>_name = 'commission.sale' sales_value = fields.Float(compute="_total", string="Sale Value") @api.multi def _total(self): sale_obj = self.env['sale.order'].search([('amount_total','=', True)]) self.sales_value = self.sale_obj.amount_total </code></pre>
2
2016-09-19T04:41:03Z
39,826,344
<pre><code>class salesman_commission(models.Model): _name = 'salesman_commission' user = fields.Many2one('res.users',string='User') sales_order_id = fields.Many2one('sale.order',string='Sale id',ondelete='cascade') sales_val = fields.Float(compute='_total',string='Sales Value') percent = fields.Float(string='Percent') commission = fields.Integer(compute='_commission',string='Commission') @api.one @api.depends('sales_order_id.amount_total') def _total(self): self.sales_val = self.sales_order_id.amount_total </code></pre>
0
2016-10-03T07:21:30Z
[ "python", "odoo-8" ]
error is not displayed in the template
39,565,560
<p>I have used <strong>django allauth</strong> for user registration and login. I have used the <code>{{ form.has_errors }}</code> in template to show an error but the error is not displayed in the template. What might be the reason for not showing an error in the template? </p> <p>The code from allauth <code>login.html(account/login.html)</code></p> <pre><code>{% block content %} &lt;div class="login-box"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 col-sm-12 col-md-6 col-md-offset-3 login-area"&gt; &lt;span class="error"&gt; {% if form.has_errors %} &lt;p&gt;Your username and password didn't match. Please try again.&lt;/p&gt; {% endif %} &lt;/span&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading login-header"&gt;{% trans "Sign In" %}&lt;/div&gt; &lt;div class="panel-body"&gt; &lt;form class="login" method="POST" action="{% url 'account_login' %}"&gt; {% csrf_token %} &lt;div class="form-group form-group-lg"&gt; &lt;label for="emailAddress"&gt;Email address&lt;/label&gt; &lt;input type="email" class="form-control" id="emailAddress id_login" name="login" placeholder="Email"&gt; &lt;/div&gt; &lt;div class="form-group form-group-lg"&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" class="form-control" id="password id_password" name="password" placeholder="Password"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; {% if redirect_field_value %} &lt;input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /&gt; {% endif %} &lt;/div&gt; &lt;button class="btn-block signin-btn btn-sm btn-primary pull-right m-t-n-xs" type="submit"&gt;{% trans "Sign In" %}&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="panel-footer"&gt; &lt;a class="button secondaryAction" href="{% url 'account_reset_password' %}"&gt;{% trans "Forgot Password?" %}&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endblock %} </code></pre>
0
2016-09-19T04:48:20Z
39,565,739
<p>Seems to be a misunderstanding of <a href="https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.has_error" rel="nofollow">has_error</a> </p> <blockquote> <p>his method returns a boolean designating whether a field has an error with a specific error code. If code is None, it will return True if the field contains any errors at all.</p> </blockquote> <p>Coupled with the fact that you are rendering the form manually. Generally there are two types of form errors, non field errors and errors associated with each field (when their validation fails). The above method accepts a field name as a parameter and returns true if the field has failed validation.</p> <p>You have several options, including continuing with your current approach but checking for <a href="http://Form.errors" rel="nofollow">form.errors</a> instead of <code>form.has_error</code> or displaying the error with each field separately.</p>
1
2016-09-19T05:07:10Z
[ "python", "django", "django-templates", "django-allauth", "django-1.9" ]
error is not displayed in the template
39,565,560
<p>I have used <strong>django allauth</strong> for user registration and login. I have used the <code>{{ form.has_errors }}</code> in template to show an error but the error is not displayed in the template. What might be the reason for not showing an error in the template? </p> <p>The code from allauth <code>login.html(account/login.html)</code></p> <pre><code>{% block content %} &lt;div class="login-box"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 col-sm-12 col-md-6 col-md-offset-3 login-area"&gt; &lt;span class="error"&gt; {% if form.has_errors %} &lt;p&gt;Your username and password didn't match. Please try again.&lt;/p&gt; {% endif %} &lt;/span&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading login-header"&gt;{% trans "Sign In" %}&lt;/div&gt; &lt;div class="panel-body"&gt; &lt;form class="login" method="POST" action="{% url 'account_login' %}"&gt; {% csrf_token %} &lt;div class="form-group form-group-lg"&gt; &lt;label for="emailAddress"&gt;Email address&lt;/label&gt; &lt;input type="email" class="form-control" id="emailAddress id_login" name="login" placeholder="Email"&gt; &lt;/div&gt; &lt;div class="form-group form-group-lg"&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" class="form-control" id="password id_password" name="password" placeholder="Password"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; {% if redirect_field_value %} &lt;input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /&gt; {% endif %} &lt;/div&gt; &lt;button class="btn-block signin-btn btn-sm btn-primary pull-right m-t-n-xs" type="submit"&gt;{% trans "Sign In" %}&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="panel-footer"&gt; &lt;a class="button secondaryAction" href="{% url 'account_reset_password' %}"&gt;{% trans "Forgot Password?" %}&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endblock %} </code></pre>
0
2016-09-19T04:48:20Z
39,565,751
<p>Try this one. Errors raised by the form which is not attached to field are stored in non_field_errors</p> <pre><code> {% if form.non_field_errors %} &lt;ul class='form-errors'&gt; {% for error in form.non_field_errors %} &lt;li&gt;{{ error }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} </code></pre> <p>or if you want to display in your way try this one</p> <pre><code>{% if form.errors %} &lt;p&gt;Your username and password didn't match. Please try again.&lt;/p&gt; {% endif %} </code></pre>
1
2016-09-19T05:09:10Z
[ "python", "django", "django-templates", "django-allauth", "django-1.9" ]
Can't deploy to Scrapinghub
39,565,575
<p>When I try to deploy using <code>shub deploy</code>, I got this error:</p> <blockquote> <p>Removing intermediate container fccf1ec715e6 Step 10 : RUN sudo -u nobody -E PYTHONUSERBASE=$PYTHONUSERBASE pip install --user --no-cache-dir -r /app/requirements.txt ---> Running in 729e0d414f46 Double requirement given: attrs==16.1.0 (from -r /app/requirements.txt (line 51)) (already in attrs==16.0.0 (from -r /app/requirements.txt (line 1)), name='attrs')</p> <p>{"message": "The command '/bin/sh -c sudo -u nobody -E PYTHONUSERBASE=$PYTHONUSERBASE pip install --user --no-cache-dir -r /app/requirements.txt' returned a non-zero code: 1", "details": {"message": "The command '/bin/sh -c sudo -u nobody -E PYTHONUSERBASE=$PYTHONUSERBASE pip install --user --no-cache-dir -r /app/requirements.txt' returned a non-zero code: 1"}, "error": "build_error"}</p> <p>{"message": "Internal build error", "status": "error"} Deploy log location: c:\users\dr521f~1.pri\appdata\local\temp\shub_deploy_pvx7dk.log Error: Deploy failed: {"message": "Internal build error", "status": "error"}</p> </blockquote> <p>This is my <code>requirements.txt</code>:</p> <pre><code>attrs==16.1.0 beautifulsoup4==4.5.1 cffi==1.8.2 click==6.6 cryptography==1.5 cssselect==0.9.2 enum34==1.1.6 fake-useragent==0.1.2 hubstorage==0.23.1 idna==2.1 ipaddress==1.0.17 lxml==3.6.1 parsel==1.0.3 pyasn1==0.1.9 pyasn1-modules==0.0.8 pycparser==2.14 PyDispatcher==2.0.5 pyOpenSSL==16.1.0 pypiwin32==219 queuelib==1.4.2 requests==2.11.1 retrying==1.3.3 ruamel.ordereddict==0.4.9 ruamel.yaml==0.12.13 scrapinghub==1.8.0 Scrapy==1.1.2 scrapy-fake-useragent==0.0.1 service-identity==16.0.0 shub==2.4.0 six==1.10.0 Twisted==16.4.0 typing==3.5.2.2 w3lib==1.15.0 zope.interface==4.3.2 </code></pre> <p>Why can't I deploy?</p>
0
2016-09-19T04:50:03Z
39,565,576
<p>From the documentation <a href="http://doc.scrapinghub.com/shub.html" rel="nofollow">here</a></p> <blockquote> <p>Note that this requirements file is an extension of the Scrapy Cloud stack, and therefore should not contain packages that are already part of the stack, such as scrapy.</p> </blockquote> <p>As you can see in the error:</p> <blockquote> <p>Running in 729e0d414f46 Double requirement given: attrs==16.1.0 (from -r /app/requirements.txt (line 51)) (already in attrs==16.0.0 (from -r /app/requirements.txt (line 1)), name='attrs')</p> </blockquote> <p>It says <code>Double requirement given</code>.</p> <p>Use different <code>requirements.txt</code> for the whole project and for Scrapinghub. I ended up creating <code>shub-requirements.txt</code> which contains this:</p> <pre><code>beautifulsoup4==4.5.1 fake-useragent==0.1.2 </code></pre>
0
2016-09-19T04:50:03Z
[ "python", "deployment", "web-scraping", "scrapy", "scrapinghub" ]
Better edge detection with OpenCV and rounded corner cards
39,565,584
<p>I've been using the great tutorials at <a href="http://www.pyimagesearch.com/2014/05/05/building-pokedex-python-opencv-perspective-warping-step-5-6/" rel="nofollow">PyImageSearch.com</a> to get a Pi (v3) to recognise some playing cards. So far it's been working out alright, but the method described in the tutorials is meant more for sharp-cornered rectangles, and of course playing cards are round-cornered. This means that the contour corners end up being drawn slightly offset to the actual card, so the cropped and de-warped image I get is slightly rotated, which throws off the phash recognition slightly. <a href="http://i.stack.imgur.com/XcJqe.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/XcJqe.jpg" alt=""></a> The green outline is that provided by OpenCV, and you can see compared to the red lines I drew that mark the actual boundaries that it's offset/rotated. My question is; how can I get it to follow those red lines i.e. detect the edges?</p> <p>This is the code currently running to get that result:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>frame = vs.read() frame = cv2.flip(frame, 1) frame = imutils.resize(frame, width=640) image = frame.copy() #copy frame so that we don't get funky contour problems when drawing contours directly onto the frame. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.bilateralFilter(gray, 11, 17, 17) edges = imutils.auto_canny(gray) cv2.imshow("Edge map", edges) #find contours in the edged image, keep only the largest # ones, and initialize our screen contour _, cnts, _ = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:3] screenCnt = None # loop over our contours for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.05 * peri, True) # if our approximated contour has four points, then # we can assume that we have found our card if len(approx) == 4: screenCnt = approx break cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 3)</code></pre> </div> </div> </p>
0
2016-09-19T04:51:05Z
39,671,918
<p>Turns out I just needed to read the <a href="http://docs.opencv.org/trunk/dd/d49/tutorial_py_contour_features.html" rel="nofollow">OpenCV contour docs</a> a bit more. What I was basically looking for was a minimum area box around my contour:</p> <pre><code>rect = cv2.minAreaRect(cnt) # get a rectangle rotated to have minimal area box = cv2.boxPoints(rect) # get the box from the rectangle box = np.int0(box) # the box is now the new contour. </code></pre> <p>In my case, all instances of <code>screenCnt</code> now become the <code>box</code> variable and the rest of my code continues as normal.</p>
0
2016-09-24T02:30:10Z
[ "python", "opencv" ]