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 |
|---|---|---|---|---|---|---|---|---|---|
Delete trailing marks ]] | 40,056,331 | <p>Doing some regex and I can't sus out how I can get rid of the ]] marks from this string</p>
<p>Regex:</p>
<pre><code><title><!\[CDATA\[(.*?)</title>
</code></pre>
<p>String:</p>
<pre><code><item>
<title><![CDATA[Coronation Street star Jean Alexander dies aged 90]]><... | -2 | 2016-10-15T07:28:10Z | 40,056,415 | <p>You have to escape the square brackets in the end too.</p>
<pre><code>string = "<title><![CDATA[Coronation Street star Jean Alexander dies aged 90]]></title>"
result = re.findall(r"\[.*\[(.*?)\]\]", string)
print(result)
</code></pre>
| 0 | 2016-10-15T07:37:33Z | [
"python",
"regex"
] |
Delete trailing marks ]] | 40,056,331 | <p>Doing some regex and I can't sus out how I can get rid of the ]] marks from this string</p>
<p>Regex:</p>
<pre><code><title><!\[CDATA\[(.*?)</title>
</code></pre>
<p>String:</p>
<pre><code><item>
<title><![CDATA[Coronation Street star Jean Alexander dies aged 90]]><... | -2 | 2016-10-15T07:28:10Z | 40,056,953 | <p>I infer that you'd like an answer with respect to using a regex with python. So, here's some code that performs the desired action:</p>
<pre><code>import re
string = "<title><![CDATA[Coronation Street star Jean Alexander dies aged 90]]></title>"
result = re.findall(r"\[.*\[(.*?)\]\]", string)
pri... | 0 | 2016-10-15T08:45:36Z | [
"python",
"regex"
] |
Is it required to build tensorflow from source to use inception? | 40,056,498 | <p>I have already asked <a href="https://github.com/tensorflow/models/issues/534" rel="nofollow">this question </a> in their repository, but they redirected me here on stack overflow. So, is it required to build <code>tensorflow</code> from the sources to use <code>inception</code>? Or a binary install of <code>tensorf... | 0 | 2016-10-15T07:47:08Z | 40,059,248 | <p>It works fine from the binary install. </p>
<p>The <a href="https://github.com/tensorflow/models/" rel="nofollow">tensorflow-models repo</a> has an <a href="https://github.com/tensorflow/models/blob/master/slim/slim_walkthough.ipynb" rel="nofollow">example notebook</a> with the boiler-plate code you need to get it... | 0 | 2016-10-15T12:52:26Z | [
"python",
"machine-learning",
"tensorflow"
] |
Why sessionid is empty string return response Set-Cookie on django? | 40,056,543 | <p>There is question for me , why django sessionid is empty value, return set-cookie</p>
<p>however sessionid value is empty but set Set-Cookie,</p>
<p>request on cookie :</p>
<pre><code>Cookie: sessionid=;csrftoken=BF8nOVWsMJaX9Gi3aJijGSO97iTyLpNY
</code></pre>
<p>here sessionid is empty now response this request ... | 0 | 2016-10-15T07:52:52Z | 40,058,848 | <p>Try to login to you django project and then check the <code>sessionid</code> value. You will see the cookie's value there. If Django does need to keep some data in the cookie, it will not. </p>
| 0 | 2016-10-15T12:10:09Z | [
"python",
"django",
"cookies"
] |
Pydev import not working, but Terminal import does | 40,056,578 | <p>I recently installed a library (obspy) on my MBP with anaconda. The installation seemed successful but for some reason I can't get it to run in my Eclipse (PyDev) environment. Going into the python shell on Terminal does however work. How can make the two consistent?</p>
| 1 | 2016-10-15T07:56:00Z | 40,130,637 | <p>Check that you have the same Python in both places and the same PYTHONPATH in both cases.</p>
<p>To do that, create a script with:</p>
<pre><code>import sys
print('\n'.join(sorted(sys.path)))
print(sys.executable)
</code></pre>
<p>and run from your terminal and from Eclipse to see if you have the same thing in bo... | 0 | 2016-10-19T11:49:53Z | [
"python",
"anaconda",
"pydev"
] |
pexpect child.before and child.after is empty | 40,056,626 | <pre><code>>>> ssh_stuff
['yes/no', 'Password:', 'password', 'Are you sure you want to continue connecting']
>>> prompt
['$', '#']
>>> child = pexpect.spawn('ssh kumarshubham@localhost')
>>> child.expect(ssh_stuff)
1
>>> child.sendline(getpass.getpass())
Password:
11
>&g... | 0 | 2016-10-15T08:01:44Z | 40,058,683 | <p>To match a literal <code>$</code> char you have to use <code>\$</code> so try with <code>prompt = ['\$', '#']</code> (or simply <code>prompt = '[$#]'</code>). And according to pexpect's doc:</p>
<blockquote>
<p>The <code>$</code> pattern for end of line match is useless. The <code>$</code> matches the end of stri... | 0 | 2016-10-15T11:52:26Z | [
"python",
"pexpect"
] |
print a list of dictionaries in table form | 40,056,747 | <p>assume I have this list as global list </p>
<pre><code> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'},
{'Major': 'Physics', 'GPA': '2.9', 'Name':'Emily'},
{'Major':'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}]
</code></pre>
<p>and a want a function print() to print it as <... | -2 | 2016-10-15T08:18:11Z | 40,056,776 | <pre><code>for dicts in dataset:
print(dicts.get('Name')),
print(dicts.get('Major')),
print(dicts.get('GPA')),
</code></pre>
<p>Example </p>
<pre><code>>>> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name': 'Emily'}, {'Major': 'Mathematics',... | 0 | 2016-10-15T08:22:06Z | [
"python"
] |
print a list of dictionaries in table form | 40,056,747 | <p>assume I have this list as global list </p>
<pre><code> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'},
{'Major': 'Physics', 'GPA': '2.9', 'Name':'Emily'},
{'Major':'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}]
</code></pre>
<p>and a want a function print() to print it as <... | -2 | 2016-10-15T08:18:11Z | 40,056,796 | <p>you can use module <a href="https://pypi.python.org/pypi/tabulate" rel="nofollow">tabulate</a></p>
<pre><code>>>> import tabulate
>>> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name': 'Emily'}, {'Major': 'Mathematics', 'GPA': '3.5', 'Name': ... | 3 | 2016-10-15T08:25:06Z | [
"python"
] |
print a list of dictionaries in table form | 40,056,747 | <p>assume I have this list as global list </p>
<pre><code> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'},
{'Major': 'Physics', 'GPA': '2.9', 'Name':'Emily'},
{'Major':'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}]
</code></pre>
<p>and a want a function print() to print it as <... | -2 | 2016-10-15T08:18:11Z | 40,056,851 | <p>How about this: </p>
<pre><code>from __future__ import print_function
dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'},Physics', 'GPA': '2.9', 'Name': 'Emily'},Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}]
[print("%s %s: %s\n"%(item['Name'],item['Major'],item['GPA'])) for item in dataset]
</code></p... | 0 | 2016-10-15T08:32:37Z | [
"python"
] |
python calling variables from another script into current script | 40,056,800 | <p>I'm trying to call a variable from another script into my current script but running into "variable not defined" issues.</p>
<p>botoGetTags.py</p>
<pre><code>20 def findLargestIP():
21 for i in tagList:
22 #remove all the spacing in the tags
23 ec2Tags = i.strip()
24 ... | 0 | 2016-10-15T08:25:20Z | 40,056,824 | <p>You imported the module, not the function. So you need to refer to the function via the module:</p>
<pre><code>import botoGetTags
largestIP = botoGetTags.findLargestIP()
</code></pre>
<p>Alternatively you could import the function directly:</p>
<pre><code>from botoGetTags import findLargestIP
largestIP = findLarg... | 2 | 2016-10-15T08:27:56Z | [
"python",
"function",
"import"
] |
What does the following segment do - Pyhon | 40,056,813 | <p>I have a problem with the following function. I can't understand what it does, because I'm new to Python, can you help me, please. Thanks in advance.</p>
<pre><code>def foo(limit):
a = [True] * limit
a[0] = a[1] = False
for (i,b) in enumerate(a):
if b:
yield i
for n in xrange(i*i... | -2 | 2016-10-15T08:26:51Z | 40,093,364 | <p>This is example of Binary Indexed Tree. </p>
| 0 | 2016-10-17T18:35:55Z | [
"python"
] |
Nested For Loop to Access MultiIndex Pandas Dataframe | 40,056,866 | <p>I have a Dataframe with 3 levels of MultiIndex. They are "Category", "Brand" and "Zip Code". There is one series ("Sales") in the Dataframe. I'd like to loop around the "Category" and "Brand" index levels and serve up a Dataframe with "Zip Code" as the Index and "Sales" as a series.</p>
<p>When I only have two mult... | 0 | 2016-10-15T08:34:03Z | 40,058,345 | <p>Not sure how you want your DataFrame grouped, but I see 2 options. The first option will give you a DataFrame with the zip codes as the index ordered as they currently are within the MultiIndex. The second option will group the zip codes such that you have an index of only the unique zip codes and the sales numbers ... | 0 | 2016-10-15T11:16:15Z | [
"python",
"pandas",
"dataframe"
] |
How to create an instance of a class inside a method within the class, python | 40,056,915 | <p>My class deals with lists of ints and computing them so they don't have reoccurring values. I have implemented a new method 'intersect' which takes in two intSet objects and creates a new object with the values that appear in both objects lists (vals). </p>
<p>Origially i was creating a new list inside the method (... | 0 | 2016-10-15T08:38:57Z | 40,056,942 | <p>It's intSet, not inSet, you've misspelled it in your intersect method. And as a habit it's better to start your classes with a capital (although there are no fixed rules, this is a habit widely adhered to).</p>
<p>About the curly braces, they are not only for dictionaries but also for Python sets. So by using them... | 1 | 2016-10-15T08:42:59Z | [
"python",
"class",
"oop",
"methods"
] |
Python ValueError: too many values to unpack in a While loop | 40,056,973 | <p>I am getting this exception from the following code and mainly form the second line in the while loop, any hint please? Thank you.</p>
<pre><code>def SampleLvl(self, mods, inds, M):
calcM = 0
total_time = 0
p = np.arange(1, self.last_itr.computedMoments()+1)
psums_delta = _empty_obj()
psums_fine... | 0 | 2016-10-15T08:47:54Z | 40,057,047 | <p>In this line:</p>
<pre><code>values, samples_time = self.fn.SampleLvl(inds=inds, M=curM)
</code></pre>
<p>you assign the result of <code>SampleLvl</code> to 2 variables, but your function, <code>SampleLvl</code>, that you seem to call recursively in that line, returns a 4-tuple.
I assume that <code>self.fn.SampleL... | 0 | 2016-10-15T08:56:34Z | [
"python",
"python-2.7"
] |
Python ValueError: too many values to unpack in a While loop | 40,056,973 | <p>I am getting this exception from the following code and mainly form the second line in the while loop, any hint please? Thank you.</p>
<pre><code>def SampleLvl(self, mods, inds, M):
calcM = 0
total_time = 0
p = np.arange(1, self.last_itr.computedMoments()+1)
psums_delta = _empty_obj()
psums_fine... | 0 | 2016-10-15T08:47:54Z | 40,057,254 | <p>You will get a <code>ValueError: too many values to unpack</code> when you try and assign more variables into less variables. </p>
<p>For example, if you had a function <code>foo()</code> which returns <code>(a, b, c)</code> you could do: <code>a, b, c = foo()</code> but you would get an error if you tried to do <c... | 0 | 2016-10-15T09:16:13Z | [
"python",
"python-2.7"
] |
string is a JSON object or JSON array in Python? | 40,056,998 | <p>I am reading JSON file line by line. Few lines contain JSON objects while other contains JSON array. I am using <code>json.loads(line)</code> function to get JSON from each line. </p>
<pre><code>def read_json_file(file_name):
json_file = []
with open(file_name) as f:
for line in f:
json_... | 2 | 2016-10-15T08:50:32Z | 40,057,142 | <p>The problem with your code - if line does not contain <em>full</em> JSON object - it seldom does - it will nearly always fail.</p>
<p>Unlike in Java, in Python JSON is naturally represented by hierarchical mixture of list and dictionary elements. So, if you are looking for list elements in your JSON, you may use r... | 0 | 2016-10-15T09:05:36Z | [
"python",
"json",
"python-3.x"
] |
string is a JSON object or JSON array in Python? | 40,056,998 | <p>I am reading JSON file line by line. Few lines contain JSON objects while other contains JSON array. I am using <code>json.loads(line)</code> function to get JSON from each line. </p>
<pre><code>def read_json_file(file_name):
json_file = []
with open(file_name) as f:
for line in f:
json_... | 2 | 2016-10-15T08:50:32Z | 40,057,410 | <p>In python, JSON object is converted into <code>dict</code> and JSON list is converted into <code>list</code> datatypes.</p>
<p>So, if you want to check the line content which should be valid <strong>JSON</strong>, is <code>JSON Object</code> or <code>JSON Array</code>, then this code will helps you:-</p>
<pre><cod... | 2 | 2016-10-15T09:35:39Z | [
"python",
"json",
"python-3.x"
] |
Create AbstractBaseUser | 40,057,001 | <p>Try to create AbstractBaseUser and custom auth.</p>
<p>models.py </p>
<pre><code>class Account(AbstractBaseUser):
account_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
birthday_date = models.DateField(blank=True, n... | 0 | 2016-10-15T08:50:47Z | 40,058,619 | <p>Look at you <code>Account</code> model. There is no <code>password</code> field. You should add this field and than you can save data there.</p>
| 0 | 2016-10-15T11:46:04Z | [
"python",
"django",
"postgresql"
] |
using confusion matrix as scoring metric in cross validation in scikit learn | 40,057,049 | <p>I am creating a pipeline in scikit learn, </p>
<pre><code>pipeline = Pipeline([
('bow', CountVectorizer()),
('classifier', BernoulliNB()),
])
</code></pre>
<p>and computing the accuracy using cross validation</p>
<pre><code>scores = cross_val_score(pipeline, # steps to convert raw messages into ... | 0 | 2016-10-15T08:56:54Z | 40,058,433 | <p>Short answer is "you cannot".</p>
<p>You need to understand difference between <code>cross_val_score</code> and cross validation as model selection method. <code>cross_val_score</code> as name suggests, works only on <strong>scores</strong>. Confusion matrix is not a score, it is a kind of summary of what happened ... | 1 | 2016-10-15T11:26:39Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Correct div-class combination for soup.select() | 40,057,058 | <p>I'm developing some scraping code and it keeps returning some errors which i imagine others might be able to help with. </p>
<p>First I run this snippet:</p>
<pre><code>import pandas as pd
from urllib.parse import urljoin
import requests
base = "http://www.reed.co.uk/jobs"
url = "http://www.reed.co.uk/jobs?dat... | 2 | 2016-10-15T08:57:43Z | 40,062,555 | <p>You can just keep looping until there is no next page:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
base = "http://www.reed.co.uk"
url = "http://www.reed.co.uk/jobs?datecreatedoffset=Today&pagesize=100"
def all_urls():
r = requests.get(url).content
so... | 0 | 2016-10-15T18:13:13Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Why is pandas map slower than list comprehension | 40,057,064 | <p>Does someone know why pandas/numpy map is slower then list comprehension?
I thought I could optimize my code replacing the list comprehensions by map. Since map doesn't need the list append operation.</p>
<p>Here is one test:</p>
<pre><code>df = pd.DataFrame(range(100000))
</code></pre>
<p><strong>List comprehens... | 1 | 2016-10-15T08:58:11Z | 40,057,151 | <p>Here are my results:</p>
<p>list comprehension:</p>
<pre><code>In [33]: %timeit df["A"] = [x for x in df[0]]
10 loops, best of 3: 72.6 ms per loop
</code></pre>
<p>simple column assignment:</p>
<pre><code>In [34]: %timeit df["A"] = df[0]
The slowest run took 5.75 times longer than the fastest. This could mean th... | 0 | 2016-10-15T09:06:08Z | [
"python",
"performance",
"pandas",
"list-comprehension"
] |
Django get form not ordered list | 40,057,092 | <p>i changed my admin form when creating new objects to hide some fields, but it orders fields alphabetically, i want to order them as they are in my model.any suggestions?</p>
<pre><code>_add_fields = ('name', 'size', 'slug',
'img', 'description', 'quantity')
def get_form(self, request, obj=None, **kw... | 1 | 2016-10-15T09:00:51Z | 40,057,855 | <p>You need to use <code>OrderedDict</code> from <code>collections</code> module to achieve that:</p>
<pre><code>from django.contrib import admin
from collections import OrderedDict
class ItemAdmin(admin.ModelAdmin):
_add_fields = ('name', 'category',
'img', 'description', 'quantity')
de... | 1 | 2016-10-15T10:24:21Z | [
"python",
"django",
"django-admin"
] |
Python dynamic function building and closure rule | 40,057,122 | <p>While interactively executing the following code in <a href="http://pythontutor.com/visualize.html" rel="nofollow">http://pythontutor.com/visualize.html</a>, the frame of each call to <code>build_match_and_apply_functions</code> appears gray in the graphical view:</p>
<p><a href="https://i.stack.imgur.com/sxo9k.png... | 1 | 2016-10-15T09:03:42Z | 40,058,432 | <p>The gray frames are the execution frames, which contain the closure. They can theoretically be read from memory.</p>
<p>For example, I managed to read the data from the frames with the following code (CPython v3.5):</p>
<p>Some utilities first:</p>
<pre><code>import gc, inspect, ctypes, random
def all_live_ids()... | 1 | 2016-10-15T11:26:29Z | [
"python",
"functional-programming",
"closures"
] |
Python Pandas Data Formatting: Diffnce in passing index and iloc | 40,057,128 | <p>This is the sample data:</p>
<pre><code>dict_country_gdp = pd.Series([52056.01781,40258.80862,40034.85063,39578.07441],
index = ['Luxembourg','Norway', 'Japan', 'Switzerland'])
</code></pre>
<p>What is the difference between <code>dict_country_gdp[0]</code> and <code>dict_country_gdp.iloc[0]</code>? </p>
<p>W... | 1 | 2016-10-15T09:04:36Z | 40,057,921 | <p>As you are working with one dimensional series, [] or .iloc will give same results. </p>
<p><strong>ONE DIMENSIONAL SERIES:</strong></p>
<pre><code>import pandas as pd
dict_country_gdp = pd.Series([52056.01781, 40258.80862,40034.85063,39578.07441])
dict_country_gdp
Out[]:
0 52056.01781
1 40258.80862
2 ... | 0 | 2016-10-15T10:31:59Z | [
"python",
"pandas",
"dictionary"
] |
How can I just import a subdir and use "subdir.pythonfile.function" in python? | 40,057,198 | <p>I have a python project with following structure:<br>
project<br>
--subdir<br>
----__init__.py<br>
----func.py (has a function a)<br>
--main.py<br></p>
<p>I want to use the function "a" in main.py. So I can<br>
<code>import subdir.func as F</code><br>
<code>F.a()</code></p>
<p>But this is not what I want to do, I... | 0 | 2016-10-15T09:10:16Z | 40,057,470 | <p>Keep your directory structure as it is and add this line in your <strong>init</strong>.py :</p>
<pre><code>from . import func
</code></pre>
| 0 | 2016-10-15T09:42:41Z | [
"python",
"import",
"subdirectory"
] |
How can I just import a subdir and use "subdir.pythonfile.function" in python? | 40,057,198 | <p>I have a python project with following structure:<br>
project<br>
--subdir<br>
----__init__.py<br>
----func.py (has a function a)<br>
--main.py<br></p>
<p>I want to use the function "a" in main.py. So I can<br>
<code>import subdir.func as F</code><br>
<code>F.a()</code></p>
<p>But this is not what I want to do, I... | 0 | 2016-10-15T09:10:16Z | 40,057,727 | <p>Let me discuss here your current scenario first.
If you print files of 'subdir' here:</p>
<pre><code> import subdir as SD
print(SD.__file__)
</code></pre>
<p>It should show the <strong>init</strong>.pyc file name with absolute path.
So to resolve issue you have to import the func.py file in <strong>init</st... | 0 | 2016-10-15T10:09:52Z | [
"python",
"import",
"subdirectory"
] |
How to monitor a python process and restart it upon abnormal termination | 40,057,204 | <p>Assume that there is a <code>task.py</code>,breaking due to memory overflow.How can i monitor this and restart it?</p>
<pre><code>import time
while(1):
print('.')
# simulate breaks
time.sleep(2)
exit(0)
</code></pre>
<p>Thanks</p>
| 1 | 2016-10-15T09:11:12Z | 40,057,267 | <p>You can use a watchdog.
Make your worker process update a dummyfile say every 10 secs.
Have another, completely independent, process check if the last access wasn't longer that say 20 secs ago.
If it was, restart your worker process.</p>
<p>There are all kinds of nifty OS-dependent ways to do the same, but this low... | 1 | 2016-10-15T09:18:15Z | [
"python",
"linux",
"bash"
] |
How to monitor a python process and restart it upon abnormal termination | 40,057,204 | <p>Assume that there is a <code>task.py</code>,breaking due to memory overflow.How can i monitor this and restart it?</p>
<pre><code>import time
while(1):
print('.')
# simulate breaks
time.sleep(2)
exit(0)
</code></pre>
<p>Thanks</p>
| 1 | 2016-10-15T09:11:12Z | 40,057,432 | <p>If it actually runs out of memory it should get <a href="https://www.kernel.org/doc/gorman/html/understand/understand016.html" rel="nofollow">OOM killed</a>. If you have another process which restarts it continuously (for example <code>while true; do /path/to/my_script.py; done</code>) it should get up and running a... | 0 | 2016-10-15T09:38:31Z | [
"python",
"linux",
"bash"
] |
How to monitor a python process and restart it upon abnormal termination | 40,057,204 | <p>Assume that there is a <code>task.py</code>,breaking due to memory overflow.How can i monitor this and restart it?</p>
<pre><code>import time
while(1):
print('.')
# simulate breaks
time.sleep(2)
exit(0)
</code></pre>
<p>Thanks</p>
| 1 | 2016-10-15T09:11:12Z | 40,059,325 | <p>Something like this should work:</p>
<pre><code>while ! /path/to/task.py; do
echo 'restarting task...'
done
</code></pre>
<p>If <em>task.py</em> exits with non-zero exit status the loop will continue and run the script again. The loop will only break when <em>task.py</em> exits with <code>0</code>.</p>
<p>If ... | 1 | 2016-10-15T13:01:24Z | [
"python",
"linux",
"bash"
] |
Regex expression excluding "-" tag | 40,057,218 | <p>Hi right now my regex expression is working as intended. However i wish to specifically exclude items such as
how do i update my regex such that it would exclude entries with "-\d*"/ negative quantity? ?</p>
<p><a href="https://regex101.com/r/4EUzLo/1" rel="nofollow">https://regex101.com/r/4EUzLo/1</a></p>
| 2 | 2016-10-15T09:12:39Z | 40,057,403 | <p>This should work for you:</p>
<pre><code>'\d+\s*([a-zA-Z].*\w)\s+\d.*'
</code></pre>
<p>The <code>'\d+</code> will only match the positive quantities, and with less steps.</p>
<p>Now, just extract the info from the capture group.</p>
<p><kbd> <a href="https://regex101.com/r/UylZqb/1" rel="nofollow">Demo</a> </kb... | 1 | 2016-10-15T09:35:10Z | [
"python",
"regex"
] |
Watch requset in gmail API doesnt work | 40,057,253 | <p>I am trying to make a watch request using python referring <a href="https://developers.google.com/gmail/api/guides/push" rel="nofollow">google APIs</a> but it does not work. </p>
<pre><code>request = {
'labelIds': ['INBOX'],
'topicName': 'projects/myproject/topics/mytopic'
}
gmail.users().watch(userId='me', bod... | 2 | 2016-10-15T09:16:12Z | 40,079,139 | <p>Do it in gmail python client(provide by google).under main function </p>
<pre><code>request = {
'labelIds': ['INBOX'],
'topicName': 'projects/myprojects/topics/getTopic'
}
print(service.users().watch(userId='me', body=request).execute())
</code></pre>
| 0 | 2016-10-17T05:36:54Z | [
"python",
"gmail-api",
"google-cloud-pubsub"
] |
Beginner python project on school managment system? | 40,057,361 | <p>i am beginner in programming and just got the hang of python language.i am doing a small project on a miniature school management system using the class defined below.i need help in reading and writing these details into a csv file.i also want to know how to modify these details.i hope you would help me with this in... | -5 | 2016-10-15T09:27:52Z | 40,057,556 | <p>Instead of using csv files, you can also use <strong>Pickle</strong></p>
<p>Saving a student:</p>
<pre><code>import pickle
file = open("student_record.pkl", "w")
pickle.dump(file, student_object)
file.close()
</code></pre>
<p>Loading a student's record:</p>
<pre><code>import pickle
file = open("student_record.... | 1 | 2016-10-15T09:53:16Z | [
"python"
] |
In Python why do some people include len(s)-2 in some cases for finding a word in a string? | 40,057,515 | <p>Consider:</p>
<pre><code>s = input("Enter a string")
n=0
for count in range(len(s)):
if s[count:count+3] == "bob":
n = n+1
print("Number of times bob occurs is: " ,n)
</code></pre>
<p>Why do some people use <code>range(len(s)-2)</code> in their code instead of <code>range(len(s))</code> although both give the... | 0 | 2016-10-15T09:48:55Z | 40,057,575 | <p>The last two <code>count</code> values in the for loop, <code>count = len(s)-2</code> and <code>len(s)-1</code> lead to substrings with only 2 or 1 characters, which cannot be equal to a 3 character string.</p>
| 1 | 2016-10-15T09:55:18Z | [
"python",
"string"
] |
In Python why do some people include len(s)-2 in some cases for finding a word in a string? | 40,057,515 | <p>Consider:</p>
<pre><code>s = input("Enter a string")
n=0
for count in range(len(s)):
if s[count:count+3] == "bob":
n = n+1
print("Number of times bob occurs is: " ,n)
</code></pre>
<p>Why do some people use <code>range(len(s)-2)</code> in their code instead of <code>range(len(s))</code> although both give the... | 0 | 2016-10-15T09:48:55Z | 40,057,578 | <p>"bob" has three characters. So if we want to search "bob" from a given word, you only need to check till the [-3] letter...</p>
<p>That's why people search till len(s)-2.</p>
| 0 | 2016-10-15T09:55:36Z | [
"python",
"string"
] |
python webdriver eror | 40,057,725 | <p>I have recently downloaded selenium and tried to run this script: </p>
<pre><code> from selenium import webdriver
driver = webdriver.Firefox()
</code></pre>
<p>but I get this error:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
driver = webdriver.Fire... | 0 | 2016-10-15T10:09:39Z | 40,079,431 | <p>I got around this by manually setting the binary location as per the following answer:</p>
<p><a href="http://stackoverflow.com/a/25715497">http://stackoverflow.com/a/25715497</a></p>
<p>Remember to set your binary to the actual location of the firefox binary on your computer</p>
<p>eg:</p>
<pre><code>from selen... | 0 | 2016-10-17T06:01:37Z | [
"python",
"selenium",
"path",
"webdriver"
] |
NewbieQ: Jupyter HTML command not working when multiple code lines | 40,057,970 | <p>I'm new to Jupyter Notebook and have this simple line of code:</p>
<pre><code>HTML('<b>Question</b>')
Q=1
</code></pre>
<p>I have found that the first line only works when nothing else comes after it. Is this normal? Do I have to have each line of code in a separate cell?</p>
| 0 | 2016-10-15T10:37:23Z | 40,107,177 | <p>There are two things at play here:</p>
<ol>
<li><code>HTML</code> creates an HTML <em>object</em>, whose <a href="https://nbviewer.jupyter.org/github/ipython/ipython/blob/5.0.0/examples/IPython%20Kernel/Rich%20Output.ipynb" rel="nofollow">rich representation</a> is the HTML string <code><b>...</code>. Instant... | 0 | 2016-10-18T11:35:34Z | [
"python",
"jupyter"
] |
import all csv files in directory as pandas dfs and name them as csv filenames | 40,058,133 | <p>I'm trying to write a script that will import all .csv files in a directory to my workspace as dataframes. Each dataframe should be named as the csv file (minus the extension: .csv).</p>
<p>This is what i have so far, but struggling to understand how to assign the correct name to the dataframe in the loop. I've see... | 0 | 2016-10-15T10:53:54Z | 40,059,175 | <p><code>DataFrame</code> have no <code>name</code> their index can have a <code>name</code>. This is how to set it.</p>
<pre><code>import glob
import os
path = "./data/"
all_files = glob.glob(os.path.join(path, "*.csv")) #make list of paths
for file in all_files:
# Getting the file name without extension
fi... | 0 | 2016-10-15T12:45:36Z | [
"python",
"csv",
"pandas"
] |
Pythn count multiple values in dictionary of list | 40,058,134 | <p>I have been trying to count the values in a dictionary with respect to the key. However, I could not achieved desired result. I will demonstrate with more details below:</p>
<pre><code>from collections import Counter
d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John}
# create ... | 0 | 2016-10-15T10:53:55Z | 40,058,177 | <p>Try this using <code>dict comprehension</code></p>
<pre><code>from collections import Counter
d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John'}
c = {i:Counter(j) for i,j in d.items()}
print c
</code></pre>
| 0 | 2016-10-15T10:58:54Z | [
"python",
"list",
"dictionary",
"counter"
] |
Pythn count multiple values in dictionary of list | 40,058,134 | <p>I have been trying to count the values in a dictionary with respect to the key. However, I could not achieved desired result. I will demonstrate with more details below:</p>
<pre><code>from collections import Counter
d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John}
# create ... | 0 | 2016-10-15T10:53:55Z | 40,058,190 | <p>You're picking only the first elements in the each list with <code>values[1]</code>, instead, you want to iterate through each values using a <code>for</code> that follows the first:</p>
<pre><code>>>> from collections import Counter
>>> d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'... | 1 | 2016-10-15T10:59:35Z | [
"python",
"list",
"dictionary",
"counter"
] |
Handling multiple variables in python | 40,058,143 | <p>Here's issue I am learning python newly i want to use loop for generating inputs from user which are then operated for some custom function (say Lcm or squaring them and returning ) so how to perform code
Consider </p>
<pre><code>k,l=0,0
while l>=10:
n_k=input("Enter")
k=k+1
l=l+1
#Do something... | -2 | 2016-10-15T10:55:03Z | 40,058,375 | <p>Instead of n_k being a single variable i think you want n to be a <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">list</a>. A list is just a bunch of variables stored together. For example the code:</p>
<pre><code>n = [1, 4, 2]
print(n[0]) #0th element of the list
print(n[1]) #1st ... | 0 | 2016-10-15T11:20:01Z | [
"python",
"python-2.7",
"loops",
"variables",
"for-loop"
] |
How can I play MIDI tracks created using python-midi package? | 40,058,310 | <p>I want to create MIDI tracks in a Python program and be able to play them instantly (preferably without writing to disk). I have recently discovered the package <a href="https://github.com/vishnubob/python-midi" rel="nofollow">python-midi</a> which looks great. However I haven't figured out how to play the tracks cr... | 0 | 2016-10-15T11:12:41Z | 40,059,738 | <p>My solution if anyone is interested:</p>
<p>I ended up using <a href="https://github.com/olemb/mido" rel="nofollow">mido</a> for my Python MIDI API, with Pygame as the backend.
Works like a charm :)</p>
| 0 | 2016-10-15T13:41:56Z | [
"python",
"api",
"midi"
] |
Matplotlib logarithmic x-axis and padding | 40,058,391 | <p>I am struggling with matplotlib and padding on the x-axis together with a logarithmic scale (see the first picture).
Without a logarithmic scale, the padding applies nicely (see the second one).
Any suggestations how to get a padding between plot lines and the axis line in the bottom left corner so that one can see ... | 0 | 2016-10-15T11:21:23Z | 40,058,832 | <p>This does not address your padding issue, but you could use <code>clip_on=False</code> to prevent the points from being cut off. It seems you also need to make sure they're above the axes using <code>zorder</code></p>
<pre><code>plt.plot(T,opt1,"o-", label="opt1", clip_on=False, zorder=10)
plt.plot(T,opt2, "s-", la... | 0 | 2016-10-15T12:08:05Z | [
"python",
"matplotlib",
"padding"
] |
Python: count frequency of words from a column and store the results into another column on my data frame | 40,058,436 | <p>I want to count the number of each word that appears in each row of one column ('Comment') and store in a new column ('word') on my data frame called headlamp.
I'm trying with the following down code, however, I get and error.</p>
<pre><code>for i in range(0,len(headlamp)):
headlamp['word'].apply(lambda text: C... | 1 | 2016-10-15T11:26:51Z | 40,059,993 | <p>You can try this:</p>
<pre><code>headlamp['word'] = headlamp['Comment'].apply(lambda x: len(x.split()))
</code></pre>
<p><strong>Example:</strong></p>
<pre><code>headlamp = pd.DataFrame({'Comment': ['hello world','world','foo','foo and bar']})
print(headlamp)
Comment
0 hello world
1 world
2 ... | 0 | 2016-10-15T14:06:32Z | [
"python",
"pandas",
"count",
"counter",
"frame"
] |
Python: count frequency of words from a column and store the results into another column on my data frame | 40,058,436 | <p>I want to count the number of each word that appears in each row of one column ('Comment') and store in a new column ('word') on my data frame called headlamp.
I'm trying with the following down code, however, I get and error.</p>
<pre><code>for i in range(0,len(headlamp)):
headlamp['word'].apply(lambda text: C... | 1 | 2016-10-15T11:26:51Z | 40,060,060 | <p>Using the <a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" rel="nofollow">most_common()</a> method you can achieve what you want.</p>
<p>Feel free to use this piece of code:</p>
<pre><code>import pandas as pd
from collections import Counter
df = pd.DataFrame({'Comment':... | 0 | 2016-10-15T14:11:50Z | [
"python",
"pandas",
"count",
"counter",
"frame"
] |
python error: local variable 'a' referenced before assignment | 40,058,439 | <p>I'm trying to create a function with an interactive input to tell you what the 'SMILES' formula is for a fatty acid (chemical compound) but I keep getting this error:</p>
<pre><code>def fatty_gen(chain_length, db_position, db_orientation):
"Returns the SMILES code of the fatty acid, given its chain length, db p... | -1 | 2016-10-15T11:26:56Z | 40,058,486 | <p>If <code>db_orientation2</code> is neither <code>"Z"</code> nor <code>"E"</code> <code>a</code> variable is not defined.</p>
<p>You need to add <code>else</code> clause like this:</p>
<pre><code>if db_orientation2 == "Z":
a = "/C=C\\"
elif db_orientation2 == "E":
a = "\C=C\\"
else:
a = "something else"... | 1 | 2016-10-15T11:31:56Z | [
"python"
] |
python error: local variable 'a' referenced before assignment | 40,058,439 | <p>I'm trying to create a function with an interactive input to tell you what the 'SMILES' formula is for a fatty acid (chemical compound) but I keep getting this error:</p>
<pre><code>def fatty_gen(chain_length, db_position, db_orientation):
"Returns the SMILES code of the fatty acid, given its chain length, db p... | -1 | 2016-10-15T11:26:56Z | 40,058,814 | <pre><code>if db_orientation2 =="Z":
a="/C=C\\"
elif db_orientation2=="E":
a="\C=C\\"
elif db_orientation2=="":
a="/C=C\\"
else: a=""
</code></pre>
<p>Anyone know why the backslashes are appearing twice, despite it supposed to be understood as just one backslash?</p>
| 0 | 2016-10-15T12:06:34Z | [
"python"
] |
How to select element locations from two Pandas dataframes of identical shape, where the values match within a certain range? | 40,058,441 | <p>How to select element locations from two Pandas dataframes of identical shape, where the values match within a certain range? A code to do this might be simple to write, but I want to know if there is a smart way to make this conditional selection (like loc) with Pandas data frames as I will need it for large image ... | 0 | 2016-10-15T11:27:07Z | 40,058,958 | <p>I need more information about </p>
<blockquote>
<p>he values match within a certain range</p>
</blockquote>
<p>But this is an example selecting values that are the same in the two <code>DataFrame</code>. By replacing the test by any other test, you could reach your goals.</p>
<pre><code># Test data
df1 = DataFr... | 0 | 2016-10-15T12:21:12Z | [
"python",
"pandas",
"dataframe"
] |
How can i write this without using the if statment | 40,058,467 | <pre><code>def in_puzzle_horizontal(puzzle, word):
left_right = lr_occurrences(puzzle, word)
right_left = lr_occurrences((rotate_puzzle(rotate_puzzle(puzzle))), word)
total = left_right or right_left
if total > 0:
return True
else:
return False
</code></pre>
| -1 | 2016-10-15T11:30:08Z | 40,058,492 | <p>You only have to replace the if statement by:</p>
<pre><code>return total > 0
</code></pre>
| 6 | 2016-10-15T11:32:40Z | [
"python",
"if-statement"
] |
How can i write this without using the if statment | 40,058,467 | <pre><code>def in_puzzle_horizontal(puzzle, word):
left_right = lr_occurrences(puzzle, word)
right_left = lr_occurrences((rotate_puzzle(rotate_puzzle(puzzle))), word)
total = left_right or right_left
if total > 0:
return True
else:
return False
</code></pre>
| -1 | 2016-10-15T11:30:08Z | 40,058,508 | <pre><code>left_right = lr_occurrences(puzzle, word)
right_left = lr_occurrences((rotate_puzzle(rotate_puzzle(puzzle))), word)
total = left_right or right_left
return total > 0
</code></pre>
| 1 | 2016-10-15T11:33:56Z | [
"python",
"if-statement"
] |
Python Unhandled Error Traceback (most recent call last): | 40,058,474 | <p>This is my code, I was looking for answers but none resolve my problem.
I'm new to Twisted and still learning.</p>
<p>Why do I get this error after I run <code>telnet localhost 72</code> in the Windows command prompt? </p>
<p>This is my code:</p>
<pre><code>from twisted.internet.protocol import Factory
from twis... | 0 | 2016-10-15T11:30:43Z | 40,077,577 | <p>@firman Are you sure you're giving us the EXACT code that's causing issues? The code above (if it were written properly) cannot possibly give that error. The error occurs in the <code>buildProtocol</code> function of the <code>Factory</code> class, which you overloaded in your example. I've edited your question and ... | 0 | 2016-10-17T02:15:02Z | [
"python",
"twisted"
] |
Different Color Result Between Python OpenCV and MATLAB | 40,058,686 | <p>I'm going to convert RGB image to YIQ image and viceversa. The problem is Python give me a weird image, while MATLAB shows the right one. I spent hours to figure what's wrong, but i still have no idea.</p>
<p>I use Python 3.5.2 with OpenCV 3.1.0 and MATLAB R2016a.</p>
<p>Python code for RGB2YIQ:</p>
<pre><code>im... | 3 | 2016-10-15T11:52:36Z | 40,060,066 | <p>You obviously face a saturation problem, due to some computed component exceeding the range [0,255]. Clamp the values or adjust the gain.</p>
<p>Then there seems to be a swapping of the components somewhere.</p>
| 0 | 2016-10-15T14:12:45Z | [
"python",
"matlab",
"opencv",
"image-processing",
"ipython"
] |
Select hidden option value from source using python selenium chromedriver | 40,058,697 | <p>I am reading a Docx file [here is the <a href="https://www.dropbox.com/s/3za9qhzupc01azt/Taxatierapport%20SEK%20-%20Auto%20Centrum%20Bollenstreek%20-%20Peugeot%20308%20-%205603.docx?dl=0" rel="nofollow">link] </a>, parsing some text from that & then Using python selenium bindings & chrome-driver I am trying ... | 0 | 2016-10-15T11:53:46Z | 40,061,817 | <pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://autotelexpro.nl/LoginPage.aspx')
driver.find_element(By.XPATH, value ='//*[@id="ctl00_cp_LogOnView... | 0 | 2016-10-15T16:59:41Z | [
"python",
"python-2.7",
"selenium",
"post",
"selenium-chromedriver"
] |
Using multiple cores with Python and Eventlet | 40,058,748 | <p>I have a Python web application in which the client (<a href="http://emberjs.com/" rel="nofollow">Ember.js</a>) communicates with the server via WebSocket (I am using <a href="https://flask-socketio.readthedocs.io/en/latest/" rel="nofollow">Flask-SocketIO</a>).
Apart from the WebSocket server the backend does two m... | 3 | 2016-10-15T11:59:36Z | 40,066,117 | <p>Eventlet is currently incompatible with the multiprocessing package. There is an open issue for this work: <a href="https://github.com/eventlet/eventlet/issues/210" rel="nofollow">https://github.com/eventlet/eventlet/issues/210</a>.</p>
<p>The alternative that I think will work well in your case is to use Celery to... | 3 | 2016-10-16T02:07:05Z | [
"python",
"multithreading",
"multiprocessing",
"eventlet",
"flask-socketio"
] |
Python Openpxyl query workbook for list of contained worksheets | 40,058,756 | <p>Dear Python community,</p>
<p>I'd like to parse a recent Excel .xlsx file with the installed Openpyxl module. I need to get a list of the worksheets contained within the workbook. How can I code that in Python?</p>
<p>Thank you.</p>
<p>Regards,</p>
| -4 | 2016-10-15T12:00:53Z | 40,058,898 | <p>This is the right code : </p>
<pre><code>from openpyxl import load_workbook
wb = load_workbook(r"path_excel_file\filename.xlsx")
for sheet in wb.worksheets:
print str(sheet).replace('<Worksheet "','').replace('">','')
</code></pre>
| 0 | 2016-10-15T12:16:09Z | [
"python",
"excel",
"worksheet"
] |
Error installing Pillow, Searched everywhere but could not find it! 3.5 | 40,058,772 | <p>Using PyCharm, my project interpreter settings show that it is installed but when importing, it errors out saying it doesn't know what it is:</p>
<pre><code>ImportError: No module named 'Pillow'
</code></pre>
<p>Python v3.5 </p>
<p><img src="https://i.stack.imgur.com/HamZ5.png" alt="Error Image"></p>
<p><img src... | -1 | 2016-10-15T12:02:59Z | 40,058,818 | <p>As the docs show, you don't import Pillow in your code; the package is <code>PIL</code>.</p>
<pre><code>from PIL import Image
</code></pre>
<p>etc.</p>
| 0 | 2016-10-15T12:06:57Z | [
"python"
] |
PyInstaller Script Not found Error | 40,058,788 | <p>I made a script for an app and it works perfectly, and now I'm trying to use PyInstaller to execute it into an .app. I'm running the latest mac os version. It seems like PyInstaller can't find my script but it's spelled correctly and it actually exists. This is what I get:</p>
<pre><code>Air-Andrej:~ Andrey$ pyinst... | 0 | 2016-10-15T12:04:28Z | 40,058,984 | <p>I just figured it out. It was expecting me to put the whole directory in, so that means that the computer was trying to find the file in the wrong directory or just stopped at a certain point.</p>
| 0 | 2016-10-15T12:23:43Z | [
"python",
"pyinstaller"
] |
Foreign key contraint is not getting set in SQLlite using flask alchemy | 40,058,855 | <p>I have below table schema defined in sqlalchemy where user_id is foreign key referencing to User's user_id table</p>
<pre><code>class Manufacturer(Model):
__tablename__='Manufacturer'
Manufacturer_id=Column(Integer,primary_key=True,autoincrement=True)
name=Column(String(length=100),nullable=False)
description=Colum... | 0 | 2016-10-15T12:10:47Z | 40,059,042 | <p>below code worked for me and found it from below link -</p>
<p><a href="http://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys">Sqlite / SQLAlchemy: how to enforce Foreign Keys?</a></p>
<pre><code> def _fk_pragma_on_connect(dbapi_con, con_record):
dbapi_con.execute('pragma f... | 0 | 2016-10-15T12:30:27Z | [
"python",
"database",
"sqlite",
"session",
"sqlalchemy"
] |
randomly controlling the percentage of non zero values in a matrix using python | 40,058,912 | <p>I am looking to create matrices with different levels of sparsity. I intend to do that by converting all the values that are nonzero in the data matrix to 1's and the remaining entries would be 0.</p>
<p>I was able to achieve that using the following code. But I am not sure how would I be able to randomly make the ... | 1 | 2016-10-15T12:17:38Z | 40,070,362 | <p>You could do something like this -</p>
<pre><code>idx = np.flatnonzero(a)
N = np.count_nonzero(a!=0) - int(round(0.25*a.size))
np.put(a,np.random.choice(idx,size=N,replace=False),0)
</code></pre>
<p><strong>Sample run</strong></p>
<p>1) Input array :</p>
<pre><code>In [259]: a
Out[259]:
array([[0, 1, 0, 1, 1],
... | 0 | 2016-10-16T12:42:09Z | [
"python",
"python-3.x",
"numpy",
"matrix",
"scipy"
] |
python: while loop does not reach last iteration | 40,058,988 | <p>I don't get the result of this code:</p>
<pre><code>a = i = 0.05
b = 1.0
while a <= b:
print a
a += i
</code></pre>
<p>Of course this should print 0.05,0.1,...,1.0 but instead the iteration stops at 0.95. Is it a float issue?</p>
| 0 | 2016-10-15T12:23:57Z | 40,058,994 | <p>Yes, you're working with floating point numbers, so you won't end up exactly at 1.0. Set b to e.g. 1.001 to cater for the rounding errors. Note that your numbers will be represented in binary. If they were truly decimal, they could be represented exactly.</p>
<p>By the way, I'd rather use:</p>
<pre><code>for i in ... | 0 | 2016-10-15T12:24:51Z | [
"python",
"while-loop",
"iteration"
] |
python: while loop does not reach last iteration | 40,058,988 | <p>I don't get the result of this code:</p>
<pre><code>a = i = 0.05
b = 1.0
while a <= b:
print a
a += i
</code></pre>
<p>Of course this should print 0.05,0.1,...,1.0 but instead the iteration stops at 0.95. Is it a float issue?</p>
| 0 | 2016-10-15T12:23:57Z | 40,059,057 | <p>Perhaps a better answer would be the following:</p>
<pre><code>a = i = 0.05
b = 1.0
a = i = int(a * 1000)
b = int(b * 1000)
while a <= b:
print a/1000.0
a += i
</code></pre>
<p>This way you wont need to deal with floating point numbers at all. Many ways to skin a cat.</p>
| 0 | 2016-10-15T12:32:19Z | [
"python",
"while-loop",
"iteration"
] |
Combinations of chars via a generator in Python | 40,058,993 | <p>I am trying to get all the combinations with replacement (in other words, the cartesian product) of strings with length(8) . The output is too big and I am having trouble storing it in memory all at once , so my process gets killed before it finishes.</p>
<p>This is the code I use which is way more faster than Pyth... | -1 | 2016-10-15T12:24:50Z | 40,063,690 | <p>My impression from other questions is that <code>product</code> is the fastest way of iteratively generating cartesian combinations:</p>
<pre><code>In [494]: g=itertools.product([1,2,3],[4,5],[6,7])
In [495]: list(g)
Out[495]:
[(1, 4, 6),
(1, 4, 7),
(1, 5, 6),
(1, 5, 7),
(2, 4, 6),
(2, 4, 7),
(2, 5, 6),
(2,... | 0 | 2016-10-15T20:07:19Z | [
"python",
"python-2.7",
"numpy",
"scikit-learn",
"itertools"
] |
How to use recursion in python | 40,059,033 | <p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 ... | 1 | 2016-10-15T12:29:19Z | 40,059,201 | <p>The line</p>
<pre><code>return macro_interpreter (macros etc.
</code></pre>
<p>will do just that. It will leave the for loop and return from the outer call. End of story.</p>
| 0 | 2016-10-15T12:47:52Z | [
"python",
"python-3.x"
] |
How to use recursion in python | 40,059,033 | <p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 ... | 1 | 2016-10-15T12:29:19Z | 40,059,229 | <p>If you always hit the one <code>else</code> statement in the loop over the <code>code</code> commands, then you never will recurse because <code>command not in macros</code>. </p>
<p>After the first iteration, <code>code == ['turn', 'turn', 'turn']</code>, but <code>macros</code> contains no key <code>"turn"</code... | 2 | 2016-10-15T12:50:02Z | [
"python",
"python-3.x"
] |
How to use recursion in python | 40,059,033 | <p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 ... | 1 | 2016-10-15T12:29:19Z | 40,059,322 | <p>I suspect it's because you return </p>
<pre><code>macro_interpreter(macros[command], macros)
</code></pre>
<p>This simply exits the function once the recursed code is run. You'll see if you change</p>
<pre><code>return macro_interpreter(macros[command], macros)
</code></pre>
<p>to</p>
<pre><code>print macro_int... | 0 | 2016-10-15T13:01:16Z | [
"python",
"python-3.x"
] |
How to use recursion in python | 40,059,033 | <p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 ... | 1 | 2016-10-15T12:29:19Z | 40,059,495 | <p>There are some amendments which i did in your code to support recursion properly. This code will do, what you want to acheive. </p>
<pre><code>def macro_interpreter(code, macros, x=0, y=0, index=0):
state = ['N', 'E', 'S', 'W']
for command in code:
if command in macros:
x, y, curr_state ... | 1 | 2016-10-15T13:17:44Z | [
"python",
"python-3.x"
] |
Error on join condition with SqlAlchemy | 40,059,136 | <p>I'm trying to use SQLAlchemy on my python app but I have a problem with the many to many relationship.
I have 4 tables:</p>
<p>users, flags, commandes, channels, and commandes_channels_flags</p>
<p>commandes_channels_flags contain a foreign key for each concerned table (commandes, channels and flags)</p>
<p>An us... | 0 | 2016-10-15T12:40:24Z | 40,059,622 | <p><code>back_populates</code> needs to match the exact name of the related property on the other model. In <code>Channel</code>, you have <code>back_populates="channels"</code>, but in <code>Commande</code>, you have:</p>
<pre><code>channel = relationship("Channel", secondary="commandes_channels_flags", back_populate... | 1 | 2016-10-15T13:29:56Z | [
"python",
"python-3.x",
"sqlalchemy"
] |
python pptx XyChart setting label font size | 40,059,179 | <p>Within an python-pptx-generated XYchart, I would like to add labels to each point of the series. Code looks like this:</p>
<pre><code>for p, v in zip(chart.series[0].points, dataSeries):
p.data_label.position = XL_LABEL_POSITION.ABOVE
p.data_label.text_frame.clear()
for paras in p.data_label.text_frame.... | 0 | 2016-10-15T12:45:50Z | 40,063,902 | <p>You need to set the font size <em>after</em> adding the text frame text.</p>
<pre><code>data_label = p.data_label
...
text_frame = data_label.text_frame
# text_frame.clear() # this line is not needed, assigning to .text does this
text_frame.text = str.format('{0:.1f}', v)
for paragraph in text_frame.paragraphs:
... | 0 | 2016-10-15T20:30:32Z | [
"python",
"fonts",
"size",
"labels",
"python-pptx"
] |
Python: Appending to a list, which is value of a dictionary | 40,059,188 | <p>Here is the code, which I would like to understand. I am creating a dict using elements of a list as keys and another list as default values. Then update this dict with another one. Finally, I would like to append to the list within dict. The append is happening multiple times for some of the elements. I would like ... | 1 | 2016-10-15T12:46:49Z | 40,059,238 | <p>this</p>
<pre><code>bm=dict.fromkeys(l,['-1','-1'])
</code></pre>
<p>Is reusing the same list <code>['-1','-1']</code> for all keys, which explains the effect you're witnessing.</p>
<p>to achieve what you want you could do this with a <em>dict comprehension</em></p>
<pre><code>bm = {x:[-1,1] for x in ['a','b','c... | 1 | 2016-10-15T12:51:23Z | [
"python"
] |
What would be wrong with this function that return a rounded number in millions | 40,059,195 | <p>I'm a beginner doing an online course using ipython notebook and panda.</p>
<p>We are given a function</p>
<pre><code>def roundToMillions (value):
result = round(value / 1000000)
return result
</code></pre>
<p>and some tests </p>
<pre><code>roundToMillions(4567890.1) == 5
roundToMillions(0) == 0 # alwa... | 0 | 2016-10-15T12:47:17Z | 40,059,307 | <p>In terms of test cases, this loop will generate many test cases and the results speak for themselves:</p>
<pre><code>for x in xrange(-2000000, 2000000, 250000):
print roundToMillions(x), x
>> -2.0 -2000000
>> -2.0 -1750000
>> -2.0 -1500000
>> -2.0 -1250000
>> -1.0 -1000000
>> -1... | 0 | 2016-10-15T12:59:48Z | [
"python",
"pandas"
] |
Why do I get an TypeError: 'in <string>' requires string as left operand, not list error when running my program? | 40,059,244 | <p>When i run through my python code:</p>
<pre><code>import time
print("\n\n\t\tWelcome to the Automated Troubleshooting Program\n\n")
time.sleep(1)
name = input("Before we begin, what is your name?\nName: ")
time.sleep(1)
option_end = False
while option_end == False:
option = input("Would you like to quit or carry ... | -1 | 2016-10-15T12:51:58Z | 40,059,367 | <p>To start you have an indentation error on your first while loop.</p>
<p>The problem is that you are trying to check if a list is in a string (doesn't work).</p>
<p>The split in line 19 changes the variable words to a list.</p>
<p>If you want to check if any of the words in question are in the line of search file ... | 0 | 2016-10-15T13:06:35Z | [
"python"
] |
Python - recursively find lists in lists (n deep) | 40,059,273 | <p>I'm trying to use ipaddress (<a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">https://docs.python.org/3/library/ipaddress.html</a>) to solve the following issue:</p>
<p>I have a BGP aggregate-address of 10.76.32.0/20</p>
<p>from which I would like to subtract all the network commands on th... | 0 | 2016-10-15T12:55:29Z | 40,075,765 | <p>You didn't indicate the version of python (2 or 3) you are using so I assumed it's python3 based on the fact that the link you posted is to the python3 documentation. You didn't post any code, but based on your description of the issue I assume you need something like this:</p>
<pre><code>from ipaddress import ip_n... | 0 | 2016-10-16T21:36:31Z | [
"python",
"networking",
"recursion"
] |
Resolving Catastrophic Backtracking issue in RegEx | 40,059,284 | <p>I am using RegEx for finding URL substrings in strings.
The RegEx I am using has been taken from tohster's answer on -
<a href="http://stackoverflow.com/questions/520031/whats-the-cleanest-way-to-extract-urls-from-a-string-using-python/30408189#30408189">What's the cleanest way to extract URLs from a string usi... | 0 | 2016-10-15T12:56:37Z | 40,060,148 | <p>The issue of the catastrophic backtracking is caused by the pattern <code>(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))</code> where <code>(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)</code> will jump through ... | 2 | 2016-10-15T14:20:07Z | [
"python",
"regex",
"url",
"ip-address",
"ipv4"
] |
How to avoid a specific tag while extracting xpath | 40,059,298 | <p>By using xpath(.//div[@class="entry-content"]/div/p//text()') i am getting all the text1,text2,.....text6. How to take only "text3","text4","text5","text6"??</p>
<pre><code>`<div class="entry-content">
<div>
<p>
<st>text1</st>
</p>
<p>
<st>... | 1 | 2016-10-15T12:59:05Z | 40,060,862 | <p>If you only want nodes within the second <code>div</code>, use the path</p>
<pre><code>.//div[@class="entry-content"]/div[2]/p//text()
</code></pre>
<p>If want nodes in all <code>div</code>s except the first, write</p>
<pre><code>.//div[@class="entry-content"]/div[position()>1]/p//text()
</code></pre>
<p>If y... | 0 | 2016-10-15T15:27:23Z | [
"python",
"python-2.7",
"python-3.x",
"xpath"
] |
How to avoid a specific tag while extracting xpath | 40,059,298 | <p>By using xpath(.//div[@class="entry-content"]/div/p//text()') i am getting all the text1,text2,.....text6. How to take only "text3","text4","text5","text6"??</p>
<pre><code>`<div class="entry-content">
<div>
<p>
<st>text1</st>
</p>
<p>
<st>... | 1 | 2016-10-15T12:59:05Z | 40,069,929 | <p>As per your clarification it seems that "p" are the nodes you want to avoid, in particular the first 2 of them. As they may appear at different depth level, one of the ways you achieve it is with this xpath expression, which is basically a variation of the solution provided by Michael Kay:</p>
<pre><code>//div[@cla... | 0 | 2016-10-16T11:52:09Z | [
"python",
"python-2.7",
"python-3.x",
"xpath"
] |
Advanced array concatenation python | 40,059,330 | <p>Say I have four multi-dimensional arrays - </p>
<pre><code>a = [["a","a","a"],
["a","a","a"],
["a","a","a"]]
b = [["b","b","b"],
["b","b","b"],
["b","b","b"]]
c = [["c","c","c"],
["c","c","c"],
["c","c","c"]]
d = [["d","d","d"],
["d","d","d"],
["d","d","d"]]
</code></pre>
<p>and I w... | 2 | 2016-10-15T13:01:51Z | 40,059,388 | <p>Maybe like this:</p>
<pre><code>top = list(x+y for x,y in zip(a,b))
bottom = list(x+y for x,y in zip(c,d))
total = top + bottom
for r in total: print(r)
</code></pre>
<p>Output:</p>
<pre><code>['a', 'a', 'a', 'b', 'b', 'b']
['a', 'a', 'a', 'b', 'b', 'b']
['a', 'a', 'a', 'b', 'b', 'b']
['c', 'c', 'c', 'd', 'd', '... | 2 | 2016-10-15T13:08:29Z | [
"python",
"arrays",
"pygame",
"concatenation"
] |
Advanced array concatenation python | 40,059,330 | <p>Say I have four multi-dimensional arrays - </p>
<pre><code>a = [["a","a","a"],
["a","a","a"],
["a","a","a"]]
b = [["b","b","b"],
["b","b","b"],
["b","b","b"]]
c = [["c","c","c"],
["c","c","c"],
["c","c","c"]]
d = [["d","d","d"],
["d","d","d"],
["d","d","d"]]
</code></pre>
<p>and I w... | 2 | 2016-10-15T13:01:51Z | 40,059,403 | <p>You can do it with a one line instruction, that mix list comprehension, zip instructions, and list concatenation with <code>+</code></p>
<pre><code>[aa+bb for aa,bb in zip(a,b)] + [cc+dd for cc,dd in zip(c,d)]
</code></pre>
<p>The whole code </p>
<pre><code>a = [["a","a","a"],
["a","a","a"],
["a","a","a"]... | 2 | 2016-10-15T13:09:45Z | [
"python",
"arrays",
"pygame",
"concatenation"
] |
Advanced array concatenation python | 40,059,330 | <p>Say I have four multi-dimensional arrays - </p>
<pre><code>a = [["a","a","a"],
["a","a","a"],
["a","a","a"]]
b = [["b","b","b"],
["b","b","b"],
["b","b","b"]]
c = [["c","c","c"],
["c","c","c"],
["c","c","c"]]
d = [["d","d","d"],
["d","d","d"],
["d","d","d"]]
</code></pre>
<p>and I w... | 2 | 2016-10-15T13:01:51Z | 40,059,522 | <p>Since you are talking about arrays, using numpy arrays and <code>hstack()</code> and <code>vstack()</code>:</p>
<pre><code>import numpy as np
ab = np.hstack((np.array(a),np.array(b)))
cd = np.hstack((np.array(c),np.array(d)))
print np.vstack((ab,cd))
</code></pre>
<p>Which leads you:</p>
<pre><code>[['a' 'a' 'a... | 0 | 2016-10-15T13:19:35Z | [
"python",
"arrays",
"pygame",
"concatenation"
] |
Advanced array concatenation python | 40,059,330 | <p>Say I have four multi-dimensional arrays - </p>
<pre><code>a = [["a","a","a"],
["a","a","a"],
["a","a","a"]]
b = [["b","b","b"],
["b","b","b"],
["b","b","b"]]
c = [["c","c","c"],
["c","c","c"],
["c","c","c"]]
d = [["d","d","d"],
["d","d","d"],
["d","d","d"]]
</code></pre>
<p>and I w... | 2 | 2016-10-15T13:01:51Z | 40,059,601 | <p>Assuming, that layout of your map is more complicated than 2x2 blocks:</p>
<pre><code>from itertools import chain
from pprint import pprint
a = [["a","a","a"],
["a","a","a"],
["a","a","a"]]
b = [["b","b","b"],
["b","b","b"],
["b","b","b"]]
c = [["c","c","c"],
["c","c","c"],
["c","c",... | 2 | 2016-10-15T13:27:52Z | [
"python",
"arrays",
"pygame",
"concatenation"
] |
How to update the parent entity specific field using python in odoo 9 | 40,059,355 | <p>I have a problem on updating the state of the parent table in hr.job table.</p>
<p>I inherit 'hr.job' table and i want to update the 'state' field</p>
<p>I have a table named: 'job_req_tbl' inherits 'hr_job'</p>
<p>Both have same field named 'state'</p>
<p>in my web_app screen there is a button named "Confirm" ,... | 0 | 2016-10-15T13:04:33Z | 40,060,019 | <p>I have resolved with following code:</p>
<pre><code>@api.multi
def action_click(self):
self.hr_job.state = 'recruit'
</code></pre>
| 0 | 2016-10-15T14:08:24Z | [
"python",
"openerp",
"odoo-9",
"odoo-view"
] |
Theano learning AND gate | 40,059,460 | <p>I wrote a simple neural network to learn an AND gate. I'm trying to understand why my cost never decreases and the predictors are always 0.5:</p>
<pre><code>import numpy as np
import theano
import theano.tensor as T
inputs = [[0,0], [1,1], [0,1], [1,0]]
outputs = [[0], [1], [0], [0]]
x = theano.shared(value=np.as... | 1 | 2016-10-15T13:15:19Z | 40,062,160 | <p>Your model is of form</p>
<pre><code><w, x>
</code></pre>
<p>thus it cannot build any separation which <strong>does not cross the origin</strong>. Such equation can only express lines going through point (0,0), and obviously line separating AND gate ((1, 1) from anything else) does not cross the origin. You ... | 1 | 2016-10-15T17:33:34Z | [
"python",
"machine-learning",
"neural-network",
"theano"
] |
I need to parse some text and integers from a file | 40,059,555 | <p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500... | -1 | 2016-10-15T13:22:38Z | 40,059,624 | <p>You are most likely going to end up using the split method, which breaks a string apart into a list element each time it encounters a certain character. Read more here <a href="http://www.pythonforbeginners.com/dictionary/python-split" rel="nofollow">http://www.pythonforbeginners.com/dictionary/python-split</a>. </... | 0 | 2016-10-15T13:30:06Z | [
"python"
] |
I need to parse some text and integers from a file | 40,059,555 | <p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500... | -1 | 2016-10-15T13:22:38Z | 40,059,631 | <p>You could use a high level library to do so, like <a href="http://pandas.pydata.org" rel="nofollow">pandas</a>.</p>
<p>It has many of the functionnalities you want!</p>
<pre><code>import pandas as pd
df = pd.read_csv('file.csv')
print(df)
</code></pre>
| 0 | 2016-10-15T13:30:36Z | [
"python"
] |
I need to parse some text and integers from a file | 40,059,555 | <p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500... | -1 | 2016-10-15T13:22:38Z | 40,059,632 | <p>Given an example line of the file like this:</p>
<pre><code>Cowboys 4 1
</code></pre>
<p>Then some code might look like this:</p>
<pre><code>line = scores.readline().split()
teamName = line[0]
wins = int(line[1])
losses = int(line[2])
if wins > losses:
print(teamName + "'s record is over .500!")
goodT... | 0 | 2016-10-15T13:30:38Z | [
"python"
] |
I need to parse some text and integers from a file | 40,059,555 | <p>I'm having trouble with a problem I'm trying to do. My goal is to import a file that contains football teams names, and then the number of wins and losses, and then if a team's average is greater than .500, than I have to write that teams name, and average to a new file. And then I have to write the teams under .500... | -1 | 2016-10-15T13:22:38Z | 40,059,646 | <p>It's really helpful if you post some lines from your input.
According to your description, I assuming each line in your input has the following layout:</p>
<pre><code>[NAME] X Y
</code></pre>
<p>Where, <code>NAME</code> is the team name, <code>X</code> is the number of wins, <code>Y</code>, the number of loses.
Y... | 0 | 2016-10-15T13:32:50Z | [
"python"
] |
pycrypto : No module named strxor | 40,059,592 | <p>I got this error : </p>
<p>Traceback (most recent call last):
File "test.py", line 8, in
from Crypto.Cipher import PKCS1_OAEP
File "C:\Users\Mokhles\Downloads\google-api-python-client-1.5.3\Crypto \Cipher\PKCS1_OAEP.py", line 57, in
import Crypto.Signature.PKCS1_PSS
File "C:\Users\M... | 0 | 2016-10-15T13:26:33Z | 40,059,658 | <p>It looks like you're simply copied pyCrypto into your project. PyCrypto is library which depends on some native library/code (like libtomcrypt). You have to install it properly. You can do this for example through pip:</p>
<pre><code>pip2 install pycrypto
</code></pre>
<p>or</p>
<pre><code>pip3 install pycrypto
<... | 0 | 2016-10-15T13:34:48Z | [
"python",
"pycrypto"
] |
Issue with python class in Kodi, trying to write a UI to replace Kodi generic menu with PYXBMCT | 40,059,597 | <p>I'm quite new to python class's and have not really used them much so please feel free to point out any other errors except the one I point out. </p>
<p>What I'm trying to achieve is a new <code>UI in Kodi</code> using the <code>pyxbmct</code> module. I'm sending through a list of things (still yet to work out how ... | 0 | 2016-10-15T13:27:32Z | 40,068,095 | <p>Your problem does not have a simple answer because you are doing it wrong at both Python level and PyXBMCt level (I'm the author of PyXBMCt, BTW).</p>
<p>First, I strongly recommend you to learn Python classes: how they are defined, how they are initialized, how they are used.</p>
<p>When you get that in order, th... | 0 | 2016-10-16T07:47:07Z | [
"python",
"class",
"kodi"
] |
how to create empty numpy array to store different kinds of data | 40,059,606 | <p>I am trying to start with an empty numpy array. As the code progresses the first column should be filled with <code>datetime.datetime</code>, the second column should be filled with <code>str</code>, the third columns with <code>float</code>, and fourth column with <code>int</code>.</p>
<p>I tried the following:</p... | 0 | 2016-10-15T13:28:26Z | 40,059,669 | <p>You can use <code>dtype=object</code>.</p>
<pre><code>A = np.empty([10, 4], dtype=object)
A[0][0] = datetime.datetime(2016, 10, 1, 1, 0)
</code></pre>
<p>It is also possible to use structured arrays, but then you have a fixed length for string objects. If you need arbitrary big objects you have to use <code>dtype=... | 1 | 2016-10-15T13:35:46Z | [
"python",
"numpy"
] |
how to create empty numpy array to store different kinds of data | 40,059,606 | <p>I am trying to start with an empty numpy array. As the code progresses the first column should be filled with <code>datetime.datetime</code>, the second column should be filled with <code>str</code>, the third columns with <code>float</code>, and fourth column with <code>int</code>.</p>
<p>I tried the following:</p... | 0 | 2016-10-15T13:28:26Z | 40,063,004 | <p>A structured array approach:</p>
<p>define a dtype according to your column specs:</p>
<pre><code>In [460]: dt=np.dtype('O,U10,f,i')
In [461]: from datetime import datetime
</code></pre>
<p>Initalize an empty array, with 3 elements (not 3x4)</p>
<pre><code>In [462]: A = np.empty((3,), dtype=dt)
In [463]: A
Out[4... | 1 | 2016-10-15T18:57:30Z | [
"python",
"numpy"
] |
Match path but not os.path | 40,059,607 | <p>I want to match the string <code>path</code> but not the string <code>os.path</code>. How do I go about that ? Tried <a href="http://stackoverflow.com/questions/2953039/regular-expression-for-a-string-containing-one-word-but-not-another"><code>(?!(os\.path))\bpath\b</code></a> but I still get all <code>os.path</code... | 0 | 2016-10-15T13:28:28Z | 40,059,729 | <p>You can use a look-behind based regex, like</p>
<pre><code>(?<!os\.)\bpath\b
</code></pre>
<p>This basically matches the exact word <code>path</code> and ensures that it is not preceded by <code>os.</code> If you want to avoid similar constructs, like <code>sys.path</code> or <code>xx.path</code> you could use ... | 1 | 2016-10-15T13:41:03Z | [
"python",
"regex",
"python-2.7"
] |
Match path but not os.path | 40,059,607 | <p>I want to match the string <code>path</code> but not the string <code>os.path</code>. How do I go about that ? Tried <a href="http://stackoverflow.com/questions/2953039/regular-expression-for-a-string-containing-one-word-but-not-another"><code>(?!(os\.path))\bpath\b</code></a> but I still get all <code>os.path</code... | 0 | 2016-10-15T13:28:28Z | 40,059,838 | <p>If you want to skip any <code>path</code> starting with <code>.</code> try</p>
<p><code>(?<!\.)path</code></p>
<p>This will skip <code>sys.path</code> or <code>os.path</code> but will match <code>path</code>.</p>
<p>e.g. if test strings is <code>if path and not os.path.sep in path</code>,</p>
<p>match will be... | 0 | 2016-10-15T13:49:45Z | [
"python",
"regex",
"python-2.7"
] |
'module' object has no attribute 'corrplot' | 40,059,642 | <pre><code>import seaborn as sns
import matplotlib.pyplot as plt
sns.corrplot(rets,annot=False,diag_names=False)
</code></pre>
<p>I get this error after I call the function above...don't know whats going on</p>
<pre><code>AttributeError Traceback (most recent call last)
<ipython-input-3... | 0 | 2016-10-15T13:32:30Z | 40,059,701 | <p>The <code>corrplot</code> function was deprecated in seaborn version v0.6: <a href="https://seaborn.github.io/whatsnew.html#other-additions-and-changes" rel="nofollow">https://seaborn.github.io/whatsnew.html#other-additions-and-changes</a></p>
<p>Note that the function actually still exists in the seaborn codebase,... | 1 | 2016-10-15T13:38:43Z | [
"python",
"seaborn"
] |
How can I select and order items based on a subquery? | 40,059,682 | <p>I have the following models in Django:</p>
<pre><code>class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
country = models.ForeignKey(Country)
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = ... | 0 | 2016-10-15T13:36:55Z | 40,060,051 | <p>Try this</p>
<pre><code>Author.objects.all().annotate(s=Min('book__pubdate')).order_by('s')
</code></pre>
<p>When if some author dont have books</p>
<pre><code>Author.objects.exclude(book__pubdate__isnull=True).annotate(s=Min('book__pubdate')).order_by('s')
</code></pre>
| 1 | 2016-10-15T14:11:10Z | [
"python",
"sql",
"django",
"django-models",
"django-orm"
] |
Using Dictionary with list manipulation | 40,059,862 | <p>How do you use dictionary to find the index in the elements of the list however it should return the index of the same element.</p>
| 0 | 2016-10-15T13:52:53Z | 40,059,899 | <p>This will work :</p>
<pre><code> text = "I like cheese bcoz cheese in great"
hash = {}
words = text.split(" ")
for i in range(1:len(words)):
word = words[i]
if word not in hash.keys():
hash[word] = i
for word in words:
print hash[word]
</code></pre>
| 0 | 2016-10-15T13:55:54Z | [
"python"
] |
Using Dictionary with list manipulation | 40,059,862 | <p>How do you use dictionary to find the index in the elements of the list however it should return the index of the same element.</p>
| 0 | 2016-10-15T13:52:53Z | 40,059,919 | <p>Try this:</p>
<pre><code>l = "I like cheese because cheese is great".split()
d = {}
count = 0
for word in l:
if word not in d.keys():
count += 1
d[i] = count
for word in l:
print(d[word], end=",")
print()
</code></pre>
| 0 | 2016-10-15T13:58:05Z | [
"python"
] |
Using Dictionary with list manipulation | 40,059,862 | <p>How do you use dictionary to find the index in the elements of the list however it should return the index of the same element.</p>
| 0 | 2016-10-15T13:52:53Z | 40,060,088 | <p>This is an alternative:</p>
<pre><code>text = "I like cheese because cheese is great"
d = {v:k for k,v in enumerate(text.split(), 1)}
print(d)
</code></pre>
| 0 | 2016-10-15T14:14:54Z | [
"python"
] |
Import settings from the file | 40,059,890 | <p>I would like to import settings from a yaml file, but make them available as regular variables in the current context.</p>
<p>for example I may have a file:</p>
<pre><code>param1: 12345
param2: test11
param3:
a: 4
b: 7
c: 9
</code></pre>
<p>And I would like to have variables <code>param1</code>, <co... | 4 | 2016-10-15T13:55:06Z | 40,059,917 | <p>You can use <code>locals()['newvarname'] = 12345</code> to create a new variable.
And you can just read your file and fill in this structure as you'd like.</p>
<p>You may write a function to call it and import settings:</p>
<pre><code>import sys
import yaml
def get_settings(filename):
flocals = sys._getframe... | 0 | 2016-10-15T13:57:40Z | [
"python",
"yaml"
] |
Import settings from the file | 40,059,890 | <p>I would like to import settings from a yaml file, but make them available as regular variables in the current context.</p>
<p>for example I may have a file:</p>
<pre><code>param1: 12345
param2: test11
param3:
a: 4
b: 7
c: 9
</code></pre>
<p>And I would like to have variables <code>param1</code>, <co... | 4 | 2016-10-15T13:55:06Z | 40,060,005 | <p>Even though the trick is great in @baldr's answer, I suggest moving the variable assignments out of the function for better readability. Having a function change its caller's context seems very hard to remember and maintain. So, </p>
<pre><code>import yaml
def get_settings(filename):
with open(filename, 'r') a... | 1 | 2016-10-15T14:07:13Z | [
"python",
"yaml"
] |
Changing path for running Python code via Java | 40,059,893 | <p>I implemented Python app, and Java app.
Let's assume that my Python app is returned True as a result.</p>
<p>I would like to run Python app via Java app, receive the results from Python app into my Java app and make additional calculations in my Java app.</p>
<p>I use Process in Java for this mission.
In my exampl... | 0 | 2016-10-15T13:55:19Z | 40,063,861 | <p>You can try <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html" rel="nofollow">ProcessBuilder</a> which allows you to set the working directory. Something like:</p>
<pre><code>ProcessBuilder pb = new ProcessBuilder(program, argument);
pb.directory(new File("path/to/python/directory"));... | 0 | 2016-10-15T20:26:18Z | [
"java",
"python"
] |
Django - Delay in creating database entry | 40,059,955 | <p>I have a Django app where I create a db entry in the view. I then want to perform background processing on the new entry. Instead of sending the created object to the task, I send the object's id then the background task can fetch the db object as explained <a href="http://stackoverflow.com/questions/15079176/should... | 0 | 2016-10-15T14:02:16Z | 40,060,305 | <p>Try this</p>
<pre><code>from django.db import transaction
with transaction.atomic():
instance = MyModel.objects.create(**kwargs)
tasks.my_task.delay(instance.id)
</code></pre>
| 2 | 2016-10-15T14:33:25Z | [
"python",
"django",
"postgresql"
] |
Mean tensor product | 40,059,979 | <p>I have another question which is related to my last problem( <a href="http://stackoverflow.com/questions/40044714/python-tensor-product">Python tensor product</a>). There I found a mistake in my calculation. With np.tensordot I am calculating the following equation:
<a href="https://i.stack.imgur.com/pykbw.png" rel=... | 1 | 2016-10-15T14:04:55Z | 40,069,485 | <p>Well you can do that efficiently with a combination of <code>np.tensordot</code> and <code>np.einsum</code>, like so -</p>
<pre><code>serc = np.einsum('ilm,ilm->i',re,np.tensordot(re,wtensor,axes=[(1,2),(0,1)]))
</code></pre>
| 1 | 2016-10-16T10:57:53Z | [
"python",
"numpy",
"numpy-einsum"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.