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
Finding and Replacing values in an XML
38,089,733
<p><a href="http://i.stack.imgur.com/fqqyE.png" rel="nofollow">Error and code pictured</a></p> <p>I'm an amatuer coder, but I'm trying to write a code at work that will quickly replace all values in an XML. I want to replace every instance of 'linear' and 'angular' with a uniform value. I saved both the code and the X...
-1
2016-06-29T03:12:46Z
38,091,805
<p>I also recommend to post the code and error message below your question, as well as modify you code to give a working example!</p> <p>Nonetheless, I think you have mistaken the <em>ElementTree.parse</em> method for <em>ElementTree.fromstring</em>. The first one parses the XML file given the file name to the functio...
0
2016-06-29T06:23:36Z
[ "python", "xml", "replace", "find" ]
Back end python query retrieving mysql id for user
38,089,925
<p>I'm trying to understand <strong>Python Web Development</strong>, particularly the part with using sessions and I can't seem to understand what this line of code means. Basically, I'm trying to retrieve the <code>id</code> of the form of a user login and the only information of the user is the email they entered. ...
-1
2016-06-29T03:32:57Z
38,090,087
<p>You are querying a <strong>list</strong> of users_id whose <code>email = session['email']</code>...so the output of this query obviously will be a list of objects(or list of ids object in your case).</p> <p>So, by <code>id[0]</code> you are setting <code>session['id']</code> to the first one of id list</p>
0
2016-06-29T03:54:06Z
[ "python", "mysql", "flask", "flask-sqlalchemy", "server-side" ]
Plotting exponential function python
38,089,954
<p>I get a linear graph when trying to plot exponential function:</p> <pre><code>import math import numpy as np import matplotlib.pyplot as plt def graph(formula, x_range): x = np.array(x_range) y = eval(formula) plt.plot(x, y) graph('100*(np.power(0.8, x))', (0,100)) </code></pre> <p>what am I doing wrong...
0
2016-06-29T03:36:20Z
38,090,045
<p>You really should NOT BE USING EVAL. However, leaving that issue aside, the problem is you are passing a tuple of two values as the argument for the x_range parameter. This is creating a <code>x</code> with the value: <code>array([ 0, 100])</code>, and if you create the corresponding y's, you'll only have two point...
1
2016-06-29T03:48:26Z
[ "python", "matplotlib" ]
PyMySQL throw "pymysql.err.Error: Already closed"
38,089,962
<p>In PyMySQL, How to make <code>pymysql.connect</code> keep-alive forever ?</p> <p><strong>OR</strong> </p> <p>How to check connect already closed before used.</p>
0
2016-06-29T03:37:20Z
38,090,318
<p>Looking at the <code>pymysql</code> code, at <a href="https://github.com/PyMySQL/PyMySQL/blob/f2e79cd1817a528b3f976ee1c79ab9d5bdf4324e/pymysql/connections.py#L724" rel="nofollow">this</a> line, you will see that the <code>connection</code> object has a property <code>open</code>:</p> <pre><code>@property def open(s...
0
2016-06-29T04:20:38Z
[ "python", "python-3.x", "pymysql" ]
Performance improvement when comparing 2 huge csv files [python]
38,089,984
<p>I have 2 csv files and I need to test every row in the first file against all the rows in the other file and write matching row to a new csv file. Here is the file structure. </p> <p><strong>csv 1</strong> (Has readings which are sampled 20s apart. First row is always header):</p> <p>Date Time Col1 Col2<br> 6/27/...
0
2016-06-29T03:41:02Z
38,090,164
<p>Since it seems that rows are ordered by time you could initially read a row from both files. If timestamp of the rows match then write the row to output and advance to next row in both files. If timestamps differ then read the next row from file where current timestamp was smaller. Below is simple implementation of ...
1
2016-06-29T04:03:11Z
[ "python", "loops", "csv" ]
Google App Engine - Task Queue taking too long to start random tasks
38,090,003
<p>Our clients are having problems with our appengine python application that requires task queues processing to generate reports and display as soon as they are finished. That workaround to the well known GAE slowness and timeouts have been working well for us until recently.</p> <p>Last week we started getting compl...
5
2016-06-29T03:43:17Z
38,190,286
<p>This problem stopped happening without any action. Apparently, it's due to some kind of failure in the GAE servers. The problem lasted for about two weeks.</p> <p>One action that can minimize the problem, however, is to spread your tasks in separate queues, if possible.</p> <p>--- edit ---</p> <p>It's happening a...
0
2016-07-04T18:12:55Z
[ "python", "google-app-engine" ]
how to wait for a specified time until a command gives a desired output
38,090,012
<p>I am writing a small python script to wait for a max of 1200 secs for devices to come up ,what is the best way to accomplish this?</p> <p>command to run</p> <pre><code>device.exe list </code></pre> <p>Output when no devices attached:</p> <pre><code>List of devices attached </code></pre> <p>Output When devices a...
1
2016-06-29T03:43:58Z
38,090,409
<p>You might be interested in the <code>retrying</code> library:</p> <p><a href="https://pypi.python.org/pypi/retrying" rel="nofollow">https://pypi.python.org/pypi/retrying</a></p> <p>You will likely need some combinations of <code>stop_max_delay</code> and <code>retry_on_result</code> keyword arguments with the <cod...
0
2016-06-29T04:29:49Z
[ "python" ]
How to generate a list of all (x, y, pixel value) tuples from a 2D image matrix with numpy?
38,090,056
<p>Using python and probably numpy, how can I generate a list of all coordinates with a ( x, y, pixelValue(x,y) ) format? I can achieve this with for loops using the following:</p> <pre><code>img = cv2.imread('messi5.jpg',0) data = [] for x in range(img.shape[1]): for y in range(img.shape[0]): data.appen...
0
2016-06-29T03:50:15Z
38,090,421
<p><code>numpy.ndenumerate</code> will create a generator in no time. You can then convert it to a list if you really need (???) to.</p> <pre><code>&gt;&gt;&gt; np.ndenumerate(np.eye(2)) &lt;numpy.lib.index_tricks.ndenumerate at 0x20d485f8&gt; &gt;&gt;&gt;for elem in np.ndenumerate(np.eye(2)): ... print elem ... (...
1
2016-06-29T04:31:08Z
[ "python", "opencv", "numpy", "scipy" ]
Python TypeError: 'TagList' object is not iterable
38,090,102
<p>This happens all the time. A function returns an object that I can't read. Here:</p> <pre><code> discoverer = GstPbutils.Discoverer() discoverer.connect('discovered', on_discovered) info = discoverer.discover_uri(self.loaded_file) print(vinfo.get_tags()) </code></pre> <p>Returns this:</p> <pre><cod...
2
2016-06-29T03:55:22Z
38,120,633
<p>This is all hypothetical as I never used python with GStreamer:</p> <p>According to documentation - yes it is said its list.. but this could be represented as internal structure.. remember that python bindings are just.. bindings - it all works similarly (if not implemented in a better way) as in C.. and what do yo...
1
2016-06-30T10:35:26Z
[ "python", "gstreamer" ]
How to type-check usage of next() with groupby result using mypy?
38,090,105
<p>I'm trying out mypy for some utils functions in my project, but I'm having trouble with this function that combines groupby and next.</p> <p>This is the function code:</p> <pre><code>from itertools import groupby from typing import Iterable, Any def all_same(iterable: Iterable[Any]) -&gt; bool: """Return Tru...
0
2016-06-29T03:55:54Z
38,091,058
<p>The reason is due to the <a href="https://github.com/python/typeshed/blob/master/stdlib/3/builtins.pyi#L692" rel="nofollow">type annotation for <code>next</code></a>. The <code>next</code> function is defined to have the following type signature:</p> <pre><code>@overload def next(i: Iterator[_T]) -&gt; _T: ... @ove...
1
2016-06-29T05:29:26Z
[ "python", "mypy" ]
Using python to separate sentences into paragraphs
38,090,137
<p>I need to use python to separate sentences into paragraphs for the video caption. I tried to use nltk.tokenize.texttiling but didn't get any results. Here the excerpt of the text:</p> <pre><code>– [Voiceover] Bob Dylan is, you must be 20 years old now, aren't you? – [Voiceover] Yeah, I must be 20. (laughing) â€...
-1
2016-06-29T03:58:59Z
38,090,959
<p>Seems pretty easy, you can use regex to do this, I did't know which format you want, but here is an example</p> <pre><code>import re sentence = """ – [Voiceover] Bob Dylan is, you must be 20 years old now, aren't you? – [Voiceover] Yeah, I must be 20. (laughing) – [Voiceover] Are you? – [Voiceover] Yeah, I...
0
2016-06-29T05:22:03Z
[ "python", "nltk", "paragraphs" ]
Django's geojson serializer outputs coordinates in the wrong order
38,090,247
<p>I am using the geojson serializer of Django but it is not getting the coordinates in the right order (according to the <a href="http://geojson.org/geojson-spec.html#positions" rel="nofollow">GeoJson spec</a>). Instead of (easting, northing) I get (latitude, longitude) and when I display the map I obviously get the w...
0
2016-06-29T04:13:38Z
38,512,894
<p>You get longitude and latitude in your geojson output because you seem to have the default srid 4326 chosen for the location field in your Places model. The GeoJSON Serializer also use 4326 as the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/gis/serializers/" rel="nofollow">default srid</a> when used. ...
0
2016-07-21T19:34:22Z
[ "python", "django", "geojson", "geodjango", "django-serializer" ]
Pass extra arguments to PyQt slot without losing default signal arguments
38,090,345
<p>A PyQt button event can be connected in the normal way to a function so that the function receives the default signal arguments (in this case the button checked state):</p> <pre><code>def connections(self): my_button.clicked.connect(self.on_button) def on_button(self, checked): print checked # prints "Tr...
2
2016-06-29T04:23:08Z
38,099,914
<p>Your <code>lambda</code> could take an argument:</p> <pre><code>def connections(self): my_button.clicked.connect(lambda checked: self.on_button(checked, 'hi')) def on_button(self, checked, message): print checked, message # prints "True, hi" </code></pre> <p>Or you could use <a href="https://docs.python...
4
2016-06-29T12:42:36Z
[ "python", "pyqt", "pyqt4" ]
bulk_insert_mappings sync model
38,090,375
<p>In a loop with bulk insert:</p> <pre><code>while condition: with transaction.manager: mapper = inspect(Foo) session.bulk_insert_mappings(mapper, foo_list) session.commit() </code></pre> <p>is the insert operation async or sync? I want to know when the loop is started for second time...
0
2016-06-29T04:25:59Z
38,093,685
<p>The fact that <code>commit()</code> is blocking or non-blocking is not handled by SQLAlchemy itself but by the SQL library you are using.</p> <p>The great majority of current SQL libraries are blocking, but there are some that are not, so I suggest you look at your SQL library's documentation.</p>
0
2016-06-29T08:01:21Z
[ "python", "sqlalchemy", "bulkinsert" ]
What is the simplest way to make matplotlib in OSX work in a virtual environment?
38,090,455
<p>I just discovered that <code>matplotlib</code> has issue with virtual environments. I tried the solutions in the <a href="http://matplotlib.org/faq/virtualenv_faq.html">FAQs</a> but they didn't work. An ideal solution should only involve <code>pip</code> commands, but it might be hard or unrealistic to request that....
13
2016-06-29T04:34:14Z
38,090,628
<p>sudo apt-get install tk-dev libpng-dev libffi-dev dvipng texlive-latex-base</p> <p>Then uninstalled and reinstalled matplotlib:</p> <p>pip uninstall matplotlib</p> <p>pip install matplotlib</p>
-2
2016-06-29T04:49:22Z
[ "python", "bash", "osx", "matplotlib" ]
What is the simplest way to make matplotlib in OSX work in a virtual environment?
38,090,455
<p>I just discovered that <code>matplotlib</code> has issue with virtual environments. I tried the solutions in the <a href="http://matplotlib.org/faq/virtualenv_faq.html">FAQs</a> but they didn't work. An ideal solution should only involve <code>pip</code> commands, but it might be hard or unrealistic to request that....
13
2016-06-29T04:34:14Z
38,155,726
<p>To get pyside working:</p> <pre><code>brew install cmake </code></pre> <p>brew is a pretty standard OSX dependency.</p> <p>You are right in identifying that this is a framework issue <a href="http://stackoverflow.com/questions/1444543/differences-between-framework-and-non-framework-builds-of-python-on-mac-os-x">D...
2
2016-07-02T01:44:38Z
[ "python", "bash", "osx", "matplotlib" ]
What is the simplest way to make matplotlib in OSX work in a virtual environment?
38,090,455
<p>I just discovered that <code>matplotlib</code> has issue with virtual environments. I tried the solutions in the <a href="http://matplotlib.org/faq/virtualenv_faq.html">FAQs</a> but they didn't work. An ideal solution should only involve <code>pip</code> commands, but it might be hard or unrealistic to request that....
13
2016-06-29T04:34:14Z
38,161,572
<p>As stated in the <a href="http://matplotlib.org/faq/virtualenv_faq.html#pythonhome-script" rel="nofollow">FAQS you reference</a>, you will need to create a <code>frameworkpython</code> scripts in <code>venv/bin</code>. It looks like your system is unable to find <code>frameworkpython</code> so it is either not on yo...
3
2016-07-02T15:15:20Z
[ "python", "bash", "osx", "matplotlib" ]
What is the simplest way to make matplotlib in OSX work in a virtual environment?
38,090,455
<p>I just discovered that <code>matplotlib</code> has issue with virtual environments. I tried the solutions in the <a href="http://matplotlib.org/faq/virtualenv_faq.html">FAQs</a> but they didn't work. An ideal solution should only involve <code>pip</code> commands, but it might be hard or unrealistic to request that....
13
2016-06-29T04:34:14Z
38,227,266
<p>Much like your setup, I am using <code>matplotlib</code> from within a virtual environment on OSX.</p> <p>I see that you have spent quite some effort to get things running and I am not certain whether or not this will actually solve your problem, since no two setups are the same. However, I drop my configuration su...
3
2016-07-06T14:59:23Z
[ "python", "bash", "osx", "matplotlib" ]
What is the simplest way to make matplotlib in OSX work in a virtual environment?
38,090,455
<p>I just discovered that <code>matplotlib</code> has issue with virtual environments. I tried the solutions in the <a href="http://matplotlib.org/faq/virtualenv_faq.html">FAQs</a> but they didn't work. An ideal solution should only involve <code>pip</code> commands, but it might be hard or unrealistic to request that....
13
2016-06-29T04:34:14Z
38,259,866
<p>Extending @Gator_Python's and @juanpa.arrivillaga's suggestions, I recommend installing the latest version of <a href="https://docs.continuum.io/anaconda/install#anaconda-for-os-x-graphical-install" rel="nofollow">anaconda</a>. It is a cross-platform, pip-like package manager that also handles virtual environments....
3
2016-07-08T06:01:45Z
[ "python", "bash", "osx", "matplotlib" ]
How do I determine input as an integer and the length, simultaneously?
38,090,588
<p>Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:</p> <pre><code>while True: try: nu...
0
2016-06-29T04:46:29Z
38,090,633
<p>You could try something like this in your try/except clause. Modify as necessary.</p> <pre><code>number_string = input("Please enter a (3 digit) number: ") number_int = int(number_string) number_length = len(number_string) if number_length == 3: break </code></pre> <p>You could also use an <code>assert</code> ...
1
2016-06-29T04:49:44Z
[ "python", "loops", "integer" ]
How do I determine input as an integer and the length, simultaneously?
38,090,588
<p>Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:</p> <pre><code>while True: try: nu...
0
2016-06-29T04:46:29Z
38,090,638
<p><code>input()</code> returns you a string. So you can first check the length of that number, and length is not 3 then you can ask the user again. If the length is 3 then you can use that string as a number by <code>int()</code>. <code>len()</code> gives you the length of the string.</p> <pre><code>while True: n...
0
2016-06-29T04:50:12Z
[ "python", "loops", "integer" ]
How do I determine input as an integer and the length, simultaneously?
38,090,588
<p>Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:</p> <pre><code>while True: try: nu...
0
2016-06-29T04:46:29Z
38,090,703
<p>Keep the input in a variable before casting it into an int to check its length:</p> <pre><code>my_input = input("Please enter a (3 digit) number: ") if len(my_input) != 3: raise ValueError() number = int(my_input) </code></pre> <p>Note that <code>except:</code> alone is a <a href="http://stackoverflow.com/ques...
0
2016-06-29T04:55:32Z
[ "python", "loops", "integer" ]
How do I determine input as an integer and the length, simultaneously?
38,090,588
<p>Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:</p> <pre><code>while True: try: nu...
0
2016-06-29T04:46:29Z
38,090,729
<pre><code>while True: inp = raw_input("Enter : ") length = len(inp) if(length!=3): raise ValueError num = int(inp) </code></pre> <p>In case you are using Python 2.x refrain from using <code>input</code>. Always use <code>raw_input</code>.</p> <p>If you are using Python 3.x it is fine.</p> ...
0
2016-06-29T04:58:28Z
[ "python", "loops", "integer" ]
How do I determine input as an integer and the length, simultaneously?
38,090,588
<p>Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:</p> <pre><code>while True: try: nu...
0
2016-06-29T04:46:29Z
38,090,780
<p>This should do it:</p> <pre><code>while True: try: string = input("Please enter a (3 digit) number: ") number = int(string) if len(string) != 3 or any(not c.isdigit() for c in string): raise ValueError() except ValueError: print('try again') else: brea...
0
2016-06-29T05:04:25Z
[ "python", "loops", "integer" ]
Python- Bar chart real time
38,090,620
<p>How can I create a bar/column chart in python using animation in real time ? I have made static bar graphs. Currently I have a program that feeds value from a machine to an excel file and my program should read that file in real time and plot a bar graph. I just want to look at patterns. It should update after every...
0
2016-06-29T04:48:48Z
38,091,193
<p>It looks like matplotlib.animation might meet your needs.</p> <p>Docs: <a href="http://matplotlib.org/examples/animation/" rel="nofollow">http://matplotlib.org/examples/animation/</a></p> <p>Tutorial: <a href="https://pythonprogramming.net/python-matplotlib-live-updating-graphs/" rel="nofollow">https://pythonprogr...
-1
2016-06-29T05:39:25Z
[ "javascript", "python", "animation", "real-time", "bar-chart" ]
Automatic email sending from a gmail account using script
38,090,643
<p>I need to send email with same content to 1 million users. Is there any way to do so by writing script or something? Email Id's are stored in Excel format.</p>
0
2016-06-29T04:50:27Z
38,090,686
<p>It is absolutely possible for a bot to be made that creates gmail accounts, in fact many already exist. The main problem is how to solve the captcha that is required for each new account, however there are services already built to handle this. The only problem then is being willing to violate googles terms of servi...
1
2016-06-29T04:54:23Z
[ "python", "python-2.7", "smtp" ]
Automatic email sending from a gmail account using script
38,090,643
<p>I need to send email with same content to 1 million users. Is there any way to do so by writing script or something? Email Id's are stored in Excel format.</p>
0
2016-06-29T04:50:27Z
38,090,883
<p>This link will help you to achieve what you wanted</p> <p><a href="http://naelshiab.com/tutorial-send-email-python/" rel="nofollow">http://naelshiab.com/tutorial-send-email-python/</a></p>
0
2016-06-29T05:15:53Z
[ "python", "python-2.7", "smtp" ]
Python Django templates - navigate to a file with physical path
38,090,692
<p>I have these files</p> <pre><code>root folder .... app ........ templates ............ app ................ index.html ................ js.js ... ... </code></pre> <p>and in the code, I want to be able to do something like this</p> <pre><code>&lt;script src="js.js"&gt;&lt;/script&gt; </code></pre> <p>and I have ...
-3
2016-06-29T04:54:44Z
38,090,753
<p>You need to put statically served files (IE JS,CSS,Images, etc) in your <a href="https://docs.djangoproject.com/en/1.9/howto/static-files/" rel="nofollow">static folder</a></p> <p>You can also <a href="https://docs.djangoproject.com/en/1.9/howto/static-files/#deployment" rel="nofollow">change the root path for your...
2
2016-06-29T05:01:08Z
[ "python", "html", "django", "jinja2" ]
TypeError: 'dict' object does not support indexing thrown on second instance of this query
38,090,730
<p>So I am building a query based on user input in flask with this code:</p> <pre><code> if empty_indic_form.validate_on_submit(): query='select name, year, value, display_name from literal inner join ent on ent_id=ent.id where display_name in (' for i in indic_form.indicators.data: query=query+'\''...
-1
2016-06-29T04:58:46Z
38,091,485
<p>The fundamental error in your method is using string concatenation to build an SQL query. If <code>indic_form.indicators.data</code> or <code>order_c</code> is user provided data, for example from an HTTP request, you've probably opened yourself up for <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofol...
2
2016-06-29T06:01:57Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy", "psycopg" ]
What are the initial estimates taken in Logistic regression in Scikit-learn for the first iteration?
38,090,810
<p>I am trying out logistic regression from scratch in python.(through finding probability estimates,cost function,applying gradient descent for increasing the maximum likelihood).But I have a confusion regarding which estimates should I take for the first iteration process.I took all the estimates as 0(including the i...
0
2016-06-29T05:07:56Z
38,105,051
<p>First of all scikit learn's LogsiticRegerssion uses <strong>regularization</strong>. So unless you apply that too , it is unlikely you will get exactly the same estimates. if you really want to test your method versus scikit's , it is better to use their gradient decent implementation of Logistic regersion which is ...
1
2016-06-29T16:15:10Z
[ "python", "machine-learning", "scikit-learn", "logistic-regression" ]
Insert into python list. Check if entry still exists
38,090,874
<p>I have many equal URL's with and without 'www'. My csv file looks like that:</p> <pre><code>www.first.com first.com www.second.com second.com www.third.eu third.eu forth.tr fifth.com ...` </code></pre> <p>I iterate over the list, fetch the ip address and insert them into a dict. How can I remove (or check before i...
0
2016-06-29T05:14:53Z
38,090,950
<p>You can test if it's in the dictionary by doing </p> <pre><code>url = url.replace("www.","") url = url.replace("http://","") url = url.split("/")[0] if url in my_dict: pass else: my_dict[url] = ip_address </code></pre>
0
2016-06-29T05:21:13Z
[ "python" ]
Insert into python list. Check if entry still exists
38,090,874
<p>I have many equal URL's with and without 'www'. My csv file looks like that:</p> <pre><code>www.first.com first.com www.second.com second.com www.third.eu third.eu forth.tr fifth.com ...` </code></pre> <p>I iterate over the list, fetch the ip address and insert them into a dict. How can I remove (or check before i...
0
2016-06-29T05:14:53Z
38,091,006
<p>First you want to remove the 'www' if there is one. Then you can check if it's in the dictionary using "if address in dict:". That is:</p> <pre><code>with open('myfile.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=' ') result = [] for row in reader: addr = socket.gethostbynam...
1
2016-06-29T05:25:08Z
[ "python" ]
Insert into python list. Check if entry still exists
38,090,874
<p>I have many equal URL's with and without 'www'. My csv file looks like that:</p> <pre><code>www.first.com first.com www.second.com second.com www.third.eu third.eu forth.tr fifth.com ...` </code></pre> <p>I iterate over the list, fetch the ip address and insert them into a dict. How can I remove (or check before i...
0
2016-06-29T05:14:53Z
38,091,012
<p>Why do you have a list of dictionaries containing a single item? Why not just use one dictionary? It would look like this with the first two entries:</p> <pre><code>url_dict = {'first.com':'192.168.31.101', 'second.com':'192.168.31.102'} </code></pre> <p>If you wish to check if a url containing www is already in...
0
2016-06-29T05:25:46Z
[ "python" ]
Insert into python list. Check if entry still exists
38,090,874
<p>I have many equal URL's with and without 'www'. My csv file looks like that:</p> <pre><code>www.first.com first.com www.second.com second.com www.third.eu third.eu forth.tr fifth.com ...` </code></pre> <p>I iterate over the list, fetch the ip address and insert them into a dict. How can I remove (or check before i...
0
2016-06-29T05:14:53Z
38,091,016
<p>Use a set to determine if an IP address has not been seen before. If the address is unknown, add it to the set and store the record.</p> <p>And strip the 'www.' from the url if you want to store the base url.</p> <pre><code>adresses = set() for row in reader: addr = socket.gethostbyname(row[0]) if addr not...
3
2016-06-29T05:26:16Z
[ "python" ]
Insert into python list. Check if entry still exists
38,090,874
<p>I have many equal URL's with and without 'www'. My csv file looks like that:</p> <pre><code>www.first.com first.com www.second.com second.com www.third.eu third.eu forth.tr fifth.com ...` </code></pre> <p>I iterate over the list, fetch the ip address and insert them into a dict. How can I remove (or check before i...
0
2016-06-29T05:14:53Z
38,091,411
<p>Using list comprehensions: ( the inner loop will iterate once every outer iteration to replace the 'www' )</p> <pre><code> with open('myfile.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=' ') result = {h: socket.gethostbyname(h) for w in reader (w.replace('www.', '') for w in h) if re...
0
2016-06-29T05:56:32Z
[ "python" ]
Insert into python list. Check if entry still exists
38,090,874
<p>I have many equal URL's with and without 'www'. My csv file looks like that:</p> <pre><code>www.first.com first.com www.second.com second.com www.third.eu third.eu forth.tr fifth.com ...` </code></pre> <p>I iterate over the list, fetch the ip address and insert them into a dict. How can I remove (or check before i...
0
2016-06-29T05:14:53Z
38,092,454
<p>Is there any reason to have all those 'entry' keys?</p> <p>It's more reasonable to have such dictionary:</p> <pre><code>entry = {'url': 'ip'} </code></pre> <p>Then your code could be:</p> <pre><code>import csv import socket with open('myfile.csv', 'r') as csvfile: reader = csv.reader(csvfile, delimiter=' ')...
0
2016-06-29T06:58:56Z
[ "python" ]
Fabric: hide stdout for remote jobs, but only show a 'grep'ed line
38,091,090
<p>I want to show stdout for my local program, which uses fabric to run two remote programs. I want to hide the stdout for the two remote programs. (I know there is a hide output option). However, I do want to show one of the print statements (can be grepped) from one of the two remote programs.</p> <p>How can I do th...
0
2016-06-29T05:31:59Z
38,113,934
<p>You can assign the grepped output to a variable then print the shortened output</p> <p>like this:</p> <pre><code>content = sudo('git status | sed -n 2p | grep -w "Your branch is up-to-date"') print (content) </code></pre> <p>Hope it helps !!</p>
3
2016-06-30T04:20:16Z
[ "python", "process", "multiprocessing", "fabric" ]
GeneratorExit, close() does not cause a traceback/exception - how?
38,091,111
<pre><code>def receiver(): print("Ready to receive") # try: while True: n = (yield) print("Got %s" % n) # except GeneratorExit: # print("Receiver done") r = receiver() r.next() r.send(10) r.close() </code></pre> <p>When I comment out the <code>GeneratorExit</code>, the <code>clo...
4
2016-06-29T05:33:22Z
38,093,384
<p>See <a href="https://docs.python.org/2/reference/expressions.html#generator.close" rel="nofollow">generator.close() documentation</a>.</p> <p>It is stated that <code>StopIteration</code> and <code>GeneratorExit</code> exceptions are use internally to dictate how the generator exits, and thus are the only exceptions...
3
2016-06-29T07:46:36Z
[ "python" ]
AttributeError: type object 'Robot' has no attribute 'repr' type object 'Robot' has no attribute 'str'
38,091,335
<pre><code>class Robot: """this is a Robot class is used to declare a Robot""" def __init__(self,name="tallapalli",build_yr=1990): """this method is use to intialize the data to the class variable""" self.name=name self.build_yr=build_yr def hello(self): """this is a mmethod ...
-1
2016-06-29T05:50:39Z
38,091,358
<p><code>__repr__</code> and <code>__str__</code> are special methods, that are normally triggered by <code>repr</code> and <code>str</code> in a function-call manner. </p> <pre><code>z=Robot("nageswara rao",1991) str(z) repr(z) </code></pre> <p>Or if you want to call the methods from the class, you must use their f...
0
2016-06-29T05:52:21Z
[ "python", "python-3.x" ]
How to drop rows not containing string type in a column in Pandas?
38,091,444
<p>I have a csv file with four columns. I read it like this:</p> <pre><code>df = pd.read_csv('my.csv', error_bad_lines=False, sep='\t', header=None, names=['A', 'B', 'C', 'D']) </code></pre> <p>Now, field <code>C</code> contains string values. But in some rows there are non-string type (floats or numbers) values. How...
2
2016-06-29T05:59:19Z
38,091,490
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <code>mask</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric</code></a> with p...
2
2016-06-29T06:02:32Z
[ "python", "string", "python-2.7", "pandas", "dataframe" ]
How to drop rows not containing string type in a column in Pandas?
38,091,444
<p>I have a csv file with four columns. I read it like this:</p> <pre><code>df = pd.read_csv('my.csv', error_bad_lines=False, sep='\t', header=None, names=['A', 'B', 'C', 'D']) </code></pre> <p>Now, field <code>C</code> contains string values. But in some rows there are non-string type (floats or numbers) values. How...
2
2016-06-29T05:59:19Z
38,091,596
<h3>Setup</h3> <pre><code>df = pd.DataFrame([['a', 'b', 'c', 'd'], ['e', 'f', 1.2, 'g']], columns=list('ABCD')) print df A B C D 0 a b c d 1 e f 1.2 g </code></pre> <p>Notice you can see what the individual cell types are.</p> <pre><code>print type(df.loc[0, 'C']), type(df.loc[1, 'C']) &lt;type '...
2
2016-06-29T06:09:53Z
[ "python", "string", "python-2.7", "pandas", "dataframe" ]
converting a set of strings to a json in python
38,091,525
<p>I am currently working on setting up a flask server for my front end. The request I get is in the form the following JSON object:</p> <pre><code>InputJson = {"text":"Field1:A|Field2:B|Field3:C","format":"Reader"} </code></pre> <p>I would like to convert the text field to a proper JSON:</p> <pre><code>OutputJson =...
0
2016-06-29T06:05:03Z
38,091,566
<p>You can split your string on "|", then split each part on ":", feeding the pairs into a dict:</p> <pre><code>output = dict( keyvalue.split(':') for keyvalue in orig_value.split('|') ) </code></pre> <p>You don't need to use any json-parsing tools for that, because the format of the string you're parsing has nothing...
4
2016-06-29T06:07:50Z
[ "python", "json", "dictionary", "split" ]
Update Google Drive file download, print and copy option via Python Django Storage
38,091,620
<p>I want to update <code>DOWNLOAD, PRINT, COPY</code> option for google drive files using <code>django.core.files.storage</code>. While adding a file to drive with body parameter, I am able to update this option using following body parameter.</p> <pre><code>body = { 'title': name, 'mimeType':...
0
2016-06-29T06:11:09Z
38,093,899
<p>Got it worked useing Updates file metadata and/or content API in Google Drive API <a href="https://developers.google.com/drive/v2/reference/files/update" rel="nofollow">reference</a></p> <h3>Sample Code:</h3> <pre><code>body = { 'labels': {'restricted': True} } self._drive_service.files...
0
2016-06-29T08:12:11Z
[ "python", "django", "google-drive-sdk" ]
Need help converting a list to a string
38,091,674
<p>The function here just generates a random list of 0s and 1s. It's for later use in a game. So I need to take the list generated by binary_gen and convert it to a string. I've tried using .join but I just get an error message back. Is there any way for me to convert the output from binary_gen to a string? Or is ...
0
2016-06-29T06:14:38Z
38,091,745
<pre><code>import random def random_binary(min_length=4, max_length=8): size = random.randint(min_length, max_length) return ''.join(str(random.randint(0, 1)) for _ in range(size)) print(random_binary()) </code></pre> <p>My guess is that the error you got was something like <code>TypeError: sequence item...
1
2016-06-29T06:19:43Z
[ "python", "python-3.x" ]
Need help converting a list to a string
38,091,674
<p>The function here just generates a random list of 0s and 1s. It's for later use in a game. So I need to take the list generated by binary_gen and convert it to a string. I've tried using .join but I just get an error message back. Is there any way for me to convert the output from binary_gen to a string? Or is ...
0
2016-06-29T06:14:38Z
38,091,788
<p>To generate a random string sequence of zeroes and ones of random length from 4 to 8:</p> <pre><code>&gt;&gt;&gt; from random import randint &gt;&gt;&gt; ''.join(str(randint(0, 1)) for i in range(randint(4, 8))) '0010111' </code></pre> <p>Or, more directly:</p> <pre><code>&gt;&gt;&gt; from random import choice, r...
2
2016-06-29T06:22:28Z
[ "python", "python-3.x" ]
Need help converting a list to a string
38,091,674
<p>The function here just generates a random list of 0s and 1s. It's for later use in a game. So I need to take the list generated by binary_gen and convert it to a string. I've tried using .join but I just get an error message back. Is there any way for me to convert the output from binary_gen to a string? Or is ...
0
2016-06-29T06:14:38Z
38,091,809
<p>Please try following:</p> <pre><code>import random def random_binary(): min_length = 4 max_length = 8 binary_gen = [random.randrange(0,2,1) for _ in range \ (random.randint(min_length,max_length))] _str = '' for i in binary_gen: _str += str(i) return _str def count_zeros(s): ...
1
2016-06-29T06:23:46Z
[ "python", "python-3.x" ]
Efficient GROUP BY query on numpy recarray
38,091,849
<p>I have a dataset of product purchases logs with 6 columns: <strong>purchase_date, user_address, user_id, product_id, brand_id, retailer_id</strong>. All contain integers, except user_address which is a string.</p> <p>I need to get the top 5 brands selling the most items over the whole dataset, i.e. the ones having...
0
2016-06-29T06:25:57Z
38,106,634
<p>While the nominated duplicate <a href="http://stackoverflow.com/questions/10741346/numpy-most-efficient-frequency-counts-for-unique-values-in-an-array">numpy: most efficient frequency counts for unique values in an array</a> is relevant, I think it ignores some important issues in this code. The accepted answer, <c...
0
2016-06-29T17:41:01Z
[ "python", "numpy", "querying", "recarray" ]
How to access variables in other classes
38,092,165
<p>In Functions class, I would like to access the variable of the Frame class.</p> <p>Please tell me if there is any way.</p> <pre><code>class Functions(): def changeText(): ... ... I want to change the 'text' in the Frame class ex )Frame.text.SetFont('change text') </code></pre...
0
2016-06-29T06:44:43Z
38,092,945
<p>You can do this by sending an instance of the class to the function:</p> <pre><code>class myClass(object): def __init__(self, text): self.text = text def changeText(input): input.text = "world" example = myClass("hello") changeText(example) </code></pre>
0
2016-06-29T07:23:31Z
[ "python", "wxpython" ]
How to access variables in other classes
38,092,165
<p>In Functions class, I would like to access the variable of the Frame class.</p> <p>Please tell me if there is any way.</p> <pre><code>class Functions(): def changeText(): ... ... I want to change the 'text' in the Frame class ex )Frame.text.SetFont('change text') </code></pre...
0
2016-06-29T06:44:43Z
38,118,866
<p>You will have to tell your objects what to work on. Out of thin air your <code>Functions</code> instance will not know (how should it?) what <code>Frame</code> should be. You could make <code>Frame</code> a global, but I do not think that is a good idea (it will break if you want to work with more than one frame ins...
0
2016-06-30T09:21:34Z
[ "python", "wxpython" ]
django-datatable default iDisplayLength
38,092,232
<p>I am using <a href="https://github.com/shymonk/django-datatable" rel="nofollow">https://github.com/shymonk/django-datatable</a> for a table.</p> <p>By default, it would display only 10 records, and there is a Length Menu to choose a different number.</p> <p>I see in the Ajax call that it asks for <code>iDisplayLen...
0
2016-06-29T06:47:27Z
38,092,821
<p>I can see from their source code: <a href="https://github.com/shymonk/django-datatable/blob/master/table/tables.py#L130" rel="nofollow">class TableOptions</a> which is used for <a href="https://github.com/shymonk/django-datatable/blob/master/table/tables.py#L201" rel="nofollow">meta options</a> and can be accessed f...
1
2016-06-29T07:16:44Z
[ "jquery", "python", "django", "datatable" ]
Why configuring width of Frame shows differences from Label's?
38,092,236
<p>(windows 7, python 2.7.3)</p> <p>Here is my code:</p> <pre><code>from Tkinter import * root = Tk() root.geometry('400x400') Frame(root, width=20, height=20, bg='red').pack(expand=NO, fill=None, side=LEFT) Label(root, width=20, height=20, bg='black').pack(expand=NO, fill=None, side=LEFT) root.mainloop() </code></p...
1
2016-06-29T06:47:39Z
38,093,174
<p>As I know Label is used for text. Label() definition and Frame() might work differently for width and height parameters, correct me if am wrong. </p> <p>example: change width and height inside Label() to 1. you will see space for one character filled with black color in tk window.</p> <p>like </p> <p><code>Label(...
1
2016-06-29T07:35:44Z
[ "python", "tkinter", "label", "frame" ]
Why configuring width of Frame shows differences from Label's?
38,092,236
<p>(windows 7, python 2.7.3)</p> <p>Here is my code:</p> <pre><code>from Tkinter import * root = Tk() root.geometry('400x400') Frame(root, width=20, height=20, bg='red').pack(expand=NO, fill=None, side=LEFT) Label(root, width=20, height=20, bg='black').pack(expand=NO, fill=None, side=LEFT) root.mainloop() </code></p...
1
2016-06-29T06:47:39Z
38,093,779
<p><strong>Short answer:</strong></p> <p>20 is the same as 20, but 20 meters is not the same as 20 kilometers.</p> <p><strong>Long answer:</strong></p> <p>The result you got is not as weird as you may think because the <code>width</code> and <code>height</code> options of <code>Tkinter.Frame()</code> are measured in...
2
2016-06-29T08:06:11Z
[ "python", "tkinter", "label", "frame" ]
Tab over non-editable cells in QtableView
38,092,251
<p>I am using PYQT5. I have a QtableView widget which I use for quick data entry similar to a spreadsheet. Some columns are editable while others (labels etc) are not. I have achieved this quite simply by subclassing QItemDelegate.</p> <p>What I would like to do is when a user tabs from an editable cell, it will ski...
2
2016-06-29T06:48:18Z
38,219,150
<p>After sweating over this for days, the answer is that you can successfully reimplement QsqlTableModel. Here is how I arrived at the answer.</p> <p>First I saw recommendations on the net mostly in the QT forums for C++ that you should reimplement QsqlQueryModel instead of QsqlTableModel. But then you have to creat...
0
2016-07-06T08:10:00Z
[ "python", "qt", "pyqt", "pyqt5" ]
vim install error about python2.7 on ubuntu precise 64
38,092,511
<p>I'm trying to install vim on a "vagrant precise 64 VM" but I have the following error message :</p> <pre><code>vagrant@precise64:/vagrant/chef-repo$ sudo apt-get install vim Reading package lists... Done Building dependency tree Reading state information... Done The following extra packages will be installed: lib...
0
2016-06-29T07:01:32Z
38,092,706
<p>That's a newbie mistake !</p> <p>I just only need doing a "sudo apt-get update" to solve the problem. It was clearly mentionned at the end of the error message.</p>
0
2016-06-29T07:11:16Z
[ "python", "ubuntu", "vim" ]
Can not draw more than 8 nodes by networkx raising `NetworkXError: Node 8 has no position` error
38,092,927
<p>I'm trying to draw graph by networkx. However, the below code suffers the error that is </p> <blockquote> <p>NetworkXError: Node 8 has no position</p> </blockquote> <p>I believe only less than seven nodes are allowed, but I can not understand why.</p> <p>Please suggest why the error happens and how to fix to dr...
0
2016-06-29T07:22:45Z
38,093,719
<p><code>nx.cubical_graph()</code> has 8 nodes. Namely <code>[0,1,2,3,4,5,6,7]</code>. You have sent a <code>nodelist</code> that includes node <code>8</code> which is not part of your graph. The graph you are drawing is the graph of a cube - 8 nodes (the vertices) and 12 edges (the edges of the cube). </p> <p>You...
0
2016-06-29T08:03:08Z
[ "python", "networkx" ]
flexible query based on two numpy arrays
38,092,951
<p>I would like to create a somewhat dynamical query based on numpy array. Ideally, the indices of one array (<code>uu</code>) should be returned, given the conditions for each column in a second array (<code>cond</code>).</p> <p>The sample below demonstrates what I have in mind, and it works using a loop. I am wonder...
0
2016-06-29T07:23:43Z
38,095,540
<p>Numpy allows to compare arrays directly:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # just making my own uu with random numbers n = 101 uu = np.random.rand(n,4) # then if you have an array or a list of values... cond = [.2,.5,.7,.8] # ... you can directly compare the array to it compar...
0
2016-06-29T09:27:06Z
[ "python", "arrays", "numpy", "filtering" ]
Django urls not taking arguments
38,092,978
<p>I am really having hard time to understand ways to dispatch arguments and keword arguments to Django urls. Following is the case study:</p> <p>I've a view using generic base view:</p> <pre><code>class CartView(View): def get(self, request, *args, **kwargs): item = request.GET.get('item') qty = req...
2
2016-06-29T07:24:58Z
38,094,114
<blockquote> <p>404 Page Not Found</p> <p>No Variation matches the given query.</p> </blockquote> <p>This message comes from your line:</p> <pre><code>item_instance = get_object_or_404(Variation, id=item_id) </code></pre> <p>And means that you have no <code>Variation</code> object matching the given <code>id<...
2
2016-06-29T08:23:42Z
[ "python", "django", "django-urls" ]
Python: Pandas dataframe sum
38,093,218
<p>I try to learn how to work with pandas dataframes. My dataframe has 4 columns A,B,C,D.</p> <p>For index (A,B,C) there are multiple values of D. I want to merge these rows and sum the values of D.</p> <p>I have:</p> <pre><code>╔═══╦═══╦═══╦═══╦═══╗ ║ ║ A ║ B ║ C ...
1
2016-06-29T07:38:29Z
38,093,411
<p>If you want to retain the columns after <code>groupby</code> you can call <code>reset_index</code>:</p> <pre><code>In [185]: df.groupby(['A','B','C'])['D'].sum().reset_index() Out[185]: A B C D 0 1 2 3 8 1 1 2 4 7 2 1 5 4 2 </code></pre> <p>or pass arg <code>as_index=False</code></p>
1
2016-06-29T07:47:56Z
[ "python", "pandas", "dataframe", "group-by" ]
Whats the difference between 'rb' and 'rU' in the open() function for csv
38,093,326
<p>I was wondering what the difference between:</p> <pre><code>with codecs.open('xxxx.csv', 'rU') as h: </code></pre> <p>and</p> <pre><code>with codecs.open('xxxx.csv', 'rb') as h: </code></pre> <p>I think I remember someone saying you should use '<strong>rb</strong>' and not '<strong>rU</strong>' when I started my...
-2
2016-06-29T07:44:05Z
38,093,783
<p>As <a href="https://docs.python.org/3.5/library/functions.html#open" rel="nofollow">the documentation</a> states, <code>U</code> (Universal Newlines) mode is deprecated; you should not use it anymore. Instead use the <code>newline=</code> keyword argument.</p> <p><a href="https://docs.python.org/3.5/library/csv.htm...
2
2016-06-29T08:06:17Z
[ "python", "python-3.x", "csv" ]
Transposing the data in python
38,093,334
<p>My Data looks something like this</p> <pre> cust c1 p1 c2 p2 c3 p3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 </pre> <p>I want to transpose this data and return in below format:</p> <pre> cust c p 1 2 3 1 4 5 1 6 7 8 9 10 8 11 12 8 13 14 </pre> <p>Please Can someone suggest what to use? ...
1
2016-06-29T07:44:23Z
38,093,474
<p>You can use function <code>lreshape</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>:</p> <pre><code>print (pd.lreshape(df, {'c': ['c1', 'c2', 'c3'], 'p': ['p1', 'p2', 'p3']}) .sort_values('cust')) ...
2
2016-06-29T07:50:44Z
[ "python", "python-2.7", "python-3.x", "numpy", "pandas" ]
Transposing the data in python
38,093,334
<p>My Data looks something like this</p> <pre> cust c1 p1 c2 p2 c3 p3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 </pre> <p>I want to transpose this data and return in below format:</p> <pre> cust c p 1 2 3 1 4 5 1 6 7 8 9 10 8 11 12 8 13 14 </pre> <p>Please Can someone suggest what to use? ...
1
2016-06-29T07:44:23Z
38,093,807
<p>If you get the data in a list, you can use csv.</p> <pre><code>import csv f = open('name.csv','wb') csv = csv.reader(f,delimiter=';') csv.writerow([list[0]]+[list[1]]+...) </code></pre>
0
2016-06-29T08:07:17Z
[ "python", "python-2.7", "python-3.x", "numpy", "pandas" ]
for listing, 'int' object is not iterable in python
38,093,337
<p>it keeps returning me the error 'int' object is not iterable. Any solution?</p> <pre><code>def calculate_average_sales(employee_list): for e in employee_list: average = sum(e.sales)/len(e.sales) print("Average sales of all employees: ",average) print(calculate_average_sales(employee_list)) </code><...
-2
2016-06-29T07:44:30Z
38,093,563
<p>You're calling <code>sum</code> on an <code>int</code>, but the signature of <code>sum</code> requires it take an iterable as first argument:</p> <pre><code>sum(e.sales) # ??? </code></pre> <p>If you tried to call <code>sum</code> on, say <code>3</code> it'll raise the same exception:</p> <pre><code>&gt;&gt;&gt; ...
0
2016-06-29T07:55:08Z
[ "python" ]
for listing, 'int' object is not iterable in python
38,093,337
<p>it keeps returning me the error 'int' object is not iterable. Any solution?</p> <pre><code>def calculate_average_sales(employee_list): for e in employee_list: average = sum(e.sales)/len(e.sales) print("Average sales of all employees: ",average) print(calculate_average_sales(employee_list)) </code><...
-2
2016-06-29T07:44:30Z
38,094,567
<p>It's very dificult to enswere hance you didn't post the code on employee_list.</p> <p>in the nats shell , you try to itarate on an int - so if i have to guss the code is somthing like </p> <pre><code>for e in 120: #you wanted to put here some list , but you actualy send numbers do something... </code></pre> <...
0
2016-06-29T08:46:52Z
[ "python" ]
How to manage concurrent LMDB writes in Python?
38,093,351
<p>I know LMDB does not support concurrent writes.</p> <p>I have an application where concurrent write attempts are very rare, but they may occasionally happen. How should this be managed in a Python application?</p> <p>Specifically:</p> <ul> <li><p>does a concurrent write attempt raise an exception in the Python LM...
0
2016-06-29T07:45:16Z
39,633,808
<p>According to lmdb documentation lmdb handles the concurrent writes. When multiple read_write transactions are opened at once.Except the active write transaction Lmdb makes all the other write transaction to wait until the current active write commits. Thus it handles concurrent writes.</p>
0
2016-09-22T08:21:01Z
[ "python", "python-2.7", "concurrency", "lmdb" ]
Python 2.7 regular expression match issue
38,093,361
<p>Suppose I am using the following regular expression to match, logically the regular expression means match anything with prefix <code>foo:</code> and ends with <strong>anything</strong> which is not a space. Match group will be the parts exclude prefix <code>foo</code></p> <p>My question is what exactly means <stro...
-2
2016-06-29T07:45:55Z
38,093,551
<p>Try:</p> <pre><code>a = re.compile('foo:\S*') </code></pre> <p>\S means anything but whitespace.</p> <p>I recommend you check out <a href="http://pythex.org" rel="nofollow">http://pythex.org</a>. It's really good for testing out regular expresions and has a decent cheat-sheet.</p> <p><strong>UPDATE:</strong></p...
2
2016-06-29T07:54:44Z
[ "python", "regex", "python-2.7" ]
Python 2.7 regular expression match issue
38,093,361
<p>Suppose I am using the following regular expression to match, logically the regular expression means match anything with prefix <code>foo:</code> and ends with <strong>anything</strong> which is not a space. Match group will be the parts exclude prefix <code>foo</code></p> <p>My question is what exactly means <stro...
-2
2016-06-29T07:45:55Z
38,093,652
<p>The regular expression metacharacter which matches any character is <code>.</code> (dot).</p> <pre><code>a = re.compile('foo:(.+)') </code></pre> <p>The character class <code>[^ ]</code> matches any one character which isn't one of the characters between the square brackets (a literal space, in this example). The...
1
2016-06-29T07:59:32Z
[ "python", "regex", "python-2.7" ]
ValueError when apply function to data frame in python-pandas
38,093,398
<p>Let's say I have a very simple data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame(np.full((6), 1)) </code></pre> <p>Now I am going to define a function that generate a numpy array with random length and add the given value to the tail:</p> <pre><code>import numpy as np def func(row): l = np.full...
1
2016-06-29T07:47:13Z
38,093,626
<p>Firstly you want <code>np.random.random_integers</code>, secondly <code>hstack</code> takes a tuple so pass a tuple, thirdly you need to return something that it can align with so in this case a <code>Series</code>:</p> <pre><code>In [213]: df = pd.DataFrame(np.full((6), 1)) def func(row): l = np.full((np.rando...
1
2016-06-29T07:58:04Z
[ "python", "numpy", "pandas", "dataframe" ]
Connecting to Amazon SQS using boto
38,093,422
<p>I am trying to connect to a Amazon SQS via the python boto library.</p> <pre><code>import boto3 sqs= boto3.resource('sqs') for queue in sqs.queues.all(): print(queue.url) </code></pre> <p>I have stored my credentials on the ~/.aws/credentials file </p> <pre><code>[default] aws_access_key_id=XXX aws_secret_ac...
0
2016-06-29T07:48:25Z
38,093,750
<p>Are you sure your user have <code>SQS</code> permission granted ?</p> <p>Go to <em>IAM</em> services, select your user (the one you use from your CLI) and check the group/permission attached to your user.</p> <p>If you don't have, you can search for <code>SQS</code> in the "Search IAM" box (top left)</p> <p><a hr...
3
2016-06-29T08:04:48Z
[ "python", "amazon-web-services", "amazon-sqs", "boto3" ]
Connecting to Amazon SQS using boto
38,093,422
<p>I am trying to connect to a Amazon SQS via the python boto library.</p> <pre><code>import boto3 sqs= boto3.resource('sqs') for queue in sqs.queues.all(): print(queue.url) </code></pre> <p>I have stored my credentials on the ~/.aws/credentials file </p> <pre><code>[default] aws_access_key_id=XXX aws_secret_ac...
0
2016-06-29T07:48:25Z
38,342,229
<p>I ended up using the previous version of Boto (2)</p>
0
2016-07-13T03:30:44Z
[ "python", "amazon-web-services", "amazon-sqs", "boto3" ]
How are signals and KeyboardInterrupt handled in Python?
38,093,522
<p>I have two Python scripts <code>foo.py</code> and <code>bar.py</code>, <code>foo.py</code> will call <code>bar.py</code> via <code>os.system()</code>.</p> <pre><code>#foo.py import os print os.getpid() os.system("python dir/bar.py") </code></pre> <pre><code>#bar.py import time time.sleep(10) print "over" </cod...
0
2016-06-29T07:53:28Z
38,143,986
<p>Let's consider each case in turn:</p> <blockquote> <p>if I type <code>kill 123</code>, the sub-process will not be affected.</p> </blockquote> <p>Yes, that's how <code>kill [pid]</code> works. It sends a signal only to the process you want to kill. If you want to send the signal to an group of processes, then y...
1
2016-07-01T11:13:31Z
[ "python", "multithreading", "process", "signals", "interrupt" ]
Double graph with matplotlib: Attribute error
38,093,600
<p>I have got a pandas dataframe like this: </p> <pre><code>nan 0 ingredient contribution count 0 0.0 cracker 0.088844873 11 1 2.0 water 0.044386494 125 2 3.0 oil 0.034567456 10 3 4.0 flour 0.030855063 186 ... </code></pre> <p>I would like to c...
1
2016-06-29T07:57:10Z
38,093,797
<p>One possible solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.bar.html" rel="nofollow"><code>Series.plot.bar</code></a>:</p> <pre><code>plt.figure(1) #creating empty figure df.set_index('ingredient', inplace=True) #set index from column ingredient fig_contr = df[...
1
2016-06-29T08:06:55Z
[ "python", "pandas", "matplotlib" ]
python crontab makec freezed
38,093,639
<p>I'm writing a test script using python I have a 'makec 'command in my script. I set up crontab to run my script every hour, here's the crontab command i use( all in one line)</p> <pre><code>20 * * * * cd /project/work/account/auto_test/ ; /project/tools/bin/python3 /project/work/lichuan/auto_test/revision.py ...
0
2016-06-29T07:58:45Z
38,117,136
<p>Anyway I figure it out. We may learn from the other webs that we need absolute path for configure files. Same applies to command. After I give abs path to my makec command e.g: </p> <pre><code>/tools/bin/makec ----options </code></pre> <p>Everything works.</p>
0
2016-06-30T07:56:21Z
[ "python", "crontab" ]
Python dimension mismatch for multiplication
38,093,693
<p>I have a few variables listed below. How come I receive the error message at the bottom when I try to run this block of code? <code>Ind_var[i,:]</code> should be of shape (1,2) so by matrix multiplication (1,2) * (2,2) is (1,2)? Sorry I'm new to python. </p> <pre><code>import numpy as np spread_len = 10 n_param = ...
-1
2016-06-29T08:01:43Z
38,093,796
<p>You need to transpose the second ind_var[i,:] to get a (2,1) shape, otherwise you're spanning a new (2,2) matrix which doesn't fit into Q[i] which is shape (1).</p> <p>Also R and ind_var need to be matrices, not arrays, for matrix math:</p> <pre><code>import numpy as np spread_len = 10 n_param = 2 Q = np.zeros((s...
0
2016-06-29T08:06:54Z
[ "python", "arrays", "numpy", "dimension" ]
Python dimension mismatch for multiplication
38,093,693
<p>I have a few variables listed below. How come I receive the error message at the bottom when I try to run this block of code? <code>Ind_var[i,:]</code> should be of shape (1,2) so by matrix multiplication (1,2) * (2,2) is (1,2)? Sorry I'm new to python. </p> <pre><code>import numpy as np spread_len = 10 n_param = ...
-1
2016-06-29T08:01:43Z
38,107,774
<p>In your example:</p> <pre><code>In [970]: ind_var.shape Out[970]: (10, 2) In [971]: R.shape Out[971]: (2, 2) In [972]: ind_var[0,:]*R*ind_var[0,:]+Ve Out[972]: array([[ 0.001, 0.001], [ 0.001, 0.001]]) </code></pre> <p>For arrays, the <code>*</code> multiplication is element by element, like MATLAB <co...
0
2016-06-29T18:46:03Z
[ "python", "arrays", "numpy", "dimension" ]
How to find a row ID or column ID in smartsheet?
38,093,751
<p>I've been working with and reading the smartsheet API for a few hours now and I notice that in all the requests I have to make, I will need either a row ID or a column ID. I must be missing something easy here, but where do I find these IDs? Are they found through a query or somewhere on the actual view-able sheet?<...
1
2016-06-29T08:04:49Z
38,103,240
<p>If you execute the <a href="http://smartsheet-platform.github.io/api-docs/?python#get-sheet" rel="nofollow">Get Sheet</a> operation, the response will be a <a href="http://smartsheet-platform.github.io/api-docs/?python#sheet-object" rel="nofollow">Sheet object</a> that contains (amongst other things), a collection o...
2
2016-06-29T14:56:42Z
[ "python", "python-requests", "smartsheet-api" ]
Group by with min
38,093,965
<p>I have a dataframe and I get the following:</p> <pre><code> index1 index2 results 0 0 0 8.605016 1 0 1 8.600410 2 0 2 8.585075 3 1 0 8.550355 4 1 1 8.557221 5 1 2 8.557640 6 2 0 4.360486 7 2 1 4.362304 8 ...
-3
2016-06-29T08:15:39Z
38,094,032
<p>My solution works, if <code>groupby</code> only but <code>index1</code> - then you get desired output.</p> <p>You need first <code>indexes</code> of values with <code>min</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.idxmin.html" rel="nofollow">...
1
2016-06-29T08:18:56Z
[ "python", "pandas", "dataframe", "group-by" ]
i am getting the following exception while encrypting the file via RSA key instance’s publickey method
38,093,992
<pre><code>This is my code for encrypting a file: </code></pre> <p>Iam getting this following error "cipher_aes = AES.new(session_key, AES.MODE_EAX) AttributeError: 'module' object has no attribute 'MODE_EAX'" If i remove the "AES.MODE_EAX" from the line NO 10 then i am getting the following error on line NO 12 (ciph...
0
2016-06-29T08:16:53Z
38,094,173
<p>I don't see cipher mode EAX anywhere in <a href="https://pythonhosted.org/pycrypto/Crypto.Cipher.AES-module.html" rel="nofollow">the documentation</a>. That would indicate to me that it is not supported by PyCrypto in the current stable release (2.6.1).</p> <p>However browsing through <a href="https://github.com/dl...
0
2016-06-29T08:26:55Z
[ "python", "cryptography", "public-key-encryption" ]
convenient collection of class variables
38,094,072
<p>Python beginner here. I am trying to write a convenience function to access class variables from a list of objects.</p> <p>currently, I am writing one function for each variable. For example, I have a class 'swarm' that contains 'animals'. Each animal has many variables that store time series such as position, head...
0
2016-06-29T08:21:25Z
38,094,146
<p>Use <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr(obj, name)</code></a> -- it's a built-in function that tries to retrieve the field or method with the given <code>name</code> from the provided <code>obj</code>, if that attribute exists.</p> <pre><code>def get_var_f...
2
2016-06-29T08:25:26Z
[ "python" ]
TensorFlow: argmax (-min)
38,094,217
<p>I just noticed an unexpected (at least for me) behavior in TensorFlow. I thought <code>tf.argmax</code> (-<code>argmin</code>) operates on the ranks of a Tensor from outer to inner, but apparently it does not?!</p> <p>Example:</p> <pre><code>import numpy as np import tensorflow as tf sess = tf.InteractiveSession(...
3
2016-06-29T08:29:01Z
38,094,712
<p>Think of the <code>dimension</code> argument of <code>tf.argmax</code> as the axis across which you reduce. <code>tf.argmax(arr, 0)</code> reduces across dimension <code>0</code>, i.e. the rows. Reducing across rows means that you will get the argmax of each individual column.</p> <p>This might be counterintuitive,...
4
2016-06-29T08:53:48Z
[ "python", "arrays", "indexing", "tensorflow" ]
Django - best way of storing data created on the fly for a view/template
38,094,250
<p>i need to send some data to a template in the format of</p> <pre><code>template_name: RTR-01 device_name: EDGE templte_name: RTR-02 device_name: EDGE template_name: SW-01 device_name: CORE </code></pre> <p>and so on.</p> <p>i know i cant use a list as they only allow one value, would a class be best suited? and...
0
2016-06-29T08:30:46Z
38,094,416
<p>A <code>list</code> of <code>dict</code>s seems best suited:</p> <pre><code>context = [ { 'template_name': 'RTR-01', 'device': 'EDGE', }, { 'template_name': 'RTR-02', 'device': 'EDGE', }, { 'template_name': 'SW-01', 'device': 'CORE', }, ] </cod...
0
2016-06-29T08:39:16Z
[ "python", "django" ]
Django - best way of storing data created on the fly for a view/template
38,094,250
<p>i need to send some data to a template in the format of</p> <pre><code>template_name: RTR-01 device_name: EDGE templte_name: RTR-02 device_name: EDGE template_name: SW-01 device_name: CORE </code></pre> <p>and so on.</p> <p>i know i cant use a list as they only allow one value, would a class be best suited? and...
0
2016-06-29T08:30:46Z
38,094,478
<p>You can store your data in a list of dictionaries:</p> <pre class="lang-python prettyprint-override"><code>data = [ { "template_name": "RTR-01", "device_name": "EDGE" }, { "template_name": "SW-01", "device_name": "CORE" }, ] </code></pre> <p>Then you will need to upd...
1
2016-06-29T08:42:16Z
[ "python", "django" ]
numpy indexed list error
38,094,271
<p>I am trying to create an indexed np.ndarray as:</p> <pre><code>dos2[q] = np.empty((dos[q].shape[0], dos[q].shape[1] + 1), dtype=dos[q].dtype) </code></pre> <p>with q properly defined. I am getting error:</p> <pre><code>NameError: name 'dos2' is not defined </code></pre> <p>The shape and type of dos[q] is:</p> <...
0
2016-06-29T08:31:57Z
38,094,593
<p>I guess it is simply just the declaration of dos2. If you want to define <code>dos2[q]</code>, <code>dos2</code>should have been defined before</p>
0
2016-06-29T08:47:41Z
[ "python", "python-3.x", "numpy" ]
numpy indexed list error
38,094,271
<p>I am trying to create an indexed np.ndarray as:</p> <pre><code>dos2[q] = np.empty((dos[q].shape[0], dos[q].shape[1] + 1), dtype=dos[q].dtype) </code></pre> <p>with q properly defined. I am getting error:</p> <pre><code>NameError: name 'dos2' is not defined </code></pre> <p>The shape and type of dos[q] is:</p> <...
0
2016-06-29T08:31:57Z
38,094,628
<p>It seems that <code>doc2</code> is not defined when you try to assign </p> <pre><code>dos2[q] = np.empty((dos[q].shape[0], dos[q].shape[1] + 1), dtype=dos[q].dtype) </code></pre> <p>Everytime you want when you try to assign something in part of the array you need to define it before. </p>
0
2016-06-29T08:49:25Z
[ "python", "python-3.x", "numpy" ]
Is there any cloud API to save internet image to cloud using Python?
38,094,337
<p>I have a project in hand to <strong>backup</strong> a website for some reasons. I use Requests in Python to crawl the contents and images (urls). The problem is, how can I save the image in the cloud, by using the url of that image, in Cloud services (Google Drive, Dropbox, etc.). </p> <p>I know there is a way to f...
-1
2016-06-29T08:36:01Z
38,102,360
<p>It seems like <a href="https://blogs.dropbox.com/developers/2015/06/programmatically-saving-a-url-to-dropbox/" rel="nofollow">Dropbox</a> has a feature called <code>/save_url</code> that</p> <blockquote> <p>lets app developers upload files to Dropbox by just providing a URL, without having to download the file fi...
0
2016-06-29T14:17:21Z
[ "python", "image", "google-app-engine", "cloud", "dropbox" ]
Is there any cloud API to save internet image to cloud using Python?
38,094,337
<p>I have a project in hand to <strong>backup</strong> a website for some reasons. I use Requests in Python to crawl the contents and images (urls). The problem is, how can I save the image in the cloud, by using the url of that image, in Cloud services (Google Drive, Dropbox, etc.). </p> <p>I know there is a way to f...
-1
2016-06-29T08:36:01Z
38,113,675
<p>If you don't mind paying for the storage, you can save it to your own cloud storage. I occasionally have to do a similar action, and handle it as such:</p> <pre class="lang-python prettyprint-override"><code>def on_upload_image(self): url = self.request.get('url') result = urlfetch.fetch(url) binary = resul...
0
2016-06-30T03:50:24Z
[ "python", "image", "google-app-engine", "cloud", "dropbox" ]
python Django migrate issue
38,094,344
<p>Here is the configuration of my setting.py</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'exercise', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } </code></pre> <p>when i run python manage.py m...
0
2016-06-29T08:36:13Z
38,094,832
<p><a href="https://code.djangoproject.com/ticket/26113" rel="nofollow">This Django ticket</a> suggests that MySQL Connector/Python 2.1.3 does not support Django 1.9.</p> <p>You could either downgrade to Django 1.8, or switch to the <code>django.db.backends.mysql</code> backend with mysqlclient or MySQLdb (MySQLdb is ...
1
2016-06-29T08:59:37Z
[ "python", "mysql", "django" ]
How do I reconstruct JSON from a dot delimeted list of strings?
38,094,363
<p>One would think doing this is easy. I swear it is, just... I can't seem to figure it out. How do I transform:</p> <p><code>terrible_way_to_describe_nested_json=['a.b.c','a.b.d','a.e','a.f','g.h']</code></p> <p>into </p> <pre><code>{ "a": { "b": { "c": None, "d": None },...
1
2016-06-29T08:37:11Z
38,094,519
<p>Try out the <a href="https://pypi.python.org/pypi/dpath" rel="nofollow">dpath</a> module, it can be used to add/filter/search dictionaries in an easy way. By replacing the dots with '/' characters you can create the <code>dict</code> you need.</p>
0
2016-06-29T08:44:44Z
[ "python", "json", "dictionary", "nested", "nested-loops" ]
How do I reconstruct JSON from a dot delimeted list of strings?
38,094,363
<p>One would think doing this is easy. I swear it is, just... I can't seem to figure it out. How do I transform:</p> <p><code>terrible_way_to_describe_nested_json=['a.b.c','a.b.d','a.e','a.f','g.h']</code></p> <p>into </p> <pre><code>{ "a": { "b": { "c": None, "d": None },...
1
2016-06-29T08:37:11Z
38,094,848
<p>Here you go:</p> <pre><code>In [5]: terrible_way_to_describe_nested_json=['a.b.c','a.b.d','a.e','a.f','g.h'] In [6]: terrible_way_to_describe_nested_json = [s.split('.') for s in terrible_way_to_describe_nested_json] In [7]: data = {} In [8]: for path in terrible_way_to_describe_nested_json: ....: curr = ...
3
2016-06-29T09:00:12Z
[ "python", "json", "dictionary", "nested", "nested-loops" ]
adsdb INSERT INTO
38,094,384
<p>I have an ADT that I can modify using Advantage Data Architect.</p> <p>However I wish to be able to modify the table using adsdb. I've created the table using;</p> <pre><code>cnxn = adsdb.connect(DataSource='c:/Python27/', ServerType='1') cursor = cnxn.cursor() cursor.execute('CREATE TABLE Persons (PersonID INTEGE...
0
2016-06-29T08:38:10Z
38,096,358
<p>In ADS SQL (and indeed in ANSI-SQL) strings (CHAR typed) values <a href="http://devzone.advantagedatabase.com/dz/webhelp/Advantage12/index.html?master_sql_literals.htm" rel="nofollow">have to be enclosed in single quotes</a>:</p> <pre><code>INSERT INTO Persons (LastName) VALUES ('Smith') </code></pre> <p><a href="...
0
2016-06-29T10:02:17Z
[ "python", "mysql", "advantage-database-server" ]
Advice about Azure IoT hub and raspberry pi
38,094,525
<p>Currently I'm creating a IoT Hub device that reads a sensor multiple times each second. I would like to achieve 3 to 4 reading each second.</p> <p>The sensor returns just a true or false and when its true I want a time-stamp and other information send to the Azure IoT hub. The device is a Raspberry Pi 3</p> <p>I w...
1
2016-06-29T08:45:01Z
38,102,952
<p>It sounds like the bit your missing here is <strong>Windows 10 IoT Core</strong> as the operating system for your Raspberry Pi. For Pi 3 this is officially still in preview mode, but still works well for doing everything you've described. I've been using it on my new Pi3 for a few months now.</p> <p>There are then ...
1
2016-06-29T14:43:47Z
[ "python", "azure", "iot", "raspberry-pi3", "azure-iot-hub" ]
Securing scrapyd's APIs and Web Interface
38,094,570
<p>I have setup <a href="http://scrapyd.readthedocs.io/en/latest/overview.html" rel="nofollow">Scrapyd</a> to manage Scrapy spiders in a better way and it is doing that really fine. I am just doubtful about how to secure it as I fear anyone who gets to know that this is a Scrapyd server can use the APIs to manipulate t...
0
2016-06-29T08:47:01Z
38,372,538
<p>That's not a scrapyd problem, That's a server management problem. What you need to do is close the scrapyd port on your server from outside ips except your own.</p>
0
2016-07-14T11:05:24Z
[ "python", "scrapy", "scrapy-spider", "scrapyd" ]
system commant wont work as in shell when calling a python comman on Ubuntu from R
38,094,651
<p>I'm trying to invoke within <code>R</code> a system command that invokes a call to a python script (that includes an import to pandas) as following:</p> <pre><code>getwd() [1] "/home/production" &gt; system("python In_tag_main_model/python_scripts/connect_to_couchbase.py") Traceback (most recent call last): File...
0
2016-06-29T08:50:47Z
38,096,067
<p>It looks like the R <code>system</code> function is executing a different python executable. You have three options to specify which executable you want:</p> <ul> <li><p>You the absolute path:</p> <pre><code>system("/anaconda2/bin/python In_tag_main_model/python_scripts/connect_to_couchbase.py") </code></pre></li>...
1
2016-06-29T09:50:15Z
[ "python", "shell" ]
python3.5: serial port reading gives error
38,094,663
<p>While reading serial port from COM4 port using python, i get the following error:</p> <pre><code> ---------------------------------------------------------------------------- F:\Invsense\motion_driver_6.12\eMPL-pythonclient&gt;python.exe eMPL-client.py 4 Traceback (most recent call last): File "eMPL-client.py", lin...
0
2016-06-29T08:51:24Z
39,668,813
<p>The problem is with the Invensense python script.</p> <ol> <li><p>Open eMPL-client.py in text editor and search for the line: <code>comport = int(sys.argv[1]) - 1</code></p></li> <li><p>change it to: <code>comport = sys.argv[1]</code></p></li> </ol> <p>The script was trying to cast the string 'COM4' into an intege...
0
2016-09-23T20:11:02Z
[ "python" ]
Force shutil copy to continue through list when encountering missing source file
38,094,679
<p>I'm using shutil to copy output from an upstream process based on user supplied files. Sometimes those files aren't compatible with the upstream process, and as such the final file I'm attempting to move won't be created. </p> <p>I'm handing shutil a list of verbose file paths, I want it to continue to move all ite...
0
2016-06-29T08:52:21Z
38,094,903
<p>One approach would be to simply add exception handling around the call, for example:</p> <pre><code>import shutil source = ['/home/Desktop/folder/subfolder/file.ext', '/home/Desktop/folder/subfolder2/file2.ext', '/home/Desktop/folder/subfolder3/file3.ext'] dest = ['/home/Desktop/target/file.ext','/home/Desktop/tar...
0
2016-06-29T09:02:30Z
[ "python", "shutil" ]
How to convert a tree drawn with ete2 to Newick format?
38,094,718
<p>I have drawn a tree in python using ete2 commands Tree(), .add_child(), .add_sister() and so on. Is there any way I can convert this tree to the corresponding Newick format?</p>
1
2016-06-29T08:53:58Z
38,108,821
<pre><code>from ete3 import Tree tree = Tree() tree.add_child(name="c") tree.add_child(name="b") print tree.write() #(c:1,b:1); </code></pre>
0
2016-06-29T19:47:19Z
[ "python", "tree", "phylogeny", "etetoolkit" ]
Pandas with Decimal?
38,094,820
<p>I'm calculating some standard deviations which are giving FloatingPointErrors. I wanted to try converting the data series to Decimal (using <a href="https://docs.python.org/3/library/decimal.html" rel="nofollow">https://docs.python.org/3/library/decimal.html</a>), to see if this fixes my issue.</p> <p>I can't seem ...
0
2016-06-29T08:58:59Z
38,094,931
<p>would something like this work? </p> <pre><code>def column_round(decimals): return partial(Series.round, decimals=decimals) df.apply(column_round(2)) </code></pre> <p>alternatively lets use <code>np.vectorize</code> so we can use <code>decimal.quantize</code> function to do rounding, this will leave the var...
0
2016-06-29T09:03:28Z
[ "python", "python-3.x", "numpy", "pandas", "decimal" ]
Why is numdifftools so inaccurate? How does it work?
38,095,023
<p>I'm using python's numdifftools library to perform derivatives. However, a few tests prove the library is highly inaccurate:</p> <pre><code>import numpy as np from numdifftools import Derivative # Result should be 1/2 or 0.5 Derivative(np.log, 1)(2.0) &gt;&gt;&gt; array(0.5493061443340549) </code></pre> <p>Is ther...
2
2016-06-29T09:07:03Z
38,095,186
<p>Using numdifftools 0.9.16 and numpy 1.9.3 the following code gives an exact result:</p> <pre><code>import numpy as np from numdifftools import Derivative # Result should be 1/2 or 0.5 Derivative(np.log)(2.0) </code></pre> <p>Output:</p> <pre><code>array(0.5000000000000238) </code></pre>
3
2016-06-29T09:14:30Z
[ "python", "numpy" ]
Why is numdifftools so inaccurate? How does it work?
38,095,023
<p>I'm using python's numdifftools library to perform derivatives. However, a few tests prove the library is highly inaccurate:</p> <pre><code>import numpy as np from numdifftools import Derivative # Result should be 1/2 or 0.5 Derivative(np.log, 1)(2.0) &gt;&gt;&gt; array(0.5493061443340549) </code></pre> <p>Is ther...
2
2016-06-29T09:07:03Z
38,096,202
<p>Issue spotted.</p> <pre><code>Derivative(np.log, 1)(2.0) </code></pre> <p>gives the wrong answer. The n should be explicitly stated:</p> <pre><code>Derivative(np.log, n=1)(2.0) &gt;&gt;&gt; array(0.5000000000000234) </code></pre>
2
2016-06-29T09:55:56Z
[ "python", "numpy" ]
Not able to remove a specific character from file via ansible
38,095,069
<p>I have a file with below data</p> <pre><code>server1 10.10.10.10, server2 10.10.10.20, server3 10.10.10.30, </code></pre> <p>And would like to only delete the comma character(<code>,</code>) from the third line i.e from <code>server3 10.10.10.30.</code></p> <p>When I try to use <code>lineinfile</code> method, it ...
0
2016-06-29T09:09:04Z
38,102,618
<p>The <code>lineinfile</code> module does not seem appropriate for your scenario. You could instead use the <code>sed</code> command:</p> <pre><code>- shell: sed -i 3s/,$// filetochange </code></pre>
0
2016-06-29T14:28:39Z
[ "python", "linux", "ansible" ]
Finding Multiple Sequences in a File by Position after SpecifIcally Repeating Characters
38,095,087
<p>i am trying to write this code, so that i can get my sequences of different samples in a file after line breaks by position, the output is always blank for some reason, can you help me?</p> <pre><code>import readline count = 0 brk = 0 with open("file.txt") as f: while (count &lt; 35): l = f.readline()[b...
-1
2016-06-29T09:10:04Z
38,113,940
<p>In the line <code>l = f.readline()[brk + 2]</code> the program puts one character into variable <code>l</code>. So, when you are trying to print substring of <code>l</code> (in the lines <code>print(l[sp:rl])</code> and <code>print(l[-30:0])</code>), the program prints empty lines. It is expected result.</p> <p>To ...
0
2016-06-30T04:20:40Z
[ "python" ]