title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python regular expression for | 38,786,432 | <p>What would be the regular expression for such data</p>
<pre><code>/home//Desktop/3A5F.py
path/sth/R67G.py
a/b/c/d/t/6UY7.py
</code></pre>
<p>i would like to get these</p>
<pre><code>3A5F.py
R67G.py
6UY7.py
</code></pre>
| -2 | 2016-08-05T09:57:24Z | 38,786,553 | <p>It looks like you're parsing paths, in which case you should really be using <a href="https://docs.python.org/3/library/os.path.html#os.path.basename" rel="nofollow"><code>os.path</code></a> instead of regex:</p>
<pre><code>from os.path import basename
basename('/home//Desktop/3A5F.py')
# 3A5F.py
</code></pre>
| 2 | 2016-08-05T10:03:54Z | [
"python",
"regex"
] |
Python regular expression for | 38,786,432 | <p>What would be the regular expression for such data</p>
<pre><code>/home//Desktop/3A5F.py
path/sth/R67G.py
a/b/c/d/t/6UY7.py
</code></pre>
<p>i would like to get these</p>
<pre><code>3A5F.py
R67G.py
6UY7.py
</code></pre>
| -2 | 2016-08-05T09:57:24Z | 38,786,751 | <p>You can use this.</p>
<pre><code>pattern = ".*/(.*$)"
mystring = "/home//Desktop/3A5F.py"
re.findall(pattern, mystring)
</code></pre>
<p>You can also use <code>os.path.split(mystring)</code></p>
| 0 | 2016-08-05T10:15:20Z | [
"python",
"regex"
] |
Django Error: Your URL pattern is invalid. Ensure that urlpatterns is a list of url() instances | 38,786,461 | <p>After upgrading to Django 1.10, I get the following error when I run <code>python manage.py runserver</code>:</p>
<pre><code>?: (urls.E004) Your URL pattern ('^$', 'myapp.views.home') is invalid. Ensure that urlpatterns is a list of url() instances.
HINT: Try using url() instead of a tuple.
</code></pre>
<p>My <co... | 1 | 2016-08-05T09:59:01Z | 38,786,462 | <p>To simplify URL configs, <code>patterns()</code> was deprecated in Django 1.8, and removed in 1.10 (<a href="https://docs.djangoproject.com/en/1.10/releases/1.10/#features-removed-in-1-10" rel="nofollow">release notes</a>). In Django 1.10, <code>urlpatterns</code> must be a list of <code>url()</code> instances. Usin... | 3 | 2016-08-05T09:59:01Z | [
"python",
"django",
"django-1.10"
] |
Python3 setuptools bidst_rpm : remove /usr/lib/python3.x/site-packages prefix. Adapt rpm install directory to client machine's python path | 38,786,627 | <p>I'm currently trying to create a rpm distribution of a python project I've been working on. I'm using setuptools 25.1.4 on a Fedora 24 and using python3.4. </p>
<p>I can generate my rpm distribution by using :</p>
<pre><code>python3 setup.py bdist_rpm
</code></pre>
<p>And here is a look at my setup.cfg file : </p... | 0 | 2016-08-05T10:08:03Z | 38,806,974 | <p>When you run <code>bdist_rpm</code> it will also create src.rpm. With this file run:</p>
<pre><code>mock -r fedora-24-x86_64 myproject.src.rpm
</code></pre>
<p>It will create fedora-24-x86_64 environment in chroot and build your package there. With correct paths for Fedora 24.</p>
| 0 | 2016-08-06T17:30:40Z | [
"python",
"python-3.x",
"fedora",
"rpm",
"setuptools"
] |
Sequence index plot python | 38,786,935 | <p>I am trying to plot the sequence of a set of time sorted values, in which each value is represented by a different colour. For instance, if my values are like </p>
<pre><code>state_seq = [2, 2, 2, 2, 0, 0, 0, 1, 3, 6, 3, 3, 3, 0, 0]
time_seq = ['2013-05-29 09:31:00', '2013-05-29 09:46:00', '2013-07-23 12:28:00', '2... | 0 | 2016-08-05T10:24:54Z | 38,789,856 | <p>I assume you want square boxes for each value, regardless of the time gap between each. To have a width indicative of the time gap you could <a href="http://stackoverflow.com/questions/466345/converting-string-into-datetime">convert <code>time_seq</code> to datetime objects</a> and then plot the dates directly with ... | 1 | 2016-08-05T12:58:19Z | [
"python",
"matplotlib",
"seaborn"
] |
Pandas: convert unicode strings to string | 38,786,936 | <p>I have data frame and there are 2 columns with unicode value. I need to convert it to string. I try <code>df.domain.astype(str)</code> but it return unicode strings.
How can I do that?
Data looks like (I need to convert either columns)</p>
<pre><code>domain search_term
vk.com None
facebook.com N... | 0 | 2016-08-05T10:25:00Z | 38,787,953 | <p>Would this help?:</p>
<pre><code>for col in types[types=='unicode'].index:
df[col] = df[col].astype(str)
</code></pre>
<p>or:</p>
<pre><code>for col in types[types=='unicode'].index:
df[col] = df[col].apply(lambda x: x.encode('utf-8').strip())
</code></pre>
| 0 | 2016-08-05T11:18:25Z | [
"python",
"pandas"
] |
Run multiple different flask apps with manage.py (flask-script) | 38,787,022 | <p>I have a Flask app set up so it can run two different sites (the sites share businesslogic and database models, so they use the same back end). One is just the regular website, the other is a site that runs tasks (it's a web interface for shooting long running tasks into celery)</p>
<p>The app currently uses Flask-... | 0 | 2016-08-05T10:29:17Z | 38,814,568 | <p>You can pass a function to the constructor of Manager. The function should return a Flask app. You can also pass parameters to the function by using the <code>manager.add_option</code> </p>
<pre><code>manager.add_option('-a','--app_type', dest='app_type',required=True)
def make_app(app_type):
if app_type =='webse... | 1 | 2016-08-07T13:21:00Z | [
"python",
"flask",
"flask-script"
] |
Error with json VirusTotal API call in python | 38,787,051 | <p>I need to retrieve the result of VirusTotal scans already performed, providing the hash of the files, without sending the file again.
You can find the documentation of the API <a href="https://www.virustotal.com/it/documentation/public-api/" rel="nofollow">here</a>.</p>
<p>I basically need to send a json of this fo... | 1 | 2016-08-05T10:31:09Z | 38,800,086 | <p>I noticed that I used a variable called <code>hash</code> and it could cause an issue because it can be mistaken with a method by the Python interpreter so I renamed it to <code>file_hash</code>. Then instead of using <code>r.json</code> I used <code>r.text</code> for getting the response as text and then I passed i... | 1 | 2016-08-06T02:48:58Z | [
"python",
"json",
"python-requests"
] |
Base.py: Unicode equal comparison failed to convert both arguments to Unicode in | 38,787,173 | <p>I was taking a look to a couple of related questions which treats about the same issue, but I still don't find a way to solve it.</p>
<p>It turns out that every time I execute a Django-related command, it prints me out the expected output plus something like this:</p>
<pre><code>/Library/Python/2.7/site-packages/d... | 1 | 2016-08-05T10:37:34Z | 38,787,241 | <p>use <a href="https://docs.python.org/2/library/stdtypes.html#str.decode" rel="nofollow">decode('utf-8')</a> to make correct comparing:</p>
<pre><code>name.decode('utf-8') == ":memory:" or "mode=memory" in force_text(name)
</code></pre>
<p>Use full info:</p>
<p><a href="https://docs.python.org/2.7/howto/unicode.ht... | 1 | 2016-08-05T10:40:29Z | [
"python",
"django",
"unicode"
] |
Substitue extra double quotes in a single CSV fields via bash | 38,787,354 | <p>I need to substitute extra double quotes from CSV log files (fields are comma separated and quoted by double-quotes). The substitution must impact only the last field of CSV.</p>
<p>Input log file example:</p>
<pre><code>"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG"dsdajasghs... | 1 | 2016-08-05T10:46:27Z | 38,787,430 | <p>You can use awk:</p>
<pre><code>awk "{gsub(/'/, \"''\", \$NF)} 1" file.csv
"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG''dsdajasghsahd"
</code></pre>
| 1 | 2016-08-05T10:50:22Z | [
"python",
"bash",
"csv"
] |
Substitue extra double quotes in a single CSV fields via bash | 38,787,354 | <p>I need to substitute extra double quotes from CSV log files (fields are comma separated and quoted by double-quotes). The substitution must impact only the last field of CSV.</p>
<p>Input log file example:</p>
<pre><code>"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG"dsdajasghs... | 1 | 2016-08-05T10:46:27Z | 38,787,575 | <p>try this; </p>
<pre><code>awk -F, -v OFS="," '{gsub(/\"/,"\47\47",$NF)gsub(/^\47\47/,"\"",$NF);gsub(/\047\047$/,"\"",$NF) }1' file
"24-12-2015","23:07:08","00","01","00","00","START","00","END","JS786JGDG7899JSGJHG''dsdajasghsahd"
</code></pre>
| 0 | 2016-08-05T10:57:40Z | [
"python",
"bash",
"csv"
] |
Define Each New Line As a Variable | 38,787,578 | <p>I have a text file that has many lines of data. I would like to setup a loop that reads each line of data and then defines that line/data as a new variable to be used in my python script.'</p>
<p><strong>File Example:</strong></p>
<pre><code>1
2
3
4
5
6
7
8
9
</code></pre>
<p><strong>Python Script (so far...):</s... | -2 | 2016-08-05T10:57:56Z | 38,787,649 | <p>You have to create a <code>List</code> and append the variables to it like this</p>
<pre><code>#!/usr/bin/python
f = open('/home/weather/test', 'r')
variables=[]
for line in f.readlines():
variables.append(line)
f.close()
</code></pre>
<p><a href="http://www.tutorialspoint.com/python/python_lists.htm" rel="no... | 1 | 2016-08-05T11:02:05Z | [
"python"
] |
Define Each New Line As a Variable | 38,787,578 | <p>I have a text file that has many lines of data. I would like to setup a loop that reads each line of data and then defines that line/data as a new variable to be used in my python script.'</p>
<p><strong>File Example:</strong></p>
<pre><code>1
2
3
4
5
6
7
8
9
</code></pre>
<p><strong>Python Script (so far...):</s... | -2 | 2016-08-05T10:57:56Z | 38,787,669 | <p>Use <code>exec</code> with a string representing the required code:</p>
<pre><code>for i in range(5):
exec('line%d=%d' % (i, i))
print(line0)
print(line1)
print(line2)
print(line3)
print(line4)
</code></pre>
<p>Output:</p>
<pre><code>0
1
2
3
4
</code></pre>
<p>The <code>exec</code> line activates the pytho... | 1 | 2016-08-05T11:03:29Z | [
"python"
] |
Define Each New Line As a Variable | 38,787,578 | <p>I have a text file that has many lines of data. I would like to setup a loop that reads each line of data and then defines that line/data as a new variable to be used in my python script.'</p>
<p><strong>File Example:</strong></p>
<pre><code>1
2
3
4
5
6
7
8
9
</code></pre>
<p><strong>Python Script (so far...):</s... | -2 | 2016-08-05T10:57:56Z | 38,788,043 | <p>Usually when you want to have dynamically named variables, really you want a sequence or mapping. In your case, sequence (e.g. list) will be enough. List of lines may be retrieved from file by <code>.readlines</code> method.</p>
<pre><code>with open('/home/weather/test', 'r'):
all_lines = f.readlines()
print al... | 2 | 2016-08-05T11:22:37Z | [
"python"
] |
substract values of two nested dictionary python | 38,787,618 | <p>I'd need to get delta of two nested dictionary:</p>
<p>I'm using a function like that to get a nested dictionary </p>
<pre><code>def _get_data(self):
duplicates = defaultdict(list) # to append tuples into a dictionary
counter_dict = AutoVivification()
vpls_dict = AutoVivification()
fpcs = self._ge... | -3 | 2016-08-05T10:59:38Z | 38,788,512 | <p>You could do that with simple recursive function that will turn <code>str</code> values to <code>int</code> and subtract or recurse in case of <code>dict</code>:</p>
<pre><code>def subtract(x, y):
if isinstance(x, dict) and isinstance(y, dict):
return {key: subtract(x[key], y[key]) for key in x if key i... | 1 | 2016-08-05T11:47:49Z | [
"python",
"dictionary",
"nested"
] |
NOT NULL constraint failed: owner_id in form saving | 38,787,689 | <p>I am trying to make a form which allows users to upload a file (a plain text dictionary file). Here is my model:</p>
<pre><code>from django.conf import settings
from django.db import models
import uuid
class Dictionary(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
... | 0 | 2016-08-05T11:04:40Z | 38,787,849 | <p><code>is_valid()</code> only validates the fields that you specified in the form (in this case - <code>file</code>). The form is valid - but you get an error later on because the other model field constraints are not met when saving. </p>
<p>Passing the <code>owner</code> to the form isn't going to work because the... | 2 | 2016-08-05T11:12:33Z | [
"python",
"django",
"web-applications"
] |
Keras deep variational autoencoder | 38,787,714 | <p>Im trying to adapt the Keras VAE example to a deep network by adding one more layer.</p>
<p>Original code: <a href="https://github.com/fchollet/keras/blob/master/examples/variational_autoencoder.py" rel="nofollow">Original VAE code</a></p>
<p>CHANGES:</p>
<pre><code>batch_size = 200
original_dim = 784
latent_dim ... | 0 | 2016-08-05T11:06:14Z | 38,793,964 | <p>When adding the new hidden layer you're overriding the <code>x</code> variable so you're left without an input layer. Also, is 'rely' a valid activation option?</p>
| 0 | 2016-08-05T16:32:24Z | [
"python",
"machine-learning",
"deep-learning",
"keras",
"autoencoder"
] |
Codecademy Advance Python The "In" Operator. Why does key print values? | 38,787,737 | <p>I am having difficulty understanding why the last line in the code is: </p>
<pre><code>print key, my_dict[key]
</code></pre>
<p>instead of... </p>
<pre><code>print key, my_dict[values]
</code></pre>
<p>CODE </p>
<pre><code>my_dict = {
"Name": "Joshua",
"Age": "28",
"Nationality": "UK"
print my_dict.keys()
... | 0 | 2016-08-05T11:07:23Z | 38,787,933 | <p>DIctionary is a mapping type.It consists of key value pairs.For each key there will be an associated value.So for retreiving a value associated with a key, we use dict[key].It is just like accessing an element in a list with the index value.In your example if you call <code>my_dict['name']</code> you will get <code... | 0 | 2016-08-05T11:17:19Z | [
"python"
] |
Codecademy Advance Python The "In" Operator. Why does key print values? | 38,787,737 | <p>I am having difficulty understanding why the last line in the code is: </p>
<pre><code>print key, my_dict[key]
</code></pre>
<p>instead of... </p>
<pre><code>print key, my_dict[values]
</code></pre>
<p>CODE </p>
<pre><code>my_dict = {
"Name": "Joshua",
"Age": "28",
"Nationality": "UK"
print my_dict.keys()
... | 0 | 2016-08-05T11:07:23Z | 38,787,974 | <p>Lists work like this:</p>
<pre><code>foo = ["spam", "spam", "lovely spam"]
print foo[0] # prints "spam"
</code></pre>
<p>0 is the index for the element "spam".</p>
<p>You are using a dictionary. Dictionaries don't have indexes, they have keys.</p>
<pre><code>my_dict = {
"Name": "Joshua",
"Age": "28",
"National... | 1 | 2016-08-05T11:19:24Z | [
"python"
] |
Installing opencv 3.1 with anaconda python3? | 38,787,748 | <p>How do I install opencv with anaconda python3 , opencv picked up my python3 executables</p>
<pre><code>-- Python 2:
-- Interpreter: /usr/bin/python2.7 (ver 2.7.12)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.12)
-- numpy: /us... | 0 | 2016-08-05T11:07:59Z | 39,240,127 | <p>I think you don't need to build OpenCV for anaconda, there is this very handy
tool called 'conda' that is available in your terminal once you have installed
the Anaconda python distribution.</p>
<p>I found this site which gives instruction on how to install opencv3</p>
<pre><code>https://anaconda.org/menpo/opencv3... | 1 | 2016-08-31T03:07:40Z | [
"python",
"opencv",
"anaconda",
"ubuntu-16.04"
] |
Django admin: Edit fields of one-to-one model class | 38,787,889 | <p>I have two models with the following relationship defined in models.py:</p>
<pre><code>class InnerModel(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class OuterModel(models.Model):
inner = models.OneToOneField(InnerModel)
def __str__(self):
... | 0 | 2016-08-05T11:14:40Z | 38,788,308 | <p>You need to use <code>inlines</code> (<a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.inlines" rel="nofollow">doc</a>):</p>
<pre><code>class InnerModelInline(admin.StackedInline):
model = InnerModel
class OuterModelAdmin(admin.ModelAdmin):
inlines = [InnerM... | 1 | 2016-08-05T11:35:58Z | [
"python",
"django",
"django-models",
"django-forms",
"django-admin"
] |
Python3 Asyncio shared resources between concurrent tasks | 38,787,989 | <p>I've got a network application written in Python3.5 which takes advantage of pythons Asyncio which concurrently handles each incoming connection. </p>
<p>On every concurrent connection, I want to store the connected clients data in a list. I'm worried that if two clients connect at the same time (which is a possibi... | 1 | 2016-08-05T11:20:10Z | 38,791,709 | <p>asyncio does context switching only on <em>yield points</em> (<code>await</code> expressions), thus two parallel tasks are not executed at <strong>the same</strong> time.</p>
<p>But if race conditions are still possible (it depends on concrete code structure) you may use <a href="https://docs.python.org/3/library/a... | 2 | 2016-08-05T14:29:24Z | [
"python",
"python-3.x",
"concurrency",
"python-asyncio",
"shared-resource"
] |
Python3 Asyncio shared resources between concurrent tasks | 38,787,989 | <p>I've got a network application written in Python3.5 which takes advantage of pythons Asyncio which concurrently handles each incoming connection. </p>
<p>On every concurrent connection, I want to store the connected clients data in a list. I'm worried that if two clients connect at the same time (which is a possibi... | 1 | 2016-08-05T11:20:10Z | 38,791,950 | <p>There is lots of info that is missing in your question.</p>
<ul>
<li>Is your app threaded? If yes, then you have to wrap your list in a <code>threading.Lock</code>.</li>
<li>Do you switch context (e.g. use <code>await</code>) between writes (to the list) in the request handler? If yes, then you have to wrap your li... | 1 | 2016-08-05T14:41:15Z | [
"python",
"python-3.x",
"concurrency",
"python-asyncio",
"shared-resource"
] |
Issues with downloading dict into CSV accesing NY Times API via Python | 38,788,027 | <p>I am currently trying to download a large number of NY Times articles using their API, based on Python 2.7. To do so, I was able to reuse a piece of code i found online: </p>
<pre><code>[code]from nytimesarticle import articleAPI
api = articleAPI('...')
articles = api.search( q = 'Brazil',
fq = {'headline':'... | 0 | 2016-08-05T11:21:40Z | 38,788,544 | <p>Where you have:</p>
<pre><code>keys = Download_all[0].keys()
</code></pre>
<p>This takes the column headers for the CSV from the dictionary for the first article. The problem is that the article dictionaries do not all have the same keys, so when you reach the first one that has the extra <code>abstract</code> key... | 0 | 2016-08-05T11:49:52Z | [
"python",
"api",
"csv"
] |
How to get information from widgets | 38,788,073 | <p>I have a PyQt program and in this project I have some calculations based on earlier set preferences.</p>
<p>As an example, I created a small calculator which contains the following files:</p>
<p><em>example_run_vars.py</em>:</p>
<pre><code>from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
d... | 2 | 2016-08-05T11:23:35Z | 38,794,039 | <p>The data is <em>already</em> stored in the widgets, so it is inefficient make another copy of it. Also, you would need to set up handlers for each individual widget, which is unnecessarily complicated. In general, it is best to gather all the information from the widgets at the point when the calculation is made.</p... | 2 | 2016-08-05T16:37:06Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5"
] |
How to upload crawled data from Scrapy to Amazon S3 as csv or json? | 38,788,096 | <p>What are the steps to upload the crawled data from Scrapy to the Amazon s3 as a csv/jsonl/json file? All i could find from the internet was to upload scraped images to the s3 bucket.</p>
<p>I'm currently using Ubuntu 16.04,
and i have installed boto by the command, </p>
<pre><code>pip install boto
</code></pre>
<... | 0 | 2016-08-05T11:24:58Z | 38,822,610 | <p>The problem was solved by adding the following line into <code>settings.py</code> file:</p>
<pre><code>ITEM_PIPELINE = {
'scrapy.pipelines.files.S3FilesStore': 1
}
</code></pre>
<p>along with the S3 credentials mentioned earlier.</p>
<pre><code>AWS_ACCESS_KEY_ID = 'access key id'
AWS_SECRET_ACCESS_KEY= 'access ke... | 0 | 2016-08-08T06:33:35Z | [
"python",
"json",
"amazon-s3",
"web-scraping",
"scrapy"
] |
Google App engine (Python) - Contact Us info from an anonymous user | 38,788,097 | <p>How to allow someone without credentials to send me an email using the contactus form that I have provided on my Google app engine app?? When I am trying normally using mail modules, it is saying no real mail is bieng sent. Help me fix it!!</p>
| -2 | 2016-08-05T11:25:09Z | 38,788,635 | <p>If I understand you correctly, All you need is to get an alert about the "Contact us form submission activity" by a visitor (anonymous user) on the website.</p>
<p>You can implement it by having an email id like contact@example.com and send email to itself when a user submits the form. You can do it pretty easily, ... | 0 | 2016-08-05T11:54:40Z | [
"python",
"google-app-engine"
] |
Parallel python extract by mask ArcGIS | 38,788,222 | <p>I found the following code in a <a href="http://gis.stackexchange.com/questions/94092/script-to-extract-by-mask-a-list-of-raster-files">previous</a> answer. I tried it for about 3000 rasters, it works but very slow. How to excute the code in parallel to fasten the process?</p>
<p>thanks,
moh</p>
<pre><code>import ... | 0 | 2016-08-05T11:31:48Z | 38,788,400 | <p>You may use threads. Depending on the number of cores you have, execute 4/8/16 simultanously.
Hints for using threads:
<a href="https://pymotw.com/2/threading/" rel="nofollow">https://pymotw.com/2/threading/</a></p>
| 0 | 2016-08-05T11:41:39Z | [
"python",
"parallel-processing",
"arcgis"
] |
Error: spawn EACCES in ubuntu for node.js/express app trying to run python | 38,788,280 | <p>I have made a node.js server to run a python script using <a href="https://github.com/extrabacon/python-shell" rel="nofollow">python-shell </a> and am encountering an EACCES error ever since migrating from windows to Ubuntu. I have to my knowledge and limited ability tried to set the correct permissions to no avail,... | 1 | 2016-08-05T11:34:40Z | 38,813,845 | <p>Upon detailed testing I have been unable to find a solution to this issue, and the question has indeed died.</p>
<p>However I successfully found a work-around, finding the issue with the EACCES was with the python path (in the options object). Removing this and running a python script in the server terminal's run l... | 0 | 2016-08-07T11:52:34Z | [
"javascript",
"python",
"node.js",
"ubuntu",
"express"
] |
Spyder does not show lists and arrays in variable explorer | 38,788,286 | <p>i don't really know why, but Spyder is not able to show lists or arrays in the variable explorer anymore. Do you have the same problem, any fixes? I have that problem on two computers.</p>
<p>Example:</p>
<pre><code>CSV = []
for x in os.listdir(location):
if x.split(".")[-1] =="CSV":
CSV.append(locatio... | 0 | 2016-08-05T11:34:53Z | 38,789,224 | <p>Menu (Tools->Preferences->Variable Explorer) Shortcut (Ctrl+Alt+Shift+P)</p>
<p>Disable all the filters</p>
<p><a href="http://i.stack.imgur.com/tCcCn.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/tCcCn.jpg" alt="enter image description here"></a></p>
| 0 | 2016-08-05T12:24:49Z | [
"python",
"list",
"spyder"
] |
Avoid interpolation problems with numpy float | 38,788,291 | <p>I need to handle timespans in a library I am creating. My first idea was to keep it simple and codify them as years, with float.</p>
<p>The problems arise, for instance, when I wish to perform interpolations. Say I have</p>
<pre><code>xs = np.array([0, 0.7, 1.2, 3.0]) # times
ys = np.array([np.nan, 124.3, 214.0, ... | 0 | 2016-08-05T11:35:11Z | 38,789,092 | <p>I think there is just no easy way out of this.
Floats are fundamentally not suitable to be checked for equality, and by evaluating your interpolation on the edges of its domain (or using floats as keys in dictionaries), you are doing exactly this.</p>
<p>Your solution using epsilons is a bit hacky, but honestly the... | 1 | 2016-08-05T12:19:18Z | [
"python",
"numpy",
"floating-point",
"interpolation"
] |
Regex search For HTML Tag with UUID | 38,788,319 | <p>I'm trying to match a single HTML tag with an <code>id</code> attribute which is a UUID. I tested it with an external resource to make sure the regex is correct with the same input string. The UUID is extracted dynamically so the string replacement is necessary. </p>
<p>The output I would would expect is for the la... | -3 | 2016-08-05T11:36:51Z | 38,788,708 | <p>Why won't you use group method? This works for me:</p>
<pre><code>element_to_link.group(0)
</code></pre>
| 0 | 2016-08-05T11:57:44Z | [
"python",
"regex"
] |
Regex search For HTML Tag with UUID | 38,788,319 | <p>I'm trying to match a single HTML tag with an <code>id</code> attribute which is a UUID. I tested it with an external resource to make sure the regex is correct with the same input string. The UUID is extracted dynamically so the string replacement is necessary. </p>
<p>The output I would would expect is for the la... | -3 | 2016-08-05T11:36:51Z | 38,789,334 | <p>From the Python re module documentation the <a href="https://docs.python.org/2/library/re.html#re.MatchObject.string" rel="nofollow">MatchObject.string</a> property returns "The string passed to match() or search().". Use one of the methods of MatchObject such as group(), groups() or groupdict().</p>
| 0 | 2016-08-05T12:31:07Z | [
"python",
"regex"
] |
Trying to scrape tripadvisor members using BeautifulSoup | 38,788,367 | <p>So Im trying to scrape this users profile for his ratings on hotels & restaurants separately
<a href="https://www.tripadvisor.in/members-reviews/rahuls896" rel="nofollow">https://www.tripadvisor.in/members-reviews/rahuls896</a></p>
<p>Now the problem is that its showing me all reviews by default when Im readin... | 0 | 2016-08-05T11:39:08Z | 38,789,834 | <p>Just try scraping the entire content for the user, then segregate them as per your requirement.</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.tripadvisor.in/members-reviews/rahuls896')
next_button = driver.find_element_by_id("cs-paginate-next")
next_button.click(... | 0 | 2016-08-05T12:57:44Z | [
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
read_csv with parse_date not recognising dates? | 38,788,398 | <p>I have a CSV file that looks like this:</p>
<pre><code>date,important
July 2015,True
August 2015,False
</code></pre>
<p>But when I try to read it into pandas using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">read_csv</a> with the <code>parse_dates</code> flag... | 0 | 2016-08-05T11:41:28Z | 38,788,438 | <p>By default, it parses the index as date and there is no index specified here. Either pass <code>index_col=0</code> or specify the name of the column:</p>
<pre><code>df = pd.read_csv('test.csv', parse_dates=['date'])
df
Out[30]:
date important
0 2015-07-01 True
1 2015-08-01 False
</code></pre>
<p... | 1 | 2016-08-05T11:43:47Z | [
"python",
"pandas"
] |
Parse entire directory Etree Parse lxml | 38,788,554 | <p>I need to parse txt files with xml markup in a directory (I already created a corpus with glob), yet etree parse only allows one file at a time. How do I set up a loop to parse all files at once? The goal then is to add these files to Elasticsearch using requests. This is what I have so far:</p>
<pre><code>import j... | -1 | 2016-08-05T11:50:32Z | 38,791,814 | <p>Simply iterate on the <code>corpus</code> list. However, you will want to use a container such as a list or dictionary to hold the individually parsed data. Below assumes .txt files are well-formed .xml files and maintain same structure including <code>tei</code> namespace:</p>
<pre><code>import os, glob
from lxml ... | 0 | 2016-08-05T14:34:53Z | [
"python",
"xml",
"lxml",
"elementtree",
"jupyter"
] |
Check remote file existence using wildcards -Python | 38,788,712 | <p>I am trying to write a python script to check whether a remote file exists, if not wait until it appears. For the file name I use a wild card. This is what I have tried until now.</p>
<pre><code>import paramiko
transport = paramiko.Transport("10.1.200.213")
transport.connect(username="user", password='password')
s... | 0 | 2016-08-05T11:58:00Z | 38,789,493 | <p>There are two ways to do it.</p>
<pre><code>import os
os.path.exists('./file.txt') # True
</code></pre>
<p>Another way that's with wildcard is Using <a href="https://docs.python.org/2/library/glob.html" rel="nofollow">glob function</a></p>
<pre><code>>>> import glob
>>> glob.glob('./[0-9].*')... | -1 | 2016-08-05T12:39:59Z | [
"python",
"wildcard",
"paramiko",
"pysftp"
] |
Assign a serial number when quantity is more than one | 38,788,754 | <p>I have a model in which a unique serial number is generated, and there is a quantity field in which the user can select how many parts they'd like made. Think of it like a shopping order. I'd like that if the user selects a quantity of more than one, a serial number be assigned to each individual part.
Models:</p>
... | -1 | 2016-08-05T12:00:25Z | 38,793,386 | <p>I can't really understand your models, but I think what you need (if you don't already have it) is a <code>Part</code> model. Have one field in the <code>Part</code> model be the serial number of the part, which can be automatically generated if you want, and so when a user requests X number of parts you can just cr... | 0 | 2016-08-05T15:57:09Z | [
"python",
"django"
] |
Pandas: AttributeError: 'str' object has no attribute 'iloc' | 38,788,771 | <p>I need to convert columns from unicode to str.
I try</p>
<pre><code>f.edge(str(group['subdomain']).iloc[i], str(group['subdomain'].iloc[i+1]),
label=str(group['search_term'].iloc[i+1]))
</code></pre>
<p>But it returns <code>AttributeError: 'str' object has no attribute 'iloc'</code>
How can I fix that?<... | -1 | 2016-08-05T12:01:09Z | 38,788,807 | <p>You're casting before accessing the <code>iloc</code> attribute:</p>
<pre><code>str(group['subdomain']).iloc[i]
# ^
</code></pre>
<p>Move the parenthesis farther to the right:</p>
<pre><code>str(group['subdomain'].iloc[i])
</code></pre>
| 1 | 2016-08-05T12:03:03Z | [
"python",
"pandas"
] |
Extract affine part of SymPy expression | 38,788,781 | <p>I have a sympy expression with one variable <code>x</code>, e.g.,</p>
<pre><code>import sympy
x = sympy.Symbol('x')
f = 3*x**2 + 5*x + 7 + sympy.exp(x)
</code></pre>
<p>I'd like to programmatically extract the <em>affine</em> part of that expression, i.e., the part that does not depend on <code>x</code>; <code>7<... | 0 | 2016-08-05T12:01:56Z | 38,788,894 | <p>If I understood you correctly, you need to use <a href="http://docs.sympy.org/0.7.6/modules/core.html#sympy.core.expr.Expr.coeff" rel="nofollow"><code>coeff</code></a>:</p>
<pre><code>>>> import sympy
>>> x = sympy.Symbol('x')
>>> f = 2*(3*x**2 + 5*x + 7 + sympy.exp(x))
>>> f.coe... | 2 | 2016-08-05T12:08:07Z | [
"python",
"sympy"
] |
what's mean "error: [Errno 2] No such file or directory: 'src/webkit_server'"? | 38,788,816 | <p>I need to install dryscrape for python but I got error, what's the problem?</p>
<pre><code>C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
</code></pre>
<p>I got this:</p>
<pre><code>Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collectin... | 1 | 2016-08-05T12:03:40Z | 38,789,024 | <p>From the <a href="http://dryscrape.readthedocs.io/en/latest/installation.html" rel="nofollow">doc</a>, you have to installed also <a href="https://github.com/niklasb/dryscrape/blob/master/requirements.txt" rel="nofollow">requirements</a>.
You can do this as follow</p>
<pre><code>pip install -r requirements.txt
</co... | 0 | 2016-08-05T12:15:56Z | [
"python",
"python-3.x",
"package",
"install"
] |
Adding Current date to Custom Widget fields | 38,788,819 | <p>I have a custom widget with Date fields and Time Fields, <code>D/M/Y, H/M(24hour)</code>. Now, on create event which is where these are used it come up with their empty_label value that i have setup.</p>
<p>I want this Empty_value to be the current day, current month. BUT i don't know if these will be stored if the... | 2 | 2016-08-05T12:03:47Z | 38,790,123 | <p>What you want is not to set the current date as "empty label", this would make no sense. Empty is empty, not current date. What you want to do is to select the current date by default, which is done by <a href="https://docs.djangoproject.com/en/stable/ref/forms/api/#dynamic-initial-values" rel="nofollow"><code>Form.... | 1 | 2016-08-05T13:10:05Z | [
"python",
"django"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_b... | 2 | 2016-08-05T12:06:29Z | 38,788,966 | <p>You can use <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow"><code>functools.partial</code></a> with keyword argument:</p>
<pre><code>>>> def multiply_by(x, multiplier):
... return x * multiplier
...
>>> from functools import partial
>>> mult... | 3 | 2016-08-05T12:12:14Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_b... | 2 | 2016-08-05T12:06:29Z | 38,788,974 | <p><a href="https://docs.python.org/3/library/functools.html#functools.partial" rel="nofollow">functools.partial</a> is made exactly for this.</p>
<p>you can use it like</p>
<pre><code>import functools
multiply_by_5=functools.partial(multiply_by,multiplier=5)
</code></pre>
| 2 | 2016-08-05T12:12:53Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_b... | 2 | 2016-08-05T12:06:29Z | 38,788,976 | <p>If you cannot change the <code>multiply_by()</code> function, the simplest and perhaps best way is probably</p>
<pre><code>def multiply_by_5(x):
return multiply_by(x, 5)
</code></pre>
<p>You can also use <code>lambda</code> if you really want a one-liner.</p>
<p>However, you may want to change your first func... | 0 | 2016-08-05T12:12:55Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_b... | 2 | 2016-08-05T12:06:29Z | 38,789,095 | <p>As suggested by @niemmi's <a href="http://stackoverflow.com/a/38788966/2289509">answer</a>, <code>functools.partial</code> is probably the way to go. </p>
<p>However, similar work can be done using curried functions:</p>
<pre><code>def multiply_by(multiplier):
def multiply(x):
return multiplier * x
... | 2 | 2016-08-05T12:19:23Z | [
"python",
"python-2.7",
"closures"
] |
Creating a copy of a function with some vars fixed | 38,788,869 | <p>Assume I have a function</p>
<pre><code>def multiply_by(x, multiplier):
return x * multiplier
</code></pre>
<p>How can I create a copy of that function and fix the multiplier in that function?</p>
<pre><code>multiply_by_5 = multiply_by? <-- here I need python magic
</code></pre>
<p>such that multiply_b... | 2 | 2016-08-05T12:06:29Z | 38,789,297 | <p>Here's an alternative that doesn't use <code>functools.partial</code>. Instead we define a function inside a function. The inner function "remembers" any of the local variables of the outer function that it needs (including the outer function's arguments). The magic that makes this happen is called <a href="https://... | 2 | 2016-08-05T12:29:07Z | [
"python",
"python-2.7",
"closures"
] |
Tensorflow 'features' format | 38,788,912 | <p>I'm a total begginer with AI and tensorflow, so please forgive if this is a dumb question.
I've trained a tensorflow network using a script based on this tutorial:</p>
<p><a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/t... | 2 | 2016-08-05T12:09:27Z | 38,794,950 | <p>The BaseEstimator class has better <a href="https://github.com/tensorflow/tensorflow/blob/5c44302d778f43a13bf1b97bffd0b2b6be46ae2f/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L369" rel="nofollow">documentation</a>.</p>
<pre><code>x: Matrix of shape [n_samples, n_features...]. Can be iterator that ... | 2 | 2016-08-05T17:36:19Z | [
"python",
"artificial-intelligence",
"tensorflow"
] |
Tensorflow 'features' format | 38,788,912 | <p>I'm a total begginer with AI and tensorflow, so please forgive if this is a dumb question.
I've trained a tensorflow network using a script based on this tutorial:</p>
<p><a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/t... | 2 | 2016-08-05T12:09:27Z | 38,902,557 | <p>I got the same error but I think this is because we are using an older release of tensorflow (I am on 0.8.0) and the fit method now can take a different input type 'input_fn' which I think can take the form of a dictionary, see <a href="https://github.com/tensorflow/tensorflow/blob/5c44302d778f43a13bf1b97bffd0b2b6be... | 0 | 2016-08-11T17:22:09Z | [
"python",
"artificial-intelligence",
"tensorflow"
] |
python multiprocessing.Queue.put/get's block parameter | 38,788,955 | <p>That is the Official Docs about multiprocessing.Queue.get</p>
<blockquote>
<p>get([block[, timeout]])</p>
<p>Remove and return an item from the queue. If
optional args block is True (the default) and timeout is None (the
default), block if necessary until an item is <code>available</code>. If timeout
i... | 0 | 2016-08-05T12:11:39Z | 38,789,203 | <blockquote>
<p>block if necessary until an item is available</p>
</blockquote>
<p>This simply means <code>Queue</code> is empty when you make the request and it will be blocked until you add an item to the <code>Queue</code>, unless you pass the argument <code>block = False</code> or set some <code>Timeout</code>.<... | 1 | 2016-08-05T12:24:07Z | [
"python"
] |
python multiprocessing.Queue.put/get's block parameter | 38,788,955 | <p>That is the Official Docs about multiprocessing.Queue.get</p>
<blockquote>
<p>get([block[, timeout]])</p>
<p>Remove and return an item from the queue. If
optional args block is True (the default) and timeout is None (the
default), block if necessary until an item is <code>available</code>. If timeout
i... | 0 | 2016-08-05T12:11:39Z | 38,789,231 | <p>In the first case where <code>block=True</code> is set, <code>"available"</code> means when an item is present on the queue and ready to be removed by <code>Queue.get()</code>. The point is that the thread/process will block <em>until</em> there is an item ready to be removed from the queue.</p>
<p>In the second ca... | 1 | 2016-08-05T12:25:31Z | [
"python"
] |
Python multiprocessing & pathos: import error | 38,788,994 | <p>I am writing some python code using multiprocessing & pathos. I have written a small test program to get used to using the mutiprocessing, that runs fine on my local machine, but it refuses to run on a different cluster. </p>
<p>I am getting the following error:</p>
<pre><code>Traceback (most recent call last)... | 2 | 2016-08-05T12:13:58Z | 39,038,036 | <p>I'm the <code>pathos</code> and <code>multiprocess</code> author. I think there are two possible reasons you can't find <code>_multiprocess</code>. The first, and by far most common reason, is that you don't have a C++ compiler. <code>multiprocessing</code> needs a C++ complier, and if you are on Windows, you have... | 0 | 2016-08-19T11:33:40Z | [
"python",
"multiprocessing",
"python-import",
"pathos"
] |
How to add custom function to admin forms? | 38,789,013 | <p>I would like to implement a function that updates <code>quantity</code> in <code>LibraryBook</code> each time the admin adds a book in <code>SingleBook</code> on the <code>admin</code> site. I have been searching for means to do so but to no avail. Any pointers including links to documentation would be very much app... | 2 | 2016-08-05T12:15:17Z | 38,789,694 | <p>Use <a href="https://docs.djangoproject.com/en/1.9/topics/signals/" rel="nofollow">signals</a>. Just attach <code>post_save</code> signal to <code>SingleBook</code> model and update according <code>LibraryBook</code> in it. <code>post_save</code> signal takes <code>created</code> argument, so you can determine if bo... | 0 | 2016-08-05T12:50:59Z | [
"python",
"django",
"python-2.7",
"django-models",
"django-admin"
] |
How to add custom function to admin forms? | 38,789,013 | <p>I would like to implement a function that updates <code>quantity</code> in <code>LibraryBook</code> each time the admin adds a book in <code>SingleBook</code> on the <code>admin</code> site. I have been searching for means to do so but to no avail. Any pointers including links to documentation would be very much app... | 2 | 2016-08-05T12:15:17Z | 38,789,904 | <h2>override save_model</h2>
<p>If you only want to make the changes when an admin updates a record, the best way is to override the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model" rel="nofollow">save_model</a> method in ModelAdmin</p>
<blockquote>
<p>Th... | 3 | 2016-08-05T13:00:16Z | [
"python",
"django",
"python-2.7",
"django-models",
"django-admin"
] |
Error installing mysql-connector-python on Amazon Linux AMI via pip-3.4 | 38,789,039 | <p>Apologies in advance if this is an easy fix, I have searched for an answer with no luck. </p>
<p>I'm trying to install the mysql-connector[-python] package on Amazon's Linux AMI. For my purposes, I want to use Python 3.4. I've installed Python 3.4 and pip-3.4 with yum and have successfully installed a few packages ... | 1 | 2016-08-05T12:16:36Z | 38,789,416 | <p>Answering my own question here, I know it doesn't solve the problem I had directly, but I've managed to get mysql-connector installed so that, in Python3(.4), <code>import mysql.connector</code> doesn't give any errors. Here's what I did: </p>
<pre><code> wget http://cdn.mysql.com/Downloads/Connector-Python/mysq... | 1 | 2016-08-05T12:35:40Z | [
"python",
"mysql",
"amazon-ec2",
"pip"
] |
Python multi module global variables. A bug in python? | 38,789,057 | <p>Recently I set up this example and am surprised by the results. I will demonstrate this with code:</p>
<p>File1: <strong>b.py</strong>:</p>
<pre><code>delta = 0.0
def example():
global delta
delta = 1
def ret_delta():
return delta
</code></pre>
<p>File2: <strong>a.py</strong>:</p>
<pre><code>from ... | 4 | 2016-08-05T12:17:11Z | 38,789,159 | <p>When you do</p>
<p><code>from b import *</code></p>
<p>in <code>a.py</code>, it imports all names defined in the module <code>b</code> (including <code>delta</code>) into <code>a</code>'s namespace. As <code>float</code> in an immutable type in Python, you can consider <code>a.delta</code> a completely separate va... | 5 | 2016-08-05T12:22:08Z | [
"python",
"python-3.x",
"module",
"global-variables"
] |
Python multi module global variables. A bug in python? | 38,789,057 | <p>Recently I set up this example and am surprised by the results. I will demonstrate this with code:</p>
<p>File1: <strong>b.py</strong>:</p>
<pre><code>delta = 0.0
def example():
global delta
delta = 1
def ret_delta():
return delta
</code></pre>
<p>File2: <strong>a.py</strong>:</p>
<pre><code>from ... | 4 | 2016-08-05T12:17:11Z | 38,789,198 | <p><code>from b import *</code> creates a series of new references in your <code>a</code> module globals. Each one of those copies the reference from <code>b</code> name. They are <em>independent</em> globals however.</p>
<p>Remember that in Python, names are merely <em>labels</em>; they are 'tied' to objects. You cre... | 2 | 2016-08-05T12:23:52Z | [
"python",
"python-3.x",
"module",
"global-variables"
] |
BASH "echo -n value" in Python 2.6/2.x or Python 3.x within a loop - single line without space | 38,789,153 | <p>Like in BASH, I can use "echo -n" within a loop and print all elements in an array (or list in Python) in a single line without any space " " character. See the "<strong>echo -n</strong> value" below in second for loop.</p>
<pre><code>Arun Sangal@pc MINGW64 ~
$ a=(1 2 33 four)
Arun Sangal@pc MINGW64 ~
$ for v in $... | 0 | 2016-08-05T12:21:54Z | 38,789,269 | <p>
You could to this:</p>
<pre><code>a = [1, 2, 3, 4]
concat = ""
for i in a:
concat = concat + str(i)
print concat
</code></pre>
<p>or without using a separate variable:</p>
<pre><code># needed if Python version 2.6+
from __future__ import print_function
a = [1, 2, 3, 4]
for i in a:
print(i, end="")
<... | 1 | 2016-08-05T12:27:26Z | [
"python",
"python-2.7",
"echo",
"line",
"pretty-print"
] |
BASH "echo -n value" in Python 2.6/2.x or Python 3.x within a loop - single line without space | 38,789,153 | <p>Like in BASH, I can use "echo -n" within a loop and print all elements in an array (or list in Python) in a single line without any space " " character. See the "<strong>echo -n</strong> value" below in second for loop.</p>
<pre><code>Arun Sangal@pc MINGW64 ~
$ a=(1 2 33 four)
Arun Sangal@pc MINGW64 ~
$ for v in $... | 0 | 2016-08-05T12:21:54Z | 38,789,505 | <p>If I understand you right, you are trying to print numbers without space between them? If so try the following. </p>
<pre><code>from __future__ import print_function
for i in range(1, 11):
print (i, end='')
</code></pre>
<p>Result</p>
<pre><code>12345678910
Process finished with exit code 0
</code></pre>
| 1 | 2016-08-05T12:40:34Z | [
"python",
"python-2.7",
"echo",
"line",
"pretty-print"
] |
How to call method of second parent class using method of child class in python? | 38,789,345 | <p>Below is my code:</p>
<pre><code>class Parent1(object):
def __init__(self):
print "!!! ___initialization Parent1___ !!!"
def method(self):
print "*** method of Parent1 is called ***"
class Parent2(object):
def __init__(self):
print "!!! ___initialization Parent2___ !!!"
d... | 0 | 2016-08-05T12:31:52Z | 38,789,442 | <pre><code>Parent2.method(self)
</code></pre>
<p>That's all you need - the <code>instance.method()</code> is just syntactic sugar for <code>ClassName.method(instance)</code>, so all you need to do is call it without the syntactic sugar and it'll do fine.</p>
<p>I changed the <code>Child</code> class to this:</p>
<pr... | 1 | 2016-08-05T12:36:56Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"multiple-inheritance"
] |
Return json from cherrypy before_handler tool | 38,789,389 | <p>I have a cherrypy application in which I've implemented a custom tool( a request filter) that I've attached to before_handler hook.
Bellow is the filter implementation:</p>
<pre><code>def custom_filter():
method = cherrypy.request.method
if method == 'POST':
print 'check POST token'
try:
... | 0 | 2016-08-05T12:34:02Z | 39,515,345 | <p>Based on <a href="http://stackoverflow.com/questions/32133758/stop-request-processing-in-cherrypy-and-return-200-response-from-a-tool">this</a> post and after some investigations I found a solution that works for me: stop the execution of the request and then add a response body.</p>
<pre><code>def custom_filter():... | 0 | 2016-09-15T15:49:33Z | [
"python",
"json",
"cherrypy"
] |
Any way to remove the last check in my converter? | 38,789,450 | <p>For an interview question I made a roman to integer converter:</p>
<pre><code>def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
mapping = {"I": 1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
numeral_list = list(s)
num_list = [[mapping[i], -1] f... | 0 | 2016-08-05T12:37:39Z | 38,790,217 | <p>What they are looking for before anything else is whether your code is easily readable and maintainable. That's more important than being right, in my opinion, although the interviewer may disagree -- so make it also correct.</p>
<p>Check for invalid inputs. What if they give a string like 'VXQIII'? Do you want to ... | 1 | 2016-08-05T13:13:58Z | [
"python"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 66... | 1 | 2016-08-05T12:37:57Z | 38,792,057 | <p>The way your array is constructed in numpy is different than it is in MATLAB.</p>
<p>Where your MATLAB array is <code>(y, x, z)</code>, your numpy array is <code>(z, y, x)</code>. Your 3d numpy array is a series of 'stacked' 2d arrays, so you're indexing "outside->inside" (for lack of a better term). Here's your ar... | 3 | 2016-08-05T14:46:39Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 66... | 1 | 2016-08-05T12:37:57Z | 38,792,064 | <p>I think that the problem is the way you create the matrix in numpy and also the different representation of matlab and numpy, why you don't use the same system in matlab and numpy</p>
<pre><code>> array = np.zeros((3,3,3),dtype=np.int)
> array
array([[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
... | 1 | 2016-08-05T14:46:55Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 66... | 1 | 2016-08-05T12:37:57Z | 38,792,658 | <p>MATLAB and Python index differently. To investigate this, lets create a linear array of number <code>1</code> to <code>8</code> and then <code>reshape</code> the result to be a <code>2</code>-by-<code>2</code>-by-<code>2</code> matrix in each language:</p>
<p>MATLAB:</p>
<pre><code>M_flat = 1:8
M = reshape(M_flat,... | 0 | 2016-08-05T15:16:17Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Numpy array and Matlab Matrix are mismatching [3D] | 38,789,455 | <p>The following octave code shows a sample 3D matrix using Octave/Matlab </p>
<pre><code>octave:1> A=zeros(3,3,3);
octave:2>
octave:2> A(:,:,1)= [[1 2 3];[4 5 6];[7 8 9]];
octave:3>
octave:3> A(:,:,2)= [[11 22 33];[44 55 66];[77 88 99]];
octave:4>
octave:4> A(:,:,3)= [[111 222 333];[444 555 66... | 1 | 2016-08-05T12:37:57Z | 38,803,741 | <p>I think that python uses this type of indexing to create arrays as shown in the following figure:</p>
<p><a href="https://www.google.com.eg/search?q=python+indexing+arrays+numpy&biw=1555&bih=805&source=lnms&tbm=isch&sa=X&ved=0ahUKEwia7b2J1qzOAhUFPBQKHXtdCBkQ_AUIBygC#imgrc=7JQu1w_4TCaAnM%3A" ... | 1 | 2016-08-06T11:25:30Z | [
"python",
"arrays",
"matlab",
"numpy",
"matrix"
] |
Cross validation predictor score the same | 38,789,457 | <p>I am trying to choose the csv file with data which has better prediction scores.
I am trying to determine cross validation scores using the following code:</p>
<pre><code>from __future__ import division
import os,csv
from sklearn import cross_validation
import numpy as np
from sklearn import svm
from sklearn import... | 0 | 2016-08-05T12:38:05Z | 38,790,226 | <p>The current code will not work because the variable CV (number of folds) of the cross_val_predict() function is bigger than the number of samples of the class 0 (False). If you lower it to less (or equal) than 6 it will work and you'll get an accuracy of 0.6 for a.csv and 0.625 for b.csv.</p>
| 1 | 2016-08-05T13:14:20Z | [
"python",
"scikit-learn",
"cross-validation"
] |
Save Python search results in variable and working with its elements | 38,789,519 | <p>Since I am pretty new to Python this might be an easy question for you!</p>
<p>I'd like to execute a process for all directories with a specific name in a given folder 'folder_a' (which includes 'folder_1','folder_2',...). </p>
<p>First question: How do I get a list of all the directories and folder_a? What I trie... | 1 | 2016-08-05T12:41:14Z | 38,790,074 | <p>To iterate over the contents of a directory, you can use python's excellent <code>os.walk</code> function:</p>
<pre><code>import os
for root, dirs, files is os.walk(root_dir):
for d in dirs:
if search_term in d:
do_something_to_directory(d)
</code></pre>
<p><code>os.walk()</code> generates tuples, with... | 4 | 2016-08-05T13:07:56Z | [
"python",
"loops"
] |
Python: TypeError: 'TreeNode' object is not iterable | 38,789,552 | <p>Here's my code:</p>
<pre><code># Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[Tree... | 0 | 2016-08-05T12:43:12Z | 38,792,236 | <p>I don't know how you get <em>that</em> </p>
<pre><code>TypeError: 'int' object is not iterable.
</code></pre>
<p>error. On both Python 2.6 and 3.6 I get the error mentioned in your question's title:</p>
<pre><code>TypeError: 'TreeNode' object is not iterable
</code></pre>
<p>This is because <code>return TreeNode... | 1 | 2016-08-05T14:55:01Z | [
"python",
"algorithm",
"binary-tree"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.... | 1 | 2016-08-05T12:43:15Z | 38,789,691 | <p>You could allow <code>J</code> to take as many arguments as necessary, then multiply the final list that f, g, and h give:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
def multiply(mylist):
return reduce(lambda a, b: a*b, mylist)
myfuncs = [f... | 3 | 2016-08-05T12:50:53Z | [
"python",
"python-3.x",
"functional-programming"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.... | 1 | 2016-08-05T12:43:15Z | 38,789,698 | <p>The variable number of arguments problem can be resolved by this:</p>
<pre><code>def f(*args): return sum(map(lambda x: x**2, args))
def g(*args): return sum(map(lambda x: x**3, args))
def h(*args): return sum(map(lambda x: x**4, args))
</code></pre>
<p>And then you could simply define the <code>J</code> functio... | 0 | 2016-08-05T12:51:12Z | [
"python",
"python-3.x",
"functional-programming"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.... | 1 | 2016-08-05T12:43:15Z | 38,789,715 | <p>A function can accept arbitrarily many arguments using <code>*</code> like this:</p>
<pre><code>def J(*args):
</code></pre>
<p>This will store all of <code>J</code>'s arguments in the list <code>args</code>. That list can then be converted back into multiple arguments to call other functions like this:</p>
<pre><... | 3 | 2016-08-05T12:52:15Z | [
"python",
"python-3.x",
"functional-programming"
] |
Programmatically define a new function from a list of other functions | 38,789,554 | <p>I have:</p>
<pre><code>def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
</code></pre>
<p>And I'd like to make a new function:</p>
<pre><code>def J(x, y):
return f(x,y)*g(x,y)*h(x,y)
</code></pre>
<p>However, I am unable to find a way to do this programmatically.... | 1 | 2016-08-05T12:43:15Z | 38,790,024 | <p>Another option:</p>
<pre><code>from functools import reduce, partial
from operator import mul
def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4
myFunctions = [f,g,h]
J = partial(lambda funcs, *args: reduce(mul, (func(*args) for func in funcs), 1), myFunctions)
print ... | 1 | 2016-08-05T13:06:00Z | [
"python",
"python-3.x",
"functional-programming"
] |
Python: Do not map empty result of multiprocessing.Pool( ) | 38,789,568 | <p>Program have function that may return None value, for minimize spend time this function calling in parallel workers.
In code below, result of this function have the "None" values, how to exclude this is values from the "ret"?</p>
<pre><code>#!/usr/bin/python
import sys,multiprocessing,time
maxNumber = sys.maxint+2
... | 1 | 2016-08-05T12:44:17Z | 38,790,023 | <p><code>oddCheck</code> returns <code>None</code> when <code>num</code> is not a even number (you do not have a return statement in this case, so <code>None</code> will be returned).</p>
<p>If you want to avoid <code>None</code> results, just use a list comprehension to filter them:</p>
<pre><code>ret = [x for x in ... | 2 | 2016-08-05T13:06:00Z | [
"python",
"multithreading",
"dictionary"
] |
How to set a general option in Python to display only N digits everywhere? | 38,789,609 | <p>I want to work with 3 digits after the decimal point in Python. What is the relevant setting to modify ?</p>
<p>I want that <code>1.0 / 3</code> would return 0.333, and not 0.3333333333333333 like it is the case in my Jupyter Notebook, using python 2.7.11 and Anaconda 4.0.0.</p>
<p>In my research, I heard about th... | 0 | 2016-08-05T12:46:18Z | 38,789,920 | <p>use numpy and try this;</p>
<pre><code>round(1.0/3, 3)
</code></pre>
<p>or</p>
<pre><code>>>> 1.0/3
0.3333333333333333
>>> '{:0.3f}'.format(1.0/3)
'0.333'
</code></pre>
| 0 | 2016-08-05T13:01:16Z | [
"python",
"number-formatting"
] |
How to set a general option in Python to display only N digits everywhere? | 38,789,609 | <p>I want to work with 3 digits after the decimal point in Python. What is the relevant setting to modify ?</p>
<p>I want that <code>1.0 / 3</code> would return 0.333, and not 0.3333333333333333 like it is the case in my Jupyter Notebook, using python 2.7.11 and Anaconda 4.0.0.</p>
<p>In my research, I heard about th... | 0 | 2016-08-05T12:46:18Z | 38,791,090 | <p>There is no "one-time" solution to your problem.
And I think that your approach might be a little misguided.</p>
<p>I suppose that your interaction with Jupyter or Ipython has lead you to the conclusion that python is quite handy as a numerical calculator. Unfortunately both of the aforementioned programs are just ... | 0 | 2016-08-05T13:57:57Z | [
"python",
"number-formatting"
] |
How to retrieve a total pixel value above an average-based threshold in Python | 38,789,670 | <p>Currently, I am practicing with retrieving the total of the pixel values above a threshold based on the mean of the whole image. (I am very new to Python). I am using Python 3.5.2, and the above code was copied from the Atom program I am using to write and experiment with the code.</p>
<p>For the time being, I am j... | 1 | 2016-08-05T12:49:53Z | 38,790,729 | <p>When you did (red > threshold) you got a mask such that all the pixels in red that are above the thrshold got the value 1 and 0 other wise. Now to get the values you can just multiply the mask with the red channel. The multiplcation will zero all the values that are less than the threshold and will leave the values ... | 1 | 2016-08-05T13:39:01Z | [
"python",
"python-3.x",
"image-processing",
"pixels",
"threshold"
] |
How to retrieve a total pixel value above an average-based threshold in Python | 38,789,670 | <p>Currently, I am practicing with retrieving the total of the pixel values above a threshold based on the mean of the whole image. (I am very new to Python). I am using Python 3.5.2, and the above code was copied from the Atom program I am using to write and experiment with the code.</p>
<p>For the time being, I am j... | 1 | 2016-08-05T12:49:53Z | 38,791,228 | <p>Another method I found that worked (providing the total pixel value) was to use masked values:</p>
<pre><code>import numpy.ma as ma
...
red_val = ma.masked_outside(red, threshold, 255).sum()
</code></pre>
<p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_outside.html#num... | 0 | 2016-08-05T14:05:31Z | [
"python",
"python-3.x",
"image-processing",
"pixels",
"threshold"
] |
Extracting specific data from multiple strings | 38,789,708 | <p>Been playing around with this. Haven't cleaned it up yet. It basically does what nslookup does. Takes a (or multiple) host name from a text file and returns the corressponding IP address. </p>
<pre><code>def getIPAddresses(file):
emptyList = []
someString = ".com"
with open(file, "r+") as output:
... | 0 | 2016-08-05T12:51:46Z | 38,789,901 | <p>So your code returns a tuple, tuples can be indexed much like a list.</p>
<p>here's what I tested </p>
<pre><code>google = socket.getaddrinfo('www.google.com', 80)
google[0][4]
returns ('74.125.141.104', 80)
</code></pre>
<p>thus to get the ip address associated
do</p>
<pre><code>google[0][4][0]
</code></pre>
<... | 0 | 2016-08-05T13:00:08Z | [
"python",
"string",
"loops"
] |
Selecting rows from Pandas Series where rows are arrays | 38,789,717 | <p>I'm trying to analyze US polling data, specifically, I'm trying to work out which States are safe, marginal, or tight ('closeness'). I have a dataframe with survey results by time and their 'closeness'. I'm using this Pandas statement to get a summary of the 'closeness' entries.</p>
<pre><code>s=self.daily.groupby(... | 1 | 2016-08-05T12:52:29Z | 38,789,874 | <p>Say you have a DataFrame with a series of lists, say:</p>
<pre><code>df = pd.DataFrame({'a': [['safe'], ['safe', 'tight'], []]})
</code></pre>
<p>Then to see which ones are exactly safe, you can use:</p>
<pre><code>In [7]: df.a.apply(lambda x: x == ['safe'])
Out[7]:
0 True
1 False
2 False
Name: a, dtyp... | 1 | 2016-08-05T12:58:49Z | [
"python",
"pandas"
] |
Selecting rows from Pandas Series where rows are arrays | 38,789,717 | <p>I'm trying to analyze US polling data, specifically, I'm trying to work out which States are safe, marginal, or tight ('closeness'). I have a dataframe with survey results by time and their 'closeness'. I'm using this Pandas statement to get a summary of the 'closeness' entries.</p>
<pre><code>s=self.daily.groupby(... | 1 | 2016-08-05T12:52:29Z | 38,796,232 | <p>dataframe sample given by OP :</p>
<pre><code>In[66]:df
Out[66]:
Date Democratic share Margin Method Other share 0 2008-11-04 0.378894 -0.215351 Election 0.026861
1 2008-11-04 0.387404 -0.215765 Election 0.009427
2 2008-11-04 0.388647 -0.198512 Elect... | 0 | 2016-08-05T19:06:59Z | [
"python",
"pandas"
] |
Selecting rows from Pandas Series where rows are arrays | 38,789,717 | <p>I'm trying to analyze US polling data, specifically, I'm trying to work out which States are safe, marginal, or tight ('closeness'). I have a dataframe with survey results by time and their 'closeness'. I'm using this Pandas statement to get a summary of the 'closeness' entries.</p>
<pre><code>s=self.daily.groupby(... | 1 | 2016-08-05T12:52:29Z | 38,797,268 | <p>I think constructing the series <code>s</code> by using <code>.unique()</code> is not the best way of attacking this problem. Try using <code>pd.crosstab</code> instead.</p>
<pre><code>import pandas as pd
daily = pd.DataFrame({'State': ['AK', 'AL', 'CA', 'CO', 'CO', 'CO', 'FL',
'FL'... | 0 | 2016-08-05T20:23:50Z | [
"python",
"pandas"
] |
Euclidean distance between elements in two different matrices? | 38,789,757 | <p>I am trying to determine the Euclidean distance for my documents from their centroids. The dimensions of the two arrays in question (<code>points</code> and <code>centers</code>) satisfy the <code>XA</code> and <code>XB</code> dimensional requirements for <code>scipy.spatial.distance.cdist</code>, but I don't know w... | 0 | 2016-08-05T12:54:27Z | 38,790,315 | <p>Just a small change that you need to do:</p>
<pre><code>cdist(X.toarray(),centers)
</code></pre>
<p>Since X is an object of type <code>scipy.sparse.csr.csr_matrix</code> it will not be directly taken as a valid input by the scipy function. The method toarray() converts it to a valid numpy array</p>
| 2 | 2016-08-05T13:19:11Z | [
"python",
"numpy"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried... | 1 | 2016-08-05T12:58:11Z | 38,789,951 | <pre><code>y = []
for e in x:
if e == 2:
break
y.append(e)
</code></pre>
<p>?</p>
| 2 | 2016-08-05T13:02:48Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried... | 1 | 2016-08-05T12:58:11Z | 38,789,986 | <p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.takewhile" rel="nofollow"><code>itertools.takewhile</code></a>:</p>
<pre><code>>>> x = [1,1,1,2,1,1]
>>> import itertools
>>> y = list(itertools.takewhile(lambda i: i != 2, x))
>>> y
[1, 1, 1]
</cod... | 2 | 2016-08-05T13:04:14Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried... | 1 | 2016-08-05T12:58:11Z | 38,789,994 | <p>Try this:</p>
<pre><code>x = [1,1,1,2,1,1]
b = 2
try:
y = x[:x.index(b)]
except ValueError:
y = x[:]
</code></pre>
<p>For example:</p>
<pre><code>In [10]: x = [1,1,1,2,1,1]
...: b = 2
...:
...: try:
...: y = x[:x.index(b)]
...: except ValueError:
...: # b was not found in... | 2 | 2016-08-05T13:04:41Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried... | 1 | 2016-08-05T12:58:11Z | 38,790,186 | <p>Way to get things done with <a href="https://docs.python.org/2/reference/expressions.html#generator-expressions" rel="nofollow"><strong>generator expression</strong></a>:</p>
<pre><code>x = ['a', 'a', 'a', 'b', 'a', 'a']
items = list(next(iter([])) if item == 'b' else item for item in x)
print items
['a', 'a', 'a']... | 1 | 2016-08-05T13:12:50Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried... | 1 | 2016-08-05T12:58:11Z | 38,790,190 | <p>Though it is somehow similar to Will's answer, but in here it shows the use of <a href="https://docs.python.org/3/library/functions.html?highlight=slice#slice" rel="nofollow"><code>slice</code></a> built-in slicing object:</p>
<pre><code>>>> x = ['a','a','a','b','a','a']
>>> s = slice(x.index('b'... | 0 | 2016-08-05T13:12:58Z | [
"python",
"arrays",
"list",
"for-loop"
] |
Copying part of a list in Python | 38,789,853 | <p>I've searched for a relevant thread on how to do this but I cannot find anything.</p>
<p>I have an array:</p>
<pre><code>x = [a,a,a,b,a,a]
</code></pre>
<p>I want to copy the elements of the array into a new array until I find 'b'. I tried to do this with a loop but I get an error that "y is not defined", I tried... | 1 | 2016-08-05T12:58:11Z | 38,790,364 | <p>I would split the array by the <code>b</code> index:</p>
<pre><code>>>> x = ['a','a','a','b','a','a']
>>> c = x.index('b')
>>> x[:c]
['a', 'a', 'a']
>>> x[c:]
['b', 'a', 'a']
</code></pre>
| 0 | 2016-08-05T13:20:52Z | [
"python",
"arrays",
"list",
"for-loop"
] |
regular expression for parentheses within quotes | 38,789,869 | <p>I want to split a string into several parts in parentheses, but the quoted things (possibly including parentheses) should be treated as a single symbol. For example, the string </p>
<p>(id1, "Hello simple"), (id2, "Hello \n weird (all chars) Ã@")</p>
<p>should be split into two parts</p>
<p>1) id1, "Hello simple... | -1 | 2016-08-05T12:58:41Z | 38,790,105 | <p>If you really need to use <code>regex</code>, this works with the current string from your post:</p>
<pre><code>import re
pat = re.compile(r'\(([a-zA-Z0-9"\(\)\s]+)\)')
matches = re.findall(pat, '(Hello "(world)"), (2016)')
# ['Hello "(world)"', '2016']
</code></pre>
<p>However, the <code>split</code> function may... | 0 | 2016-08-05T13:09:22Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,911 | <p>Try this:</p>
<pre><code>max = list[0]
for i in range(1,len(list)):
if len(list[i]) > max:
max = len(list[i])
</code></pre>
| 0 | 2016-08-05T13:00:48Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,976 | <pre><code>tempMaxDig = 0
for item in numList:
num = len(str(item))
if num > tempMaxDig:
tempMaxDig = num
return tempMaxDig
</code></pre>
| 0 | 2016-08-05T13:03:42Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,989 | <p>Try this</p>
<pre><code>mylist = [3, 14, 24, 6, 157, 132, 12]
print (len(str(max([abs(element) for element in mylist]))))
#3
#This will work for negative numbers too
</code></pre>
| 2 | 2016-08-05T13:04:25Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,789,992 | <p>Just use :</p>
<pre><code>len(str(max(list)))
</code></pre>
<p>what we are doing here finding the maximum number, then lenght of that.</p>
| 0 | 2016-08-05T13:04:31Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,075 | <p>"Try this</p>
<pre><code>mylist = [3, 14, 24, 6, 157, 132, 12]
print (len(str(max(mylist)))
</code></pre>
<p>"</p>
<p>Sorry I would comment but < 50 rep. Credit to @soumendra</p>
<p>Soumendra's solution works but not for negative numbers. Easy way to do this is:</p>
<pre><code>mylist = [3, 14, 24, 6, 157, 13... | 0 | 2016-08-05T13:07:57Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,108 | <p>The key is to treat the elements as strings so you can ask for their length or number of digits.</p>
<p>Some code </p>
<pre><code>#Your list
L = [ 3 , 14 , 24 , 6 , 157 , 132 ,12]
# Imperative
max_digits = 0
for element in L:
n_digits = len(str(element))
if n_digits > max_digits:
max_digits = n... | 0 | 2016-08-05T13:09:30Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,136 | <p>In case your list contains negative numbers you could pass generator expression calling <a href="https://docs.python.org/3.5/library/functions.html#abs" rel="nofollow"><code>abs</code></a> as an argument for <a href="https://docs.python.org/3.5/library/functions.html#max" rel="nofollow"><code>max</code></a>:</p>
<p... | 3 | 2016-08-05T13:10:29Z | [
"python"
] |
How to find the maximum no of digits in the list in python | 38,789,873 | <p>For example
If the list contains numbers 3 , 14 , 24 , 6 , 157 , 132 ,12
It should give the maximum no of digits as 3 </p>
| 1 | 2016-08-05T12:58:47Z | 38,790,377 | <p>The first requirement is to decide <em>exactly</em> what <strong>you</strong> mean by "number of digits." For example, <code>-2.1352</code> contains ... how many digits? One? Five? Six? Seven? An argument could be made in favor of each of these.</p>
<p>Then, in the case of <em>floating point</em> numbers, there's... | 1 | 2016-08-05T13:21:42Z | [
"python"
] |
When using scipy.optimize.fmin_bfgs I got TypeError: f() missing 1 required positional argument: | 38,789,983 | <p>I'm trying to calculate minima of the six-hump camelback function using scipy.optimize.fmin_bfgs() function. Here is my code: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
def f(x,y):
return (4 - 2.1*x**2 + x**4/3)*x**2 + x*y + (4*y**2 - 4)*y**2
x0 = [0,0]
opti... | 2 | 2016-08-05T13:04:10Z | 38,790,301 | <p>Per this page there should be one array argument to <code>f</code>: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html</a></p>
<p>Do instead:</p>
<pre><code>def f(x):
return (... | 2 | 2016-08-05T13:18:45Z | [
"python",
"numpy",
"scipy"
] |
How to get all the tags in an XML using python? | 38,790,012 | <p>I have been researching in the Python Docs for a way to get the tag names from an XML file, but I haven't been very successful. Using the XML file below, one can get the country name tags, and all its associated child tags. Does anyone know how this is done?</p>
<pre><code><?xml version="1.0"?>
<data>
... | 0 | 2016-08-05T13:05:27Z | 38,790,079 | <p>Look into the built-in XML functionality of Python, traverse the document recursively and collect all tags in a set.</p>
| -1 | 2016-08-05T13:08:01Z | [
"python",
"xml",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.